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
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
#![crate_type = "proc-macro"]
#![allow(unused_imports)]
use syn::{self, parse_macro_input, spanned::Spanned, ItemFn};
use proc_macro::TokenStream;
use quote::{self, ToTokens};
#[cfg(not(feature = "full"))]
mod store {
use proc_macro::TokenStream;
pub fn construct_cache(
attr: &TokenStream,
key_type: proc_macro2::TokenStream,
value_type: proc_macro2::TokenStream,
) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
if !attr.is_empty() {
return (
syn::Error::new_spanned(proc_macro2::TokenStream::from(attr.clone()),
"memoize error: Attributes are specified, but the feature 'full' is not enabled! To fix this, compile with `--features=full`.",
)
.to_compile_error(),
proc_macro2::TokenStream::new(),
);
}
(
quote::quote! { std::collections::HashMap<#key_type, #value_type> },
quote::quote! { std::collections::HashMap::new() },
)
}
pub fn cache_access_methods(
_attr: &TokenStream,
) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
(quote::quote! { insert }, quote::quote! { get })
}
}
#[cfg(feature = "full")]
mod store {
use proc_macro::TokenStream;
use syn::{parse as p, Expr};
#[derive(Default, Clone)]
pub(crate) struct CacheOptions {
lru_max_entries: Option<usize>,
pub(crate) time_to_live: Option<Expr>,
}
#[derive(Clone)]
enum CacheOption {
LRUMaxEntries(usize),
TimeToLive(Expr),
}
syn::custom_keyword!(Capacity);
syn::custom_keyword!(TimeToLive);
syn::custom_punctuation!(Colon, :);
impl p::Parse for CacheOption {
fn parse(input: p::ParseStream) -> syn::Result<Self> {
let la = input.lookahead1();
if la.peek(Capacity) {
let _: Capacity = input.parse().unwrap();
let _: Colon = input.parse().unwrap();
let cap: syn::LitInt = input.parse().unwrap();
return Ok(CacheOption::LRUMaxEntries(cap.base10_parse()?));
}
if la.peek(TimeToLive) {
let _: TimeToLive = input.parse().unwrap();
let _: Colon = input.parse().unwrap();
let cap: syn::Expr = input.parse().unwrap();
return Ok(CacheOption::TimeToLive(cap));
}
Err(la.error())
}
}
impl p::Parse for CacheOptions {
fn parse(input: p::ParseStream) -> syn::Result<Self> {
let f: syn::punctuated::Punctuated<CacheOption, syn::Token![,]> =
input.parse_terminated(CacheOption::parse)?;
let mut opts = Self::default();
for opt in f {
match opt {
CacheOption::LRUMaxEntries(cap) => opts.lru_max_entries = Some(cap),
CacheOption::TimeToLive(sec) => opts.time_to_live = Some(sec),
}
}
Ok(opts)
}
}
pub fn construct_cache(
attr: &TokenStream,
key_type: proc_macro2::TokenStream,
value_type: proc_macro2::TokenStream,
) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
let options: CacheOptions = syn::parse(attr.clone()).unwrap();
let value_type = match options.time_to_live {
None => quote::quote! {#value_type},
Some(_) => quote::quote! {(std::time::Instant, #value_type)},
};
match options.lru_max_entries {
None => (
quote::quote! { std::collections::HashMap<#key_type, #value_type> },
quote::quote! { std::collections::HashMap::new() },
),
Some(cap) => (
quote::quote! { ::memoize::lru::LruCache<#key_type, #value_type> },
quote::quote! { ::memoize::lru::LruCache::new(#cap) },
),
}
}
pub fn cache_access_methods(
attr: &TokenStream,
) -> (proc_macro2::TokenStream, proc_macro2::TokenStream) {
let options: CacheOptions = syn::parse(attr.clone()).unwrap();
match options.lru_max_entries {
None => (quote::quote! { insert }, quote::quote! { get }),
Some(_) => (quote::quote! { put }, quote::quote! { get }),
}
}
}
#[proc_macro_attribute]
pub fn memoize(attr: TokenStream, item: TokenStream) -> TokenStream {
let func = parse_macro_input!(item as ItemFn);
let sig = &func.sig;
let fn_name = &sig.ident.to_string();
let renamed_name = format!("memoized_original_{}", fn_name);
let map_name = format!("memoized_mapping_{}", fn_name);
let input_types: Vec<Box<syn::Type>>;
let input_names: Vec<Box<syn::Pat>>;
let return_type;
match check_signature(sig) {
Ok((t, n)) => {
input_types = t;
input_names = n;
}
Err(e) => return e.to_compile_error().into(),
}
let input_tuple_type = quote::quote! { (#(#input_types),*) };
match &sig.output {
syn::ReturnType::Default => return_type = quote::quote! { () },
syn::ReturnType::Type(_, ty) => return_type = ty.to_token_stream(),
}
let store_ident = syn::Ident::new(&map_name.to_uppercase(), sig.span());
let (cache_type, cache_init) = store::construct_cache(&attr, input_tuple_type, return_type);
let store = quote::quote! {
::memoize::lazy_static::lazy_static! {
static ref #store_ident : std::sync::Mutex<#cache_type> =
std::sync::Mutex::new(#cache_init);
}
};
let mut renamed_fn = func.clone();
renamed_fn.sig.ident = syn::Ident::new(&renamed_name, func.sig.span());
let memoized_id = &renamed_fn.sig.ident;
let syntax_names_tuple = quote::quote! { (#(#input_names),*) };
let syntax_names_tuple_cloned = quote::quote! { (#(#input_names.clone()),*) };
let (insert_fn, get_fn) = store::cache_access_methods(&attr);
#[cfg(feature = "full")]
let memoizer = {
let options: store::CacheOptions = syn::parse(attr.clone().into()).unwrap();
match options.time_to_live {
None => quote::quote! {
#sig {
{
let mut hm = &mut #store_ident.lock().unwrap();
if let Some(r) = hm.#get_fn(&#syntax_names_tuple_cloned) {
return r.clone();
}
}
let r = #memoized_id(#(#input_names.clone()),*);
let mut hm = &mut #store_ident.lock().unwrap();
hm.#insert_fn(#syntax_names_tuple, r.clone());
r
}
},
Some(ttl) => quote::quote! {
#sig {
{
let mut hm = &mut #store_ident.lock().unwrap();
if let Some((last_updated, r)) = hm.#get_fn(&#syntax_names_tuple_cloned) {
if last_updated.elapsed() < #ttl {
return r.clone();
}
}
}
let r = #memoized_id(#(#input_names.clone()),*);
let mut hm = &mut #store_ident.lock().unwrap();
hm.#insert_fn(#syntax_names_tuple, (std::time::Instant::now(), r.clone()));
r
}
},
}
};
#[cfg(not(feature = "full"))]
let memoizer = quote::quote! {
#sig {
{
let mut hm = &mut #store_ident.lock().unwrap();
if let Some(r) = hm.#get_fn(&#syntax_names_tuple_cloned) {
return r.clone();
}
}
let r = #memoized_id(#(#input_names.clone()),*);
let mut hm = &mut #store_ident.lock().unwrap();
hm.#insert_fn(#syntax_names_tuple, r.clone());
r
}
};
(quote::quote! {
#store
#renamed_fn
#memoizer
})
.into()
}
fn check_signature(
sig: &syn::Signature,
) -> Result<(Vec<Box<syn::Type>>, Vec<Box<syn::Pat>>), syn::Error> {
if let syn::FnArg::Receiver(_) = sig.inputs[0] {
return Err(syn::Error::new(
sig.span(),
"Cannot memoize method (self-receiver) without arguments!",
));
}
let mut types = vec![];
let mut names = vec![];
for a in &sig.inputs {
if let syn::FnArg::Typed(ref arg) = a {
types.push(arg.ty.clone());
if let syn::Pat::Ident(_) = &*arg.pat {
names.push(arg.pat.clone());
} else {
return Err(syn::Error::new(
sig.span(),
"Cannot memoize arbitrary patterns!",
));
}
}
}
Ok((types, names))
}
#[cfg(test)]
mod tests {}