cachelito-macro-utils 0.10.1

Shared utilities for cachelito procedural macros
Documentation
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
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
//! Shared utilities for cachelito procedural macros
//!
//! This crate provides common parsing and code generation utilities
//! used by both `cachelito-macros` and `cachelito-async-macros`.

use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use syn::{punctuated::Punctuated, Expr, MetaNameValue, Token};

/// List of supported eviction policies
static POLICIES: &[&str] = &["fifo", "lru", "lfu", "arc"];

pub fn policies_str_with_separator(separator: &str) -> String {
    POLICIES
        .iter()
        .map(|p| format!("\"{}\"", p))
        .collect::<Vec<_>>()
        .join(separator)
}

/// Parsed macro attributes for async caching
pub struct AsyncCacheAttributes {
    pub limit: TokenStream2,
    pub policy: TokenStream2,
    pub ttl: TokenStream2,
    pub custom_name: Option<String>,
    pub max_memory: TokenStream2,
}

impl Default for AsyncCacheAttributes {
    fn default() -> Self {
        Self {
            limit: quote! { Option::<usize>::None },
            policy: quote! { "fifo" },
            ttl: quote! { Option::<u64>::None },
            custom_name: None,
            max_memory: quote! { Option::<usize>::None },
        }
    }
}

/// Parsed macro attributes for sync caching
pub struct SyncCacheAttributes {
    pub limit: TokenStream2,
    pub policy: TokenStream2,
    pub ttl: TokenStream2,
    pub scope: TokenStream2,
    pub custom_name: Option<String>,
    pub max_memory: TokenStream2,
}

impl Default for SyncCacheAttributes {
    fn default() -> Self {
        Self {
            limit: quote! { None },
            policy: quote! { cachelito_core::EvictionPolicy::FIFO },
            ttl: quote! { None },
            scope: quote! { cachelito_core::CacheScope::Global },
            custom_name: None,
            max_memory: quote! { None },
        }
    }
}

/// Parse the `limit` attribute
pub fn parse_limit_attribute(nv: &MetaNameValue) -> TokenStream2 {
    match &nv.value {
        Expr::Lit(expr_lit) => match &expr_lit.lit {
            syn::Lit::Int(lit_int) => {
                let val = lit_int
                    .base10_parse::<usize>()
                    .expect("limit must be a positive integer");
                quote! { Some(#val) }
            }
            _ => quote! { compile_error!("Invalid literal for `limit`: expected integer") },
        },
        _ => quote! { compile_error!("Invalid syntax for `limit`: expected `limit = <integer>`") },
    }
}

/// Parse the `policy` attribute and return the string value
pub fn parse_policy_attribute(nv: &MetaNameValue) -> Result<String, TokenStream2> {
    match &nv.value {
        Expr::Lit(expr_lit) => match &expr_lit.lit {
            syn::Lit::Str(s) => {
                let val = s.value();
                // Validate the policy value
                if POLICIES.contains(&val.as_str()) {
                    Ok(val)
                } else {
                    let policies = policies_str_with_separator(", ");
                    let err_msg = format!("Invalid policy: expected one of {}", policies);
                    Err(quote! { compile_error!(#err_msg) })
                }
            }
            _ => Err(quote! { compile_error!("Invalid literal for `policy`: expected string") }),
        },
        _ => {
            let policies = policies_str_with_separator("|");
            let err_msg = format!(
                "Invalid syntax for `policy`: expected `policy = \"{}\"`",
                policies
            );
            Err(quote! {
                compile_error!(#err_msg)
            })
        }
    }
}

/// Parse the `ttl` attribute
pub fn parse_ttl_attribute(nv: &MetaNameValue) -> TokenStream2 {
    match &nv.value {
        Expr::Lit(expr_lit) => match &expr_lit.lit {
            syn::Lit::Int(lit_int) => {
                let val = lit_int
                    .base10_parse::<u64>()
                    .expect("ttl must be a positive integer (seconds)");
                quote! { Some(#val) }
            }
            _ => quote! { compile_error!("Invalid literal for `ttl`: expected integer (seconds)") },
        },
        _ => quote! { compile_error!("Invalid syntax for `ttl`: expected `ttl = <integer>`") },
    }
}

/// Parse the `name` attribute
pub fn parse_name_attribute(nv: &MetaNameValue) -> Option<String> {
    match &nv.value {
        Expr::Lit(expr_lit) => match &expr_lit.lit {
            syn::Lit::Str(s) => Some(s.value()),
            _ => None,
        },
        _ => None,
    }
}

/// Parse the `max_memory` attribute
/// Supports formats like: "100MB", "1GB", "500KB", or raw numbers
pub fn parse_max_memory_attribute(nv: &MetaNameValue) -> TokenStream2 {
    match &nv.value {
        Expr::Lit(expr_lit) => match &expr_lit.lit {
            syn::Lit::Str(s) => {
                let val_str = s.value();
                let val_str = val_str.to_uppercase();

                // Parse memory size with units
                let bytes = if val_str.ends_with("GB") {
                    let num_str = val_str.trim_end_matches("GB");
                    match num_str.parse::<usize>() {
                        Ok(n) => n * 1024 * 1024 * 1024,
                        Err(_) => {
                            return quote! { compile_error!("Invalid number format for max_memory") }
                        }
                    }
                } else if val_str.ends_with("MB") {
                    let num_str = val_str.trim_end_matches("MB");
                    match num_str.parse::<usize>() {
                        Ok(n) => n * 1024 * 1024,
                        Err(_) => {
                            return quote! { compile_error!("Invalid number format for max_memory") }
                        }
                    }
                } else if val_str.ends_with("KB") {
                    let num_str = val_str.trim_end_matches("KB");
                    match num_str.parse::<usize>() {
                        Ok(n) => n * 1024,
                        Err(_) => {
                            return quote! { compile_error!("Invalid number format for max_memory") }
                        }
                    }
                } else {
                    // Try to parse as raw number (bytes)
                    match val_str.parse::<usize>() {
                        Ok(n) => n,
                        Err(_) => {
                            return quote! { compile_error!("Invalid format for max_memory: expected \"100MB\", \"1GB\", \"500KB\", or number") }
                        }
                    }
                };

                quote! { Some(#bytes) }
            }
            syn::Lit::Int(lit_int) => {
                let val = lit_int
                    .base10_parse::<usize>()
                    .expect("max_memory must be a positive integer (bytes)");
                quote! { Some(#val) }
            }
            _ => {
                quote! { compile_error!("Invalid literal for `max_memory`: expected string (\"100MB\") or integer") }
            }
        },
        _ => {
            quote! { compile_error!("Invalid syntax for `max_memory`: expected `max_memory = \"100MB\"`") }
        }
    }
}

/// Parse the `scope` attribute and return the string value
pub fn parse_scope_attribute(nv: &MetaNameValue) -> Result<String, TokenStream2> {
    match &nv.value {
        Expr::Lit(expr_lit) => match &expr_lit.lit {
            syn::Lit::Str(s) => {
                let val = s.value();
                // Validate the scope value
                if val == "global" || val == "thread" {
                    Ok(val)
                } else {
                    Err(
                        quote! { compile_error!("Invalid scope: expected \"global\" or \"thread\"") },
                    )
                }
            }
            _ => Err(quote! { compile_error!("Invalid literal for `scope`: expected string") }),
        },
        _ => Err(
            quote! { compile_error!("Invalid syntax for `scope`: expected `scope = \"global\"|\"thread\"`") },
        ),
    }
}

/// Generate cache key expression based on function arguments (for async macros using format!)
pub fn generate_key_expr(has_self: bool, arg_pats: &[TokenStream2]) -> TokenStream2 {
    if has_self {
        if arg_pats.is_empty() {
            quote! {{
                format!("{:?}", self)
            }}
        } else {
            quote! {{
                let mut __key_parts = Vec::new();
                __key_parts.push(format!("{:?}", self));
                #(
                    __key_parts.push(format!("{:?}", #arg_pats));
                )*
                __key_parts.join("|")
            }}
        }
    } else if arg_pats.is_empty() {
        quote! {{ String::new() }}
    } else {
        quote! {{
            let mut __key_parts = Vec::new();
            #(
                __key_parts.push(format!("{:?}", #arg_pats));
            )*
            __key_parts.join("|")
        }}
    }
}

/// Generate cache key expression using CacheableKey trait (for sync macros)
pub fn generate_key_expr_with_cacheable_key(
    has_self: bool,
    arg_pats: &[TokenStream2],
) -> TokenStream2 {
    if has_self {
        if arg_pats.is_empty() {
            quote! {{
                use cachelito_core::CacheableKey;
                self.to_cache_key()
            }}
        } else {
            quote! {{
                use cachelito_core::CacheableKey;
                let mut __key_parts = Vec::new();
                __key_parts.push(self.to_cache_key());
                #(
                    __key_parts.push((#arg_pats).to_cache_key());
                )*
                __key_parts.join("|")
            }}
        }
    } else if arg_pats.is_empty() {
        quote! {{ String::new() }}
    } else {
        quote! {{
            use cachelito_core::CacheableKey;
            let mut __key_parts = Vec::new();
            #(
                __key_parts.push((#arg_pats).to_cache_key());
            )*
            __key_parts.join("|")
        }}
    }
}

/// Parse async cache attributes from a token stream
pub fn parse_async_attributes(attr: TokenStream2) -> Result<AsyncCacheAttributes, TokenStream2> {
    use syn::parse::Parser;

    let parser = Punctuated::<MetaNameValue, Token![,]>::parse_terminated;
    let parsed_args = parser.parse2(attr).map_err(|e| {
        let msg = format!("Failed to parse attributes: {}", e);
        quote! { compile_error!(#msg) }
    })?;

    let mut attrs = AsyncCacheAttributes::default();

    for nv in parsed_args {
        if nv.path.is_ident("limit") {
            attrs.limit = parse_limit_attribute(&nv);
        } else if nv.path.is_ident("policy") {
            match parse_policy_attribute(&nv) {
                Ok(policy_str) => attrs.policy = quote! { #policy_str },
                Err(err) => return Err(err),
            }
        } else if nv.path.is_ident("ttl") {
            attrs.ttl = parse_ttl_attribute(&nv);
        } else if nv.path.is_ident("name") {
            attrs.custom_name = parse_name_attribute(&nv);
        } else if nv.path.is_ident("max_memory") {
            attrs.max_memory = parse_max_memory_attribute(&nv);
        }
    }

    Ok(attrs)
}

/// Parse sync cache attributes from a token stream
pub fn parse_sync_attributes(attr: TokenStream2) -> Result<SyncCacheAttributes, TokenStream2> {
    use syn::parse::Parser;

    let parser = Punctuated::<MetaNameValue, Token![,]>::parse_terminated;
    let parsed_args = parser.parse2(attr).map_err(|e| {
        let msg = format!("Failed to parse attributes: {}", e);
        quote! { compile_error!(#msg) }
    })?;

    let mut attrs = SyncCacheAttributes::default();

    for nv in parsed_args {
        if nv.path.is_ident("limit") {
            attrs.limit = parse_limit_attribute(&nv);
        } else if nv.path.is_ident("policy") {
            match parse_policy_attribute(&nv) {
                Ok(policy_str) => {
                    attrs.policy = if policy_str == "fifo" {
                        quote! { cachelito_core::EvictionPolicy::FIFO }
                    } else if policy_str == "lru" {
                        quote! { cachelito_core::EvictionPolicy::LRU }
                    } else if policy_str == "lfu" {
                        quote! { cachelito_core::EvictionPolicy::LFU }
                    } else if policy_str == "arc" {
                        quote! { cachelito_core::EvictionPolicy::ARC }
                    } else {
                        return Err(
                            quote! { compile_error!("Invalid policy: expected \"fifo\", \"lru\", \"lfu\", or \"arc\"") },
                        );
                    };
                }
                Err(err) => return Err(err),
            }
        } else if nv.path.is_ident("ttl") {
            attrs.ttl = parse_ttl_attribute(&nv);
        } else if nv.path.is_ident("scope") {
            match parse_scope_attribute(&nv) {
                Ok(scope_str) => {
                    attrs.scope = if scope_str == "thread" {
                        quote! { cachelito_core::CacheScope::ThreadLocal }
                    } else if scope_str == "global" {
                        quote! { cachelito_core::CacheScope::Global }
                    } else {
                        return Err(
                            quote! { compile_error!("Invalid scope: expected \"global\" or \"thread\"") },
                        );
                    };
                }
                Err(err) => return Err(err),
            }
        } else if nv.path.is_ident("name") {
            attrs.custom_name = parse_name_attribute(&nv);
        } else if nv.path.is_ident("max_memory") {
            attrs.max_memory = parse_max_memory_attribute(&nv);
        }
    }

    Ok(attrs)
}

#[cfg(test)]
mod tests {
    use super::*;
    use quote::quote;
    use syn::parse_quote;

    #[test]
    fn test_policies_str_with_separator() {
        let result = policies_str_with_separator(", ");
        assert_eq!(result, "\"fifo\", \"lru\", \"lfu\", \"arc\"");

        let result = policies_str_with_separator("|");
        assert_eq!(result, "\"fifo\"|\"lru\"|\"lfu\"|\"arc\"");
    }

    #[test]
    fn test_parse_limit_attribute_valid() {
        let nv: MetaNameValue = parse_quote! { limit = 100 };
        let result = parse_limit_attribute(&nv);
        assert_eq!(result.to_string(), "Some (100usize)");
    }

    #[test]
    fn test_parse_policy_attribute_valid() {
        let nv: MetaNameValue = parse_quote! { policy = "fifo" };
        let result = parse_policy_attribute(&nv);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "fifo");

        let nv: MetaNameValue = parse_quote! { policy = "lru" };
        let result = parse_policy_attribute(&nv);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "lru");
    }

    #[test]
    fn test_parse_max_memory_attribute() {
        // Test MB format
        let nv: MetaNameValue = parse_quote! { max_memory = "100MB" };
        let result = parse_max_memory_attribute(&nv);
        let expected = 100 * 1024 * 1024;
        assert_eq!(result.to_string(), format!("Some ({}usize)", expected));

        // Test GB format
        let nv: MetaNameValue = parse_quote! { max_memory = "1GB" };
        let result = parse_max_memory_attribute(&nv);
        let expected = 1024 * 1024 * 1024;
        assert_eq!(result.to_string(), format!("Some ({}usize)", expected));

        // Test KB format
        let nv: MetaNameValue = parse_quote! { max_memory = "500KB" };
        let result = parse_max_memory_attribute(&nv);
        let expected = 500 * 1024;
        assert_eq!(result.to_string(), format!("Some ({}usize)", expected));

        // Test raw number
        let nv: MetaNameValue = parse_quote! { max_memory = 1024 };
        let result = parse_max_memory_attribute(&nv);
        assert_eq!(result.to_string(), "Some (1024usize)");

        // Test raw number as string
        let nv: MetaNameValue = parse_quote! { max_memory = "2048" };
        let result = parse_max_memory_attribute(&nv);
        assert_eq!(result.to_string(), "Some (2048usize)");
    }

    #[test]
    fn test_parse_policy_attribute_invalid() {
        let nv: MetaNameValue = parse_quote! { policy = "invalid" };
        let result = parse_policy_attribute(&nv);
        assert!(result.is_err());
    }

    #[test]
    fn test_parse_ttl_attribute_valid() {
        let nv: MetaNameValue = parse_quote! { ttl = 60 };
        let result = parse_ttl_attribute(&nv);
        assert_eq!(result.to_string(), "Some (60u64)");
    }

    #[test]
    fn test_parse_name_attribute() {
        let nv: MetaNameValue = parse_quote! { name = "my_cache" };
        let result = parse_name_attribute(&nv);
        assert_eq!(result, Some("my_cache".to_string()));
    }

    #[test]
    fn test_parse_scope_attribute_valid() {
        let nv: MetaNameValue = parse_quote! { scope = "global" };
        let result = parse_scope_attribute(&nv);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "global");

        let nv: MetaNameValue = parse_quote! { scope = "thread" };
        let result = parse_scope_attribute(&nv);
        assert!(result.is_ok());
        assert_eq!(result.unwrap(), "thread");
    }

    #[test]
    fn test_parse_scope_attribute_invalid() {
        let nv: MetaNameValue = parse_quote! { scope = "invalid" };
        let result = parse_scope_attribute(&nv);
        assert!(result.is_err());
    }

    #[test]
    fn test_generate_key_expr_no_self_no_args() {
        let result = generate_key_expr(false, &[]);
        assert_eq!(result.to_string(), "{ String :: new () }");
    }

    #[test]
    fn test_generate_key_expr_with_self_no_args() {
        let result = generate_key_expr(true, &[]);
        let expected = quote! {{ format!("{:?}", self) }};
        assert_eq!(result.to_string(), expected.to_string());
    }

    #[test]
    fn test_generate_key_expr_with_args() {
        let args = vec![quote! { arg1 }, quote! { arg2 }];
        let result = generate_key_expr(false, &args);
        assert!(result.to_string().contains("__key_parts"));
    }

    #[test]
    fn test_parse_async_attributes_defaults() {
        let attrs = parse_async_attributes(quote! {}).unwrap();
        assert_eq!(attrs.limit.to_string(), "Option :: < usize > :: None");
        assert_eq!(attrs.policy.to_string(), "\"fifo\"");
        assert_eq!(attrs.ttl.to_string(), "Option :: < u64 > :: None");
        assert_eq!(attrs.custom_name, None);
    }

    #[test]
    fn test_parse_async_attributes_complete() {
        let attrs = parse_async_attributes(quote! {
            limit = 50,
            policy = "lru",
            ttl = 120,
            name = "test_cache"
        })
        .unwrap();

        assert_eq!(attrs.limit.to_string(), "Some (50usize)");
        assert_eq!(attrs.policy.to_string(), "\"lru\"");
        assert_eq!(attrs.ttl.to_string(), "Some (120u64)");
        assert_eq!(attrs.custom_name, Some("test_cache".to_string()));
    }

    #[test]
    fn test_parse_sync_attributes_defaults() {
        let attrs = parse_sync_attributes(quote! {}).unwrap();
        assert_eq!(attrs.limit.to_string(), "None");
        assert_eq!(
            attrs.policy.to_string(),
            "cachelito_core :: EvictionPolicy :: FIFO"
        );
        assert_eq!(
            attrs.scope.to_string(),
            "cachelito_core :: CacheScope :: Global"
        );
    }

    #[test]
    fn test_parse_sync_attributes_complete() {
        let attrs = parse_sync_attributes(quote! {
            limit = 100,
            policy = "arc",
            ttl = 300,
            scope = "thread",
            name = "sync_cache"
        })
        .unwrap();

        assert_eq!(attrs.limit.to_string(), "Some (100usize)");
        assert_eq!(
            attrs.policy.to_string(),
            "cachelito_core :: EvictionPolicy :: ARC"
        );
        assert_eq!(
            attrs.scope.to_string(),
            "cachelito_core :: CacheScope :: ThreadLocal"
        );
        assert_eq!(attrs.custom_name, Some("sync_cache".to_string()));
    }
}