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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
use darling::FromMeta;
use proc_macro::TokenStream;
use quote::quote;
use syn::{
    parse_macro_input, parse_str, AttributeArgs, Block, FnArg, Ident, ItemFn, Pat, ReturnType, Type,
};

#[derive(FromMeta)]
struct MacroArgs {
    #[darling(default)]
    name: Option<String>,
    #[darling(default)]
    unbound: bool,
    #[darling(default)]
    size: Option<usize>,
    #[darling(default)]
    time: Option<u64>,
    #[darling(default)]
    key: Option<String>,
    #[darling(default)]
    convert: Option<String>,
    #[darling(default)]
    result: bool,
    #[darling(default)]
    option: bool,
    #[darling(default, rename = "type")]
    cache_type: Option<String>,
    #[darling(default, rename = "create")]
    cache_create: Option<String>,
}

/// # Attributes
/// - **Cache Name:** Use `name = "CACHE_NAME"` to specify the name for the generated cache.
/// - **Cache Type:** The default cache type is `UnboundCache`.
/// You specify which of the built-in cache types to use with `unbound`, `size = cache_size`, or `time = lifetime_in_seconds`
/// - **Cache Create:** You can specify the cache creation with `create = "{ CacheType::new() }"`.
/// - **Custom Cache Type:** You can use `type = "CacheType"` to specify the type of cache to use.
/// This requires create to also be set.
/// - **Cache Key:** Use `key = "KeyType"` to specify what type to use for the cache key.
/// This requires convert to also be set.
/// - **Cache Key Convert:** Use `convert = "{ convert_inputs_to_key }"`.
/// This requires either key or type to also be set.
/// - **Caching Result/Option:** If your function returns a `Result` or `Option`
/// you may want to use `result` or `option` to only cache when the output is `Ok` or `Some`
/// ## Note
/// The `type`, `create`, `key`, and `convert` attributes must be in a `String`
/// This is because darling, which is used for parsing the attributes, does not support parsing attributes into `Type` or `Block`.
#[proc_macro_attribute]
pub fn cached(args: TokenStream, input: TokenStream) -> TokenStream {
    let attr_args = parse_macro_input!(args as AttributeArgs);
    let args = match MacroArgs::from_list(&attr_args) {
        Ok(v) => v,
        Err(e) => {
            return TokenStream::from(e.write_errors());
        }
    };
    let input = parse_macro_input!(input as ItemFn);

    // pull out the parts of the input
    let _attributes = input.attrs;
    let visibility = input.vis;
    let signature = input.sig;
    let body = input.block;

    // pull out the parts of the function signature
    let fn_ident = signature.ident.clone();
    let inputs = signature.inputs.clone();
    let output = signature.output.clone();
    let asyncness = signature.asyncness.clone();

    // pull out the names and types of the function inputs
    let input_tys = inputs
        .iter()
        .map(|input| match input {
            FnArg::Receiver(_) => panic!("methods (functions taking 'self') are not supported"),
            FnArg::Typed(pat_type) => pat_type.ty.clone(),
        })
        .collect::<Vec<Box<Type>>>();

    let input_names = inputs
        .iter()
        .map(|input| match input {
            FnArg::Receiver(_) => panic!("methods (functions taking 'self') are not supported"),
            FnArg::Typed(pat_type) => pat_type.pat.clone(),
        })
        .collect::<Vec<Box<Pat>>>();

    // pull out the output type
    let output_ty = match &output {
        ReturnType::Default => quote! {()},
        ReturnType::Type(_, ty) => quote! {#ty},
    };

    // make the cache identifier
    let cache_ident = match args.name {
        Some(name) => Ident::new(&name, fn_ident.span()),
        None => Ident::new(&fn_ident.to_string().to_uppercase(), fn_ident.span()),
    };

    // make the cache key type and block that converts the inputs into the key type
    let (cache_key_ty, key_convert_block) = match (&args.key, &args.convert, &args.cache_type) {
        (Some(key_str), Some(convert_str), _) => {
            let cache_key_ty = parse_str::<Type>(key_str).expect("unable to parse cache key type");

            let key_convert_block =
                parse_str::<Block>(convert_str).expect("unable to parse key convert block");

            (quote! {#cache_key_ty}, quote! {#key_convert_block})
        }
        (None, Some(convert_str), Some(_)) => {
            let key_convert_block =
                parse_str::<Block>(convert_str).expect("unable to parse key convert block");

            (quote! {}, quote! {#key_convert_block})
        }
        (None, None, _) => (
            quote! {(#(#input_tys),*)},
            quote! {(#(#input_names.clone()),*)},
        ),
        (Some(_), None, _) => panic!("key requires convert to be set"),
        (None, Some(_), None) => panic!("convert requires key or type to be set"),
    };

    // make the cache type and create statement
    let (cache_ty, cache_create) = match (
        &args.unbound,
        &args.size,
        &args.time,
        &args.cache_type,
        &args.cache_create,
    ) {
        (true, None, None, None, None) => {
            let cache_ty = quote! {cached::UnboundCache<#cache_key_ty, #output_ty>};
            let cache_create = quote! {cached::UnboundCache::new()};
            (cache_ty, cache_create)
        }
        (false, Some(size), None, None, None) => {
            let cache_ty = quote! {cached::SizedCache<#cache_key_ty, #output_ty>};
            let cache_create = quote! {cached::SizedCache::with_size(#size)};
            (cache_ty, cache_create)
        }
        (false, None, Some(time), None, None) => {
            let cache_ty = quote! {cached::TimedCache<#cache_key_ty, #output_ty>};
            let cache_create = quote! {cached::TimedCache::with_lifespan(#time)};
            (cache_ty, cache_create)
        }
        (false, None, None, None, None) => {
            let cache_ty = quote! {cached::UnboundCache<#cache_key_ty, #output_ty>};
            let cache_create = quote! {cached::UnboundCache::new()};
            (cache_ty, cache_create)
        }
        (false, None, None, Some(type_str), Some(create_str)) => {
            let cache_type = parse_str::<Type>(type_str).expect("unable to parse cache type");

            let cache_create =
                parse_str::<Block>(create_str).expect("unable to parse cache create block");

            (quote! { #cache_type }, quote! { #cache_create })
        }
        (false, None, None, Some(_), None) => panic!("type requires create to also be set"),
        (false, None, None, None, Some(_)) => panic!("create requires type to also be set"),
        _ => panic!("cache types (unbound, size, time, or type and create) are mutually exclusive"),
    };

    // make the set cache block
    let set_cache_block = match (&args.result, &args.option) {
        (false, false) => quote! { cache.cache_set(key, result.clone()); },
        (true, false) => quote! {
            match result.clone() {
                Ok(result) => { cache.cache_set(key, Ok(result)); },
                _ => {},
            }
        },
        (false, true) => quote! {
            match result.clone() {
                Some(result) => { cache.cache_set(key, Some(result)); },
                _ => {},
            }
        },
        _ => panic!("the result and option attributes are mutually exclusive"),
    };

    // put it all together
    let expanded = if asyncness.is_some() {
        quote! {
            #visibility static #cache_ident: ::cached::once_cell::sync::Lazy<::cached::async_std::sync::Mutex<#cache_ty>> = ::cached::once_cell::sync::Lazy::new(|| ::cached::async_std::sync::Mutex::new(#cache_create));
            #visibility #signature {
                use cached::Cached;
                let key = #key_convert_block;
                {
                    // check if the result is cached
                    let mut cache = #cache_ident.lock().await;
                    if let Some(result) = cache.cache_get(&key) {
                        return result.clone();
                    }
                }

                // run the function and cache the result
                async fn inner(#inputs) #output #body;
                let result = inner(#(#input_names),*).await;

                let mut cache = #cache_ident.lock().await;
                #set_cache_block

                result
            }
        }
    } else {
        quote! {
            #visibility static #cache_ident: ::cached::once_cell::sync::Lazy<std::sync::Mutex<#cache_ty>> = ::cached::once_cell::sync::Lazy::new(|| std::sync::Mutex::new(#cache_create));
            #visibility #signature {
                use cached::Cached;
                let key = #key_convert_block;
                {
                    // check if the result is cached
                    let mut cache = #cache_ident.lock().unwrap();
                    if let Some(result) = cache.cache_get(&key) {
                        return result.clone();
                    }
                }

                // run the function and cache the result
                fn inner(#inputs) #output #body;
                let result = inner(#(#input_names),*);

                let mut cache = #cache_ident.lock().unwrap();
                #set_cache_block

                result
            }
        }
    };

    expanded.into()
}