croissant_macro/lib.rs
1use proc_macro::TokenStream;
2use proc_macro2::Span;
3use quote::{quote, ToTokens};
4use syn::{parse_macro_input, ItemFn, Pat};
5
6extern crate proc_macro;
7
8/// Creates a wrapper function, that can be Boxed and passed to
9/// Croissant scheduler
10/// ```
11///
12/// #[croissant]
13/// async fn hello(msg: String) {
14/// println!("{}", msg);
15/// }
16///
17/// fn main() {
18/// let mut croissant = Croissant::new();
19/// croissant
20/// .add_async_job("Hello World".to_string(), Box::new(hello_croissant));
21/// croissant.run_every(Duration::from_secs(5));
22/// croissant.run_at(NaiveTime::from_hms(12, 0, 0));
23/// thread::sleep(Duration::from_secs(100));
24/// }
25/// ```
26#[proc_macro_attribute]
27pub fn croissant(_: TokenStream, input: TokenStream) -> TokenStream {
28 // let attr = proc_macro2::TokenStream::from(a);
29 // let item = proc_macro2::TokenStream::from(i);
30 //
31 // let t: Fn = syn::parse(item.into()).unwrap();
32 // println!("{}", t);
33 // item.into()
34 // Parse the input as a function
35 let input = parse_macro_input!(input as ItemFn);
36
37 // Extract the function name and input type
38 let visibility = &input.vis;
39 let fn_name = &input.sig.ident;
40 let input_type = &input.sig.inputs;
41
42 let _pnk = input_type.iter().fold("".to_string(), |y, x| {
43 y + (format!("L: {:?}", x.to_token_stream())).as_str()
44 });
45 // panic!("{}", pnk);
46 let params: Vec<_> = input_type
47 .iter()
48 .map(|param| {
49 if let syn::FnArg::Typed(pat_type) = param {
50 if let Pat::Ident(ident) = &*pat_type.pat {
51 // if let Type::Path(type_path) = &*pat_type.ty {
52 let param_name = &ident.ident;
53 // let param_type = &type_path.path;
54
55 // You can now use param_name and param_type as needed
56
57 param_name
58 // } else {
59 // panic!("Unsupported parameter type");
60 // }
61 } else {
62 panic!("Unsupported parameter pattern");
63 }
64 } else {
65 panic!("Unsupported function argument");
66 }
67 })
68 .collect();
69
70 // panic!("{:?}", param_name);
71
72 let wrapper_name = proc_macro2::Ident::new(
73 &(fn_name.to_string() + "_croissant"),
74 Span::call_site(),
75 );
76 let expanded = quote! {
77 #input
78
79 #visibility fn #wrapper_name(#input_type) -> std::pin::Pin<std::boxed::Box<dyn std::future::Future<Output = ()> + Send + Sync>> {
80 Box::pin(#fn_name(#(#params),*))
81 }
82 };
83
84 // Return the generated code as a TokenStream
85 TokenStream::from(expanded)
86}