dioxus-provider-macros 0.1.0

Procedural macros for dioxus-provider - declarative data fetching and caching for Dioxus applications
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
#![allow(unused_variables)] // Variables used in quote! macros aren't detected by compiler

use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use std::time::Duration;
use syn::{
    FnArg, ItemFn, LitStr, Pat, PatType, Result, ReturnType, Token, Type, parse::Parse,
    parse::ParseStream, parse_macro_input,
};

/// Attribute arguments for the provider macro
#[derive(Default)]
struct ProviderArgs {
    interval: Option<Duration>,
    cache_expiration: Option<Duration>,
    stale_time: Option<Duration>,
    inject: Vec<syn::Type>, // New: list of types to inject
}

impl Parse for ProviderArgs {
    fn parse(input: ParseStream) -> Result<Self> {
        let mut args = ProviderArgs::default();

        while !input.is_empty() {
            let ident: syn::Ident = input.parse()?;
            input.parse::<Token![=]>()?;

            match ident.to_string().as_str() {
                "interval" => {
                    let lit: LitStr = input.parse()?;
                    let duration_str = lit.value();
                    let duration = humantime::parse_duration(&duration_str).map_err(|e| {
                        syn::Error::new_spanned(lit, format!("Invalid duration format: {}", e))
                    })?;
                    args.interval = Some(duration);
                }
                "cache_expiration" => {
                    let lit: LitStr = input.parse()?;
                    let duration_str = lit.value();
                    let duration = humantime::parse_duration(&duration_str).map_err(|e| {
                        syn::Error::new_spanned(lit, format!("Invalid duration format: {}", e))
                    })?;
                    args.cache_expiration = Some(duration);
                }
                "stale_time" => {
                    let lit: LitStr = input.parse()?;
                    let duration_str = lit.value();
                    let duration = humantime::parse_duration(&duration_str).map_err(|e| {
                        syn::Error::new_spanned(lit, format!("Invalid duration format: {}", e))
                    })?;
                    args.stale_time = Some(duration);
                }
                "inject" => {
                    // Parse injection types: inject = [Type1, Type2, ...]
                    let content;
                    syn::bracketed!(content in input);
                    let types = content.parse_terminated(syn::Type::parse, Token![,])?;
                    args.inject = types.into_iter().collect();
                }
                _ => return Err(syn::Error::new_spanned(ident, "Unknown argument")),
            }

            if input.peek(Token![,]) {
                input.parse::<Token![,]>()?;
            }
        }

        Ok(args)
    }
}

/// Unified attribute macro for creating providers
/// Automatically detects provider type based on function parameters:
/// - No parameters → Future Provider  
/// - Has parameters → Family Provider
///
/// Supports humantime duration syntax for all timing parameters:
/// - #[provider(interval = "5s")] - refresh every 5 seconds
/// - #[provider(interval = "1min")] - refresh every minute  
/// - #[provider(interval = "30sec")] - refresh every 30 seconds
///
/// Cache expiration with humantime:
/// - #[provider(cache_expiration = "30s")] - cache expires after 30 seconds
/// - #[provider(cache_expiration = "5min")] - cache expires after 5 minutes
/// - #[provider(cache_expiration = "1h")] - cache expires after 1 hour
///
/// Stale-while-revalidate with humantime:
/// - #[provider(stale_time = "5s")] - serve stale data after 5 seconds, refresh in background
/// - #[provider(stale_time = "30sec")] - serve stale data after 30 seconds, refresh in background
/// - #[provider(stale_time = "2min")] - serve stale data after 2 minutes, refresh in background
///
/// Can combine features:
/// - #[provider(interval = "10s", cache_expiration = "1min")]
/// - #[provider(stale_time = "5s", cache_expiration = "30s")]
///
/// Supported humantime formats:
/// - "5s", "30sec", "2min", "1h", "1day"
/// - "500ms", "1.5s", "2.5min"
#[proc_macro_attribute]
pub fn provider(args: TokenStream, input: TokenStream) -> TokenStream {
    let provider_args = if args.is_empty() {
        ProviderArgs::default()
    } else {
        match syn::parse(args) {
            Ok(args) => args,
            Err(err) => return err.to_compile_error().into(),
        }
    };

    let input_fn = parse_macro_input!(input as ItemFn);

    let result = generate_provider(input_fn, provider_args);

    match result {
        Ok(tokens) => tokens.into(),
        Err(err) => err.to_compile_error().into(),
    }
}

fn generate_provider(input_fn: ItemFn, provider_args: ProviderArgs) -> Result<TokenStream2> {
    let info = extract_provider_info(&input_fn)?;

    let ProviderInfo {
        fn_vis,
        fn_block,
        output_type,
        error_type,
        struct_name,
        ..
    } = &info;

    // Generate enhanced function body with dependency injection
    let enhanced_fn_block = generate_dependency_injection(&provider_args.inject, fn_block);

    // Generate interval and cache expiration implementations
    let interval_impl = generate_interval_impl(&provider_args);
    let cache_expiration_impl = generate_cache_expiration_impl(&provider_args);
    let stale_time_impl = generate_stale_time_impl(&provider_args);

    // Generate common struct and const
    let common_struct = generate_common_struct_and_const(&info);

    // Determine parameter type and implementation based on function parameters
    if input_fn.sig.inputs.is_empty() {
        // No parameters - Provider<()>
        Ok(quote! {
            #common_struct

            impl #struct_name {
                #fn_vis async fn call() -> Result<#output_type, #error_type> {
                    #enhanced_fn_block
                }
            }

            impl ::dioxus_provider::hooks::Provider<()> for #struct_name {
                type Output = #output_type;
                type Error = #error_type;

                fn run(&self, _param: ()) -> impl ::std::future::Future<Output = Result<Self::Output, Self::Error>> + Send {
                    Self::call()
                }

                #interval_impl
                #cache_expiration_impl
                #stale_time_impl
            }
        })
    } else {
        // Has parameters - extract and handle them
        let params = extract_all_params(&input_fn)?;

        if params.len() == 1 {
            // Single parameter - Provider<ParamType>
            let param = &params[0];
            let param_name = &param.name;
            let param_type = &param.ty;

            Ok(quote! {
                #common_struct

                impl #struct_name {
                    #fn_vis async fn call(#param_name: #param_type) -> Result<#output_type, #error_type> {
                        #enhanced_fn_block
                    }
                }

                impl ::dioxus_provider::hooks::Provider<#param_type> for #struct_name {
                    type Output = #output_type;
                    type Error = #error_type;

                    fn run(&self, #param_name: #param_type) -> impl ::std::future::Future<Output = Result<Self::Output, Self::Error>> + Send {
                        Self::call(#param_name)
                    }

                    #interval_impl
                    #cache_expiration_impl
                    #stale_time_impl
                }
            })
        } else {
            // Multiple parameters - Provider<(Param1, Param2, ...)>
            let param_names: Vec<_> = params.iter().map(|p| &p.name).collect();
            let param_types: Vec<_> = params.iter().map(|p| &p.ty).collect();
            let tuple_type = quote! { (#(#param_types,)*) };

            Ok(quote! {
                #common_struct

                impl #struct_name {
                    #fn_vis async fn call(#(#param_names: #param_types,)*) -> Result<#output_type, #error_type> {
                        #enhanced_fn_block
                    }
                }

                impl ::dioxus_provider::hooks::Provider<#tuple_type> for #struct_name {
                    type Output = #output_type;
                    type Error = #error_type;

                    fn run(&self, params: #tuple_type) -> impl ::std::future::Future<Output = Result<Self::Output, Self::Error>> + Send {
                        let (#(#param_names,)*) = params;
                        Self::call(#(#param_names,)*)
                    }

                    #interval_impl
                    #cache_expiration_impl
                    #stale_time_impl
                }
            })
        }
    }
}

/// Generate duration implementation for provider methods
fn generate_duration_impl(method_name: &str, duration: Option<Duration>) -> TokenStream2 {
    if let Some(duration) = duration {
        let duration_secs = duration.as_secs();
        let method_ident = syn::Ident::new(method_name, proc_macro2::Span::call_site());

        quote! {
            fn #method_ident(&self) -> Option<::std::time::Duration> {
                Some(::std::time::Duration::from_secs(#duration_secs))
            }
        }
    } else {
        quote! {}
    }
}

/// Generate interval implementation
fn generate_interval_impl(provider_args: &ProviderArgs) -> TokenStream2 {
    generate_duration_impl("interval", provider_args.interval)
}

/// Generate cache expiration implementation
fn generate_cache_expiration_impl(provider_args: &ProviderArgs) -> TokenStream2 {
    generate_duration_impl("cache_expiration", provider_args.cache_expiration)
}

/// Generate stale time implementation
fn generate_stale_time_impl(provider_args: &ProviderArgs) -> TokenStream2 {
    generate_duration_impl("stale_time", provider_args.stale_time)
}

/// Information extracted from the provider function
struct ProviderInfo {
    fn_vis: syn::Visibility,
    fn_attrs: Vec<syn::Attribute>,
    fn_block: Box<syn::Block>,
    output_type: Type,
    error_type: Type,
    struct_name: syn::Ident,
    fn_name: syn::Ident,
}

/// Information about a function parameter
struct ParamInfo {
    name: syn::Ident,
    ty: Type,
}

/// Extract provider information from the input function
fn extract_provider_info(input_fn: &ItemFn) -> Result<ProviderInfo> {
    let fn_name = input_fn.sig.ident.clone();
    let fn_vis = input_fn.vis.clone();
    let fn_attrs = input_fn.attrs.clone();
    let fn_block = input_fn.block.clone();

    let (output_type, error_type) = extract_result_types(&input_fn.sig.output)?;
    let struct_name = syn::Ident::new(
        &to_pascal_case(&fn_name.to_string()),
        proc_macro2::Span::call_site(),
    );

    Ok(ProviderInfo {
        fn_vis,
        fn_attrs,
        fn_block,
        output_type,
        error_type,
        struct_name,
        fn_name,
    })
}

/// Generate common struct and const for the provider
fn generate_common_struct_and_const(info: &ProviderInfo) -> TokenStream2 {
    let struct_name = &info.struct_name;
    let fn_attrs = &info.fn_attrs;
    let fn_name = &info.fn_name;

    quote! {
        #[derive(Clone, PartialEq)]
        #(#fn_attrs)*
        pub struct #struct_name;

        impl Default for #struct_name {
            fn default() -> Self {
                Self
            }
        }

        // Generate a function that returns an instance of the struct
        pub fn #fn_name() -> #struct_name {
            #struct_name
        }
    }
}

/// Extract all parameters from the function signature
fn extract_all_params(input_fn: &ItemFn) -> Result<Vec<ParamInfo>> {
    let mut params = Vec::new();

    for input in &input_fn.sig.inputs {
        match input {
            FnArg::Typed(PatType { pat, ty, .. }) => {
                if let Pat::Ident(pat_ident) = &**pat {
                    params.push(ParamInfo {
                        name: pat_ident.ident.clone(),
                        ty: (**ty).clone(),
                    });
                } else {
                    return Err(syn::Error::new_spanned(
                        pat,
                        "Only simple parameter names are supported",
                    ));
                }
            }
            FnArg::Receiver(_) => {
                return Err(syn::Error::new_spanned(
                    input,
                    "Methods with self parameter are not supported",
                ));
            }
        }
    }

    Ok(params)
}

/// Extract result types from the function return type
fn extract_result_types(return_type: &ReturnType) -> Result<(Type, Type)> {
    match return_type {
        ReturnType::Default => Err(syn::Error::new_spanned(
            return_type,
            "Provider functions must return Result<T, E>",
        )),
        ReturnType::Type(_, ty) => {
            if let Type::Path(type_path) = &**ty {
                if let Some(segment) = type_path.path.segments.last() {
                    if segment.ident == "Result" {
                        if let syn::PathArguments::AngleBracketed(args) = &segment.arguments {
                            if args.args.len() == 2 {
                                let mut args_iter = args.args.iter();

                                let output_type = match args_iter.next().unwrap() {
                                    syn::GenericArgument::Type(ty) => ty.clone(),
                                    _ => {
                                        return Err(syn::Error::new_spanned(
                                            args,
                                            "Result must have type arguments",
                                        ));
                                    }
                                };

                                let error_type = match args_iter.next().unwrap() {
                                    syn::GenericArgument::Type(ty) => ty.clone(),
                                    _ => {
                                        return Err(syn::Error::new_spanned(
                                            args,
                                            "Result must have type arguments",
                                        ));
                                    }
                                };

                                return Ok((output_type, error_type));
                            }
                        }
                    }
                }
            }

            Err(syn::Error::new_spanned(
                return_type,
                "Provider functions must return Result<T, E>",
            ))
        }
    }
}

/// Convert a string to PascalCase
fn to_pascal_case(s: &str) -> String {
    let mut result = String::new();
    let mut capitalize_next = true;

    for c in s.chars() {
        if c == '_' {
            capitalize_next = true;
        } else if capitalize_next {
            result.push(c.to_ascii_uppercase());
            capitalize_next = false;
        } else {
            result.push(c);
        }
    }

    result
}

/// Generate dependency injection code
fn generate_dependency_injection(inject_types: &[syn::Type], original_block: &syn::Block) -> syn::Block {
    if inject_types.is_empty() {
        return original_block.clone();
    }

    // Create injection statements
    let injection_stmts: Vec<_> = inject_types
        .iter()
        .map(|ty| {
            let var_name = syn::Ident::new(
                &format!("injected_{}", to_pascal_case(&quote!(#ty).to_string().to_lowercase())),
                proc_macro2::Span::call_site(),
            );
            
            syn::parse_quote! {
                let #var_name = ::dioxus_provider::injection::inject::<#ty>()
                    .map_err(|e| format!("Dependency injection failed for {}: {}", stringify!(#ty), e))?;
            }
        })
        .collect();

    // Create new block with injection statements
    let mut new_block = original_block.clone();
    new_block.stmts.splice(0..0, injection_stmts);

    new_block
}