xladd_derive/
lib.rs

1use proc_macro::*;
2use std::collections::BTreeMap;
3use quote::quote;
4use syn::{FnArg, ItemFn};
5
6
7
8
9#[proc_macro_attribute]
10pub fn xl_func(attr: TokenStream, input: TokenStream) -> TokenStream {
11    // println!("{:?}", attr);
12    // println!("{:?}", input);
13    // println!("{:?}", input);
14
15    let item = syn::parse::<ItemFn>(input).expect("Failed to parse.");
16    let mut params = BTreeMap::new();
17    let tree = attr.into_iter().collect::<Vec<TokenTree>>();
18    for chunk in tree.as_slice().windows(3) {
19        match chunk {
20            [TokenTree::Ident(i),TokenTree::Punct(_),TokenTree::Literal(l)] => {
21                let l = l.to_string();
22                params.insert(i.to_string(),l[1..l.len()-1].to_string());
23            },
24            _ => (),
25        }
26    }
27    let name = item.sig.ident.to_string();
28    let category = if let Some(v) = params.get("category") { v } else { "" };
29    let prefix = if let Some(v) = params.get("prefix") { v } else { "xl" };
30    let rename = if let Some(v) = params.get("rename") { v } else { name.as_str() };
31    let async_function = if let Some(_) = params.get("async") { true } else { false };
32    let single_threaded = if let Some(_) = params.get("single_threaded") { true } else { true };
33    // Use `quote` to convert the syntax tree back into tokens so we can return them. Note
34    // that the tokens we're returning at this point are still just the input, we've simply
35    // converted it between a few different forms.
36    let output = &item.sig.output;
37    let func = &item.sig.ident;
38
39    let xl_function = proc_macro2::Ident::new(
40        &format!("{}_{}", prefix, rename),
41        proc_macro2::Span::call_site(),
42    );
43    let error_handler_function = proc_macro2::Ident::new(
44        &format!("_error_hndlr_{}", func),
45        proc_macro2::Span::call_site(),
46    );
47
48    let register_function = proc_macro2::Ident::new(
49        &format!("register_{}", func),
50        proc_macro2::Span::call_site(),
51    );
52    // From the signature, identify the types we handle
53    // f32,f64,i32,i64,bool,&str,&[&str],&[f64]
54    // and map them to the corresponding owned types
55
56    let typed_args = &item.sig.inputs.iter().map(|arg| match arg {
57        FnArg::Typed(typed_arg) => {
58            // Arg name
59            let arg_name = {
60                let pat = &typed_arg.pat;
61                match &**pat {
62                    syn::Pat::Ident(ident) => quote!(#ident),
63                    _ => panic!("Type not covered"),
64                }
65            };
66            // Owned type
67            let owned_type = {
68                let ty = &typed_arg.ty;
69                match &**ty {
70                    syn::Type::Path(p) => {
71                        let segment = &p.path.segments[0];
72                        let ident = &segment.ident;
73                        let p_type = if ident == "str" {
74                            quote!(String)
75                        } else {
76                            quote!(#p)
77                        };
78                        quote!( 
79                            if #arg_name.is_missing_or_null() {
80                                return Err(Box::new(xladd::variant::XLAddError::MissingArgument(stringify!(#func).to_string(),stringify!(#arg_name).to_string())));
81                            }
82                            let #arg_name = std::convert::TryInto::<#p_type>::try_into(&#arg_name)?; 
83                            log::trace!("{}:[{:?}]",stringify!(#arg_name),#arg_name);
84                        )
85                    }
86                    syn::Type::Reference(p) => {
87                        let elem = &p.elem;
88                        // Slice
89                        match &**elem {
90                            syn::Type::Slice(s) => {
91                                let elem = &s.elem;
92                                match &**elem {
93                                    syn::Type::Path(p) => {
94                                        let segment = &p.path.segments[0];
95                                        let ident = &segment.ident;
96                                        quote!( 
97                                                if #arg_name.is_missing_or_null() {
98                                                    return Err(Box::new(xladd::variant::XLAddError::MissingArgument(stringify!(#func).to_string(),stringify!(#arg_name).to_string())));
99                                                }
100                                                let #arg_name = std::convert::TryInto::<Vec<#ident>>::try_into(&#arg_name)?;
101                                                log::trace!("{}:[{:?}]",stringify!(#arg_name),#arg_name);
102                                                //let #arg_name = #arg_name.as_slice();
103                                        )
104                                    }
105                                    syn::Type::Reference(p) => {
106                                        let elem = &p.elem;
107                                        match &**elem {
108                                            syn::Type::Path(p) => {
109                                                let segment = &p.path.segments[0];
110                                                let ident = &segment.ident;
111                                                if ident == "str" {
112                                                    quote!( if #arg_name.is_missing_or_null() {
113                                                                return Err(Box::new(xladd::variant::XLAddError::MissingArgument(stringify!(#func).to_string(),stringify!(#arg_name).to_string())));
114                                                            }
115                                                            let #arg_name = std::convert::TryInto::<Vec<String>>::try_into(&#arg_name)?;
116                                                            let #arg_name = #arg_name.iter().map(AsRef::as_ref).collect::<Vec<_>>();
117                                                            log::trace!("{}:[{:?}]",stringify!(#arg_name),#arg_name);
118                                                            //let #arg_name = #arg_name.as_slice();
119                                                    )
120                                                } else {
121                                                    panic!("Only slices of &[&str] supported")
122                                                }
123                                            }
124                                            _ => panic!("Type not covered"),
125                                        }
126                                    }
127                                    _ => panic!("Type not covered"),
128                                }
129                            }
130                            syn::Type::Path(s) => {
131                                let segment = &s.path.segments[0];
132                                let ident = &segment.ident;
133                                if ident == "str" { 
134                                    quote!(
135                                        if #arg_name.is_missing_or_null() {
136                                            return Err(Box::new(xladd::variant::XLAddError::MissingArgument(stringify!(#func).to_string(),stringify!(#arg_name).to_string())));
137                                        }
138                                        let #arg_name = std::convert::TryInto::<String>::try_into(&#arg_name)?;
139                                        log::trace!("{}:[{:?}]",stringify!(#arg_name),#arg_name);
140                                       // let #arg_name = #arg_name.as_str();
141                                    )
142                                } else { 
143                                    quote!(
144                                        if #arg_name.is_missing_or_null() {
145                                            return Err(Box::new(xladd::variant::XLAddError::MissingArgument(stringify!(#func).to_string(),stringify!(#arg_name).to_string())));
146                                        }
147                                        let #arg_name = std::convert::TryInto::<#ident>::try_into(&#arg_name)?;
148                                        log::trace!("{}:[{:?}]",stringify!(#arg_name),#arg_name);
149                                        )
150                                    }
151                            }
152                            _ => panic!("Type not covered"),
153                        }
154
155                        // or Path
156                    }
157                    _ => panic!("Type not covered"),
158                }
159            };
160            // Slice converted for &[&str],&[f64]
161            (arg_name, owned_type)
162        }
163        FnArg::Receiver(_) => panic!("Free functions only"),
164    });
165
166
167    // Rerefence args
168    let reference_args = &item.sig.inputs.iter().map(|arg| match arg {
169        FnArg::Typed(typed_arg) => {
170            // Arg name
171            let arg_name = {
172                let pat = &typed_arg.pat;
173                match &**pat {
174                    syn::Pat::Ident(ident) => quote!(#ident),
175                    _ => panic!("Type not covered"),
176                }
177            };
178            // Owned type
179            let owned_type = {
180                let ty = &typed_arg.ty;
181                match &**ty {
182                    syn::Type::Path(_) => {
183                        quote!()
184                    }
185                    syn::Type::Reference(p) => {
186                        let elem = &p.elem;
187                        // Slice
188                        match &**elem {
189                            syn::Type::Slice(s) => {
190                                let elem = &s.elem;
191                                match &**elem {
192                                    syn::Type::Path(_) => {
193                                        quote!( let #arg_name = #arg_name.as_slice(); )
194                                    }
195                                    syn::Type::Reference(p) => {
196                                        let elem = &p.elem;
197                                        match &**elem {
198                                            syn::Type::Path(p) => {
199                                                let segment = &p.path.segments[0];
200                                                let ident = &segment.ident;
201                                                if ident == "str" {
202                                                    quote!( let #arg_name = #arg_name.as_slice(); )
203                                                } else {
204                                                    panic!("Only slices of &[&str] supported")
205                                                }
206                                            }
207                                            _ => panic!("Type not covered"),
208                                        }
209                                    }
210                                    _ => panic!("Type not covered"),
211                                }
212                            }
213                            syn::Type::Path(s) => {
214                                let segment = &s.path.segments[0];
215                                let ident = &segment.ident;
216                                if ident == "str" { 
217                                    quote!(let #arg_name = #arg_name.as_str(); )
218                                } else { 
219                                    quote!()
220                                    }
221                            }
222                            _ => panic!("Type not covered"),
223                        }
224
225                        // or Path
226                    }
227                    _ => panic!("Type not covered"),
228                }
229            };
230            // Slice converted for &[&str],&[f64]
231            (arg_name, owned_type)
232        }
233        FnArg::Receiver(_) => panic!("Free functions only"),
234    });
235    // Parse the doc comments
236
237    let comments = &item.attrs.iter().filter_map(|attr: &syn::Attribute| {
238        let segment = &attr.path.segments[0];
239        if segment.ident == "doc" {
240            Some(attr.tokens.to_string())
241        } else {
242            None
243        }
244    });
245    let args = typed_args
246        .clone()
247        .filter_map(|(name, _)| {
248            let name = name.to_string();
249            comments.clone().find_map(|v| {
250                if v.starts_with(&format!("= \" * {} -", name)) {
251                    let v = &v[name.len() + 9..v.len() - 1];
252                    Some(quote! {#v})
253                } else {
254                    None
255                }
256            })
257        })
258        .collect::<Vec<_>>();
259    let ret = comments.clone().find_map(|v| {
260        if v.starts_with("= \" * ret -") {
261            let v = &v[12..v.len() - 1];
262            Some(v.to_owned())
263        } else {
264            None
265        }
266    });
267    let docs = comments.clone().find_map(|v| {
268        if !v.starts_with("= \" *") {
269            let v = &v[4..v.len() - 1];
270            Some(v.to_owned())
271        } else {
272            None
273        }
274    });
275
276    let docs_ret = vec![
277        if ret.is_some() {
278            ret.as_ref().unwrap()
279        } else {
280            ""
281        },
282        if docs.is_some() {
283            docs.as_ref().unwrap()
284        } else {
285            ""
286        },
287    ]
288    .join(" and ");
289    // Return type convert back to variant
290    let output = {
291        match output {
292            syn::ReturnType::Default => quote! {},
293            syn::ReturnType::Type(_, path) => match &**path {
294                syn::Type::Path(path) => {
295                    let segment = &path.path.segments[0];
296                    if segment.ident == "Result" {
297                        let args = &segment.arguments;
298                        match args {
299                            syn::PathArguments::AngleBracketed(generic_args) => {
300                                let arg0 = &generic_args.args[0];
301                                match &*arg0 {
302                                    syn::GenericArgument::Type(path) => match path {
303                                        syn::Type::Tuple(tuple) => {
304                                            let elems = &tuple.elems[0];
305                                            match &*elems {
306                                                syn::Type::Path(path) => {
307                                                    let segment = &path.path.segments[0];
308                                                    if segment.ident == "Vec" {
309                                                        let args = &segment.arguments;
310                                                        match &*args {
311                                                            syn::PathArguments::AngleBracketed(generic_args) => {
312                                                                let arg0 = &generic_args.args[0];
313                                                                match &*arg0 {
314                                                                    syn::GenericArgument::Type(path) => {
315                                                                        match path {
316                                                                            syn::Type::Path(p) => {
317                                                                                if p.path.segments[0].ident == "String" {
318                                                                                    quote! {Ok(Variant::from(&(res.0.iter().map(AsRef::as_ref).collect::<Vec<_>>().as_slice(),res.1)))}
319                                                                                } else {
320                                                                                    quote! {Ok(Variant::from(&(res.0.as_slice(),res.1)))}
321                                                                                }
322                                                                            },
323                                                                            _ => panic!("Expected a type of f64,u32,bool,String")
324                                                                        }
325 
326                                                                    },
327                                                                    _ =>  panic!("Expected a simple type after a vec"),
328
329                                                                }
330                                                            },
331                                                                syn::PathArguments::Parenthesized(_) => {
332                                                                    quote! {Ok(Variant::from(true))}
333                                                                },
334                                                                syn::PathArguments::None => panic!("Unhandled type for result0"),
335                                                        }
336//                                                        quote! {Ok(Variant::from(&(res.0.as_slice(),res.1)))}
337                                                    } else {
338                                                        quote! {Ok(Variant::from(res))}
339                                                    }        
340                                                },
341                                                _ => panic!("Tuple returned must of <Vec<f64>,Dimension(usize)>")
342
343                                            }
344                                        }
345                                        syn::Type::Path(_) => {
346                                            quote! {Ok(Variant::from(res))}
347                                        },
348                                        _ => panic!("XL functions must return a basic type of f64,i64,u32,i32,bool or a tuple of (Vec<f64>,Dimension(usize))")
349                                    },
350                                    _ => panic!("XL functions must return a basic type of f64,i64,u32,i32,bool or a tuple of (Vec<f64>,Dimension(usize))")
351                                }
352                            }
353                            syn::PathArguments::Parenthesized(_) => {
354                                quote! {Ok(Variant::from(true))}
355                            }
356                            syn::PathArguments::None => quote! {} //panic!("XL functions must return a basic type of f64,i64,u32,i32,bool or a tuple of (Vec<f64>,Dimension(usize))")
357
358                        }
359                    } else {
360                        panic!("XL functions must return a Result<TYPE,Error>. Error can be coerced into a Box<std::error::Error>")
361                    }
362                }
363                _ => panic!("Unhandled type"),
364            },
365        }
366    };
367    // Now collate
368    let lpx_oper_args = typed_args
369        .clone()
370        .map(|(name, _)| quote!(#name: LPXLOPER12))
371        .collect::<Vec<_>>();
372    let variant_args = typed_args
373        .clone()
374        .map(|(name, _)| quote!(#name: xladd::variant::Variant))
375        .collect::<Vec<_>>();
376    let to_variant = typed_args
377        .clone()
378        .map(|(name, _)| quote!(let #name = xladd::variant::Variant::from(#name);))
379        .collect::<Vec<_>>();
380    let caller_args = typed_args
381        .clone()
382        .map(|(name, _)| quote!(#name))
383        .collect::<Vec<_>>();
384    let caller_args_str = typed_args
385        .clone()
386        .map(|(name, _)| name.to_string())
387        .collect::<Vec<_>>()
388        .join(",");
389    let mut q_args = typed_args
390        .clone()
391        .map(|(_, _)| "Q")
392        .collect::<Vec<_>>()
393        .join("");
394    // Mark function as async
395    if async_function {
396        q_args.insert(0,'>');
397        q_args.push('X');
398    } else {
399        // Return type is a variant
400        q_args.push('Q');
401    }
402    // not_thread_safe
403    if !(single_threaded || async_function) { q_args.push('$'); };
404    let convert_to_owned_rust_types = typed_args
405        .clone()
406        .map(|(_, owned_type)| owned_type)
407        .collect::<Vec<_>>();
408
409    let convert_to_ref_rust_types = reference_args
410        .clone()
411        .map(|(_, owned_type)| owned_type)
412        .collect::<Vec<_>>();
413
414        let xl_function_str = xl_function.to_string();
415    // Async function
416    if async_function {
417        let wrapper = quote! {
418             // Error handler
419             fn #error_handler_function(#(#variant_args),*, return_handle: LPXLOPER12) -> Result<Variant, Box<dyn std::error::Error>> {
420                log::trace!("{} called [*ASYNC*] ..waiting for results",stringify!(#xl_function));
421                #(#convert_to_owned_rust_types)*;
422                let raw_ptr = xladd::variant::XLOPERPtr(return_handle);
423                std::thread::spawn(move ||{
424                    #(#convert_to_ref_rust_types)*;
425                    match #func(#(#caller_args),*) {
426                        Ok(v) => {
427                            log::trace!("Results [{:?}]",v);
428                            xladd::entrypoint::excel12(
429                                                xladd::xlcall::xlAsyncReturn,
430                                                &mut [Variant::from(raw_ptr), v]);
431                        }
432                        Err(e) => {
433                            log::error!("Error {:?}",e.to_string());
434                            xladd::entrypoint::excel12(
435                                                xladd::xlcall::xlAsyncReturn,
436                                                &mut [Variant::from(raw_ptr), Variant::from(e.to_string())]);
437                        }
438                    }
439                });
440                Ok(Variant::default())
441            }
442            // Excel function
443            #[no_mangle]
444            pub extern "stdcall" fn #xl_function(#(#lpx_oper_args),* ,return_handle: LPXLOPER12) {
445                #(#to_variant)*
446                match #error_handler_function(#(#caller_args),*, return_handle) {
447                    Ok(_) => (),
448                    Err(e) => {
449                        log::error!("{}",e.to_string());
450                        let raw_ptr = xladd::variant::XLOPERPtr(return_handle);
451                        xladd::entrypoint::excel12(
452                            xladd::xlcall::xlAsyncReturn,
453                            &mut [xladd::variant::Variant::from(raw_ptr), xladd::variant::Variant::from(e.to_string())],
454                        );
455                    },
456                }
457            }
458
459            pub (crate) fn #register_function(reg: &xladd::registrator::Reg) {
460                reg.add(#xl_function_str,#q_args,#caller_args_str,#category,#docs_ret,&[#(#args),*]);
461            }
462            // User function
463            #item
464        };
465        wrapper.into()
466    } else {
467        let wrapper = quote! {
468            // Error handler
469            fn #error_handler_function(#(#variant_args),*) -> Result<xladd::variant::Variant, Box<dyn std::error::Error>> {
470                log::trace!("{} called",stringify!(#xl_function));
471                #(#convert_to_owned_rust_types)*;
472                #(#convert_to_ref_rust_types)*;
473                let res = std::panic::catch_unwind(|| #func(#(#caller_args),*));
474                match res {
475                    Ok(result) => {
476                        let res = result?;
477                        log::trace!("Results [{:?}]",res);
478                        #output        
479                    }
480                    Err(_) => {
481                        log::error!("Unexpected error while calling function"); 
482                        Err("Error when trying to execute function, check for invalid values, ranges, or #n/a".into())
483                    }
484                }
485            }
486            // Excel function
487            #[no_mangle]
488            pub extern "stdcall" fn #xl_function(#(#lpx_oper_args),*)  -> LPXLOPER12 {
489                #(#to_variant)*
490                match #error_handler_function(#(#caller_args),*) {
491                    Ok(v) => LPXLOPER12::from(v),
492                    Err(e) => {
493                        log::error!("{}",e.to_string());
494                        LPXLOPER12::from(xladd::variant::Variant::from(e.to_string().as_str()))
495                    },
496                }
497            }
498
499            pub (crate) fn #register_function(reg: &xladd::registrator::Reg) {
500                reg.add(#xl_function_str,#q_args,#caller_args_str,#category,#docs_ret,&[#(#args),*]);
501            }
502            // User function
503            #item
504        };
505    wrapper.into()
506    }   
507}