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
extern crate proc_macro;

#[macro_use]
extern crate syn;

#[macro_use]
extern crate quote;

use proc_macro::TokenStream;

type TokenStream2 = proc_macro2::TokenStream;

/// Declare the function to be an effectful computation whose effect type is the coproduct of the arguments
///
/// This macro transforms the function like what `async fn` does
#[proc_macro_attribute]
pub fn eff(attr: TokenStream, item: TokenStream) -> TokenStream {
    use syn::parse::Parser;
    use syn::punctuated::Punctuated;

    let effects_parser = Punctuated::<syn::Type, Token![,]>::parse_terminated;
    let types = effects_parser
        .parse(attr)
        .expect("failed to parse attribute");

    let item: syn::Item = syn::parse(item).expect("failed to parse item");

    if let syn::Item::Fn(mut func) = item {
        let mut ret = TokenStream2::new();

        let effects_type_name = quote! {
            eff::Coproduct![#types]
        };

        func.decl.output = syn::parse2(match func.decl.output {
            syn::ReturnType::Default => quote! {
                -> impl eff::Effectful<Output = (), Effect = #effects_type_name>
            },
            syn::ReturnType::Type(arrow, ty) => quote! {
                #arrow impl eff::Effectful<Output = #ty, Effect = #effects_type_name>
            },
        })
        .unwrap();

        let original_block = func.block;
        func.block = syn::parse2(quote! {
            {
                eff::from_generator(static move || {
                    if false {
                        yield unreachable!();
                    }

                    #original_block
                })
            }
        })
        .unwrap();

        // supress warning
        ret.extend(quote! {
            #[allow(unreachable_code)]
            #func
        });

        ret.into()
    } else {
        panic!("item must be a function");
    }
}