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
use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use venial::{Declaration, Error, Function};

/// An attribute macro that performs "Ok-wrapping" on the return value of a `fn` item.
/// This is compatible with [`Result`], [`Option`], [`ControlFlow`], and any type that
/// implements the unstable [`std::ops::Try`] trait.
///
/// Using this macro is equivalent to wrapping the body of a fn in a try block.
///
/// Nightly:
/// ```ignore
/// fn fallible_fn(x: T) -> Result<U, E> {
///     try {
///         let a = do_one(x)?;
///         let b = do_two(a)?;
///         b
///     }
/// }
/// ```
///
/// With tryvial:
/// ```ignore
/// #[tryvial]
/// fn fallible_fn(x: T) -> Result<U, E> {
///     let a = do_one(x)?;
///     let b = do_two(a)?;
///     b
/// }
/// ```
///
/// [`ControlFlow`]: core::ops::ControlFlow
#[proc_macro_attribute]
pub fn tryvial(_attr: TokenStream, item: TokenStream) -> TokenStream {
    impl_tryvial(item.into())
        .unwrap_or_else(|e| e.to_compile_error())
        .into()
}

fn impl_tryvial(input: TokenStream2) -> Result<TokenStream2, Error> {
    let decl = venial::parse_declaration(input)?;
    let Function {
        attributes,
        vis_marker,
        qualifiers,
        tk_fn_keyword,
        name,
        generic_params,
        tk_params_parens: _,
        params,
        where_clause,
        tk_return_arrow: _,
        return_ty,
        tk_semicolon: _,
        body,
    } = match decl {
        Declaration::Function(item) => item,
        _ => Err(Error::new("`#[tryvial]` is supported only on `fn` items"))?,
    };

    let body = body.ok_or(Error::new(
        "`#[tryvial]` can only be used on functions with a body",
    ))?;

    let return_ty = return_ty.map_or_else(|| quote! { () }, |ty| quote! { #ty });

    Ok(quote! {
        #(#attributes)*
        #vis_marker #qualifiers #tk_fn_keyword #name #generic_params ( #params ) -> #return_ty
        #where_clause
        {
            ::core::iter::empty().try_fold(#body, |_, __x: ::core::convert::Infallible| match __x {})
        }
    })
}