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
use proc_macro::TokenStream;
use proc_macro2::Ident;
use quote::quote;

use syn::{parse, parse_macro_input, ItemImpl};

fn snake_case_to_camel_case(s: &str) -> String {
    s.split('_')
        .enumerate()
        .map(|(i, s)| {
            if i == 0 {
                s.to_string()
            } else {
                s.chars().next().unwrap().to_uppercase().collect::<String>() + &s[1..]
            }
        })
        .collect()
}

#[proc_macro_attribute]
pub fn plugin_impl(args: TokenStream, input: TokenStream) -> TokenStream {
    let item_impl = parse_macro_input!(input as ItemImpl);
    let _ = parse_macro_input!(args as parse::Nothing);

    let struct_ident = item_impl.clone().self_ty;

    let mut method_idents: Vec<(Ident, String, bool, Option<bool>)> = vec![];

    for item in item_impl.clone().items {
        match item {
            syn::ImplItem::Method(method) => {
                let function_ident = &method.sig.ident;
                let env_is_option = if &method.sig.inputs.len() > &3 {
                    let env = &method.sig.inputs[3];
                    let env_str = quote! { #env }.to_string();

                    Some(env_str.contains("Option <"))
                } else {
                    None
                };

                let output_type = match &method.sig.output {
                    syn::ReturnType::Default => quote! { () },
                    syn::ReturnType::Type(_, ty) => quote! { #ty },
                };
                let output_type = quote! { #output_type }.to_string();
                let function_ident_str = snake_case_to_camel_case(&function_ident.to_string());
                let output_is_option = output_type.contains("Option <");

                method_idents.push((
                    function_ident.clone(),
                    function_ident_str.clone(),
                    output_is_option,
                    env_is_option,
                ));
            }
            _ => panic!("Wrong function signature"),
        }
    }

    let supported_methods =
        method_idents
            .clone()
            .into_iter()
            .enumerate()
            .map(|(_, (_, ident_str, _, _))| {
                quote! {
                  #ident_str
                }
            });

    let methods = method_idents.into_iter().enumerate().map(
        |(_, (ident, ident_str, output_is_option, env_is_option))| {
            let args = if let Some(env_is_option) = env_is_option {
                let env = if env_is_option {
                    quote! {
                      if let Some(e) = env {
                          Some(polywrap_msgpack_serde::from_slice(&e).unwrap())
                      } else {
                          None
                      }
                    }
                } else {
                    quote! {
                        if let Some(e) = env {
                          polywrap_msgpack_serde::from_slice(&e).unwrap()
                        } else {
                          panic!("Env must be defined for method '{}'", #ident_str)
                        }
                    }
                };

                quote! {
                  &polywrap_msgpack_serde::from_slice(&params).unwrap(),
                  invoker,
                  #env
                }
            } else {
                quote! {
                  &polywrap_msgpack_serde::from_slice(&params).unwrap(),
                  invoker
                }
            };

            let output = quote! {
                Ok(polywrap_msgpack_serde::to_vec(&result)?)
            };

            quote! {
                #ident_str => {
                    let result = self.#ident(
                      #args
                    )?;

                    #output
                }
            }
        },
    );

    let module_impl = quote! {
        impl polywrap_plugin::module::PluginModule for #struct_ident {
            fn _wrap_invoke(
                &mut self,
                method_name: &str,
                params: &[u8],
                env: Option<&[u8]>,
                invoker: Arc<dyn polywrap_core::invoker::Invoker>,
            ) -> Result<Vec<u8>, polywrap_plugin::error::PluginError> {
                let supported_methods = vec![#(#supported_methods),*];
                match method_name {
                    #(#methods)*
                    _ => Err(PluginError::MethodNotFoundError(method_name.to_string())),
                }
            }
        }
    };

    let from_impls = quote! {
        impl From<#struct_ident> for polywrap_plugin::package::PluginPackage<#struct_ident> {
            fn from(plugin: #struct_ident) -> polywrap_plugin::package::PluginPackage<#struct_ident> {
                let plugin_module = Arc::new(std::sync::Mutex::new(plugin));
                polywrap_plugin::package::PluginPackage::new(plugin_module, get_manifest())
            }
        }

        impl From<#struct_ident> for polywrap_plugin::wrapper::PluginWrapper<#struct_ident> {
            fn from(plugin: #struct_ident) -> polywrap_plugin::wrapper::PluginWrapper<#struct_ident> {
                let plugin_module = Arc::new(std::sync::Mutex::new(plugin));
                polywrap_plugin::wrapper::PluginWrapper::new(plugin_module)
            }
        }
    };

    quote! {
        #item_impl

        #module_impl

        #from_impls
    }
    .into()
}