densha-macros-internal 0.1.0

Procedural macros for the Densha framework
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
// Procedural macros for Densha framework
// These macros provide attribute-style functionality for defining routes

extern crate proc_macro;

use proc_macro::TokenStream;
use quote::quote;
use syn::{
    parse::Parse, parse_macro_input, punctuated::Punctuated, Expr, FnArg, Ident, ItemFn, Meta, Pat,
    PatType, Token,
};

/// Custom structure to parse macro arguments
#[derive(Default)]
struct PageArgs {
    render: Option<String>,
}

/// Parse arguments like (render = "static")
impl Parse for PageArgs {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        let mut args = Self::default();

        if input.is_empty() {
            return Ok(args);
        }

        let vars = Punctuated::<Meta, Token![,]>::parse_terminated(input)?;

        for var in vars {
            if let Meta::NameValue(meta) = var {
                if meta.path.is_ident("render") {
                    if let Expr::Lit(expr_lit) = &meta.value {
                        if let syn::Lit::Str(lit_str) = &expr_lit.lit {
                            args.render = Some(lit_str.value());
                        }
                    }
                }
            }
        }

        Ok(args)
    }
}

/// Custom structure to parse static_props arguments
#[derive(Default)]
struct StaticPropsArgs {
    revalidate: Option<u64>,
}

/// Parse arguments like (revalidate = 60)
impl Parse for StaticPropsArgs {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        let mut args = Self::default();

        if input.is_empty() {
            return Ok(args);
        }

        let vars = Punctuated::<Meta, Token![,]>::parse_terminated(input)?;

        for var in vars {
            if let Meta::NameValue(meta) = var {
                if meta.path.is_ident("revalidate") {
                    if let Expr::Lit(expr_lit) = &meta.value {
                        if let syn::Lit::Int(lit_int) = &expr_lit.lit {
                            if let Ok(value) = lit_int.base10_parse::<u64>() {
                                args.revalidate = Some(value);
                            }
                        }
                    }
                }
            }
        }

        Ok(args)
    }
}

/// Attribute macro for defining page components
///
/// # Example
///
/// ```ignore
/// use densha_macros::page;
///
/// #[page]
/// pub fn about_page() -> String {
///     "About page".to_string()
/// }
///
/// #[page(render = "static")]
/// pub fn static_page() -> String {
///     "Static page".to_string()
/// }
/// ```
#[proc_macro_attribute]
pub fn page(attr: TokenStream, item: TokenStream) -> TokenStream {
    let args = parse_macro_input!(attr as PageArgs);
    let input = parse_macro_input!(item as ItemFn);

    // Process attributes
    let render_strategy = args.render.unwrap_or_else(|| "server".to_string());

    // Get function name and path
    let fn_name = &input.sig.ident;
    let fn_vis = &input.vis;
    let fn_block = &input.block;
    let fn_generics = &input.sig.generics;
    let fn_inputs = &input.sig.inputs;
    let fn_output = &input.sig.output;

    // Create route path from function name
    let route_path = fn_name_to_route_path(fn_name);

    // Extract path parameters
    let _path_params = extract_path_params(fn_inputs);

    // Generate output
    let expanded = quote! {
        #[allow(non_camel_case_types)]
        #fn_vis struct #fn_name;

        impl #fn_name {
            #fn_vis fn new() -> Self {
                // Register the page with the Densha router
                println!("Registering page: {} with render strategy: {}", #route_path, #render_strategy);

                Self
            }

            #fn_vis #fn_generics fn call(#fn_inputs) #fn_output {
                #fn_block
            }
        }

        // Create a static instance to register the route
        #[allow(non_upper_case_globals)]
        #fn_vis static #fn_name: () = {
            let _ = #fn_name::new();
            ()
        };
    };

    TokenStream::from(expanded)
}

/// Attribute macro for defining API endpoints
///
/// # Example
///
/// ```ignore
/// use densha_macros::api;
///
/// #[api]
/// pub async fn list_users() -> String {
///     "User list".to_string()
/// }
/// ```
#[proc_macro_attribute]
pub fn api(attr: TokenStream, item: TokenStream) -> TokenStream {
    let _args = parse_macro_input!(attr as PageArgs);
    let input = parse_macro_input!(item as ItemFn);

    // Get function name and path
    let fn_name = &input.sig.ident;
    let fn_vis = &input.vis;
    let fn_block = &input.block;
    let fn_generics = &input.sig.generics;
    let fn_inputs = &input.sig.inputs;
    let fn_output = &input.sig.output;

    // Create route path from function name
    let route_path = fn_name_to_route_path(fn_name);

    // Extract path parameters
    let _path_params = extract_path_params(fn_inputs);

    // Generate output
    let expanded = quote! {
        #[allow(non_camel_case_types)]
        #fn_vis struct #fn_name;

        impl #fn_name {
            #fn_vis fn new() -> Self {
                // Register the API with the Densha router
                println!("Registering API: {}", #route_path);

                Self
            }

            #fn_vis #fn_generics fn call(#fn_inputs) #fn_output {
                #fn_block
            }
        }

        // Create a static instance to register the route
        #[allow(non_upper_case_globals)]
        #fn_vis static #fn_name: () = {
            let _ = #fn_name::new();
            ()
        };
    };

    TokenStream::from(expanded)
}

/// Attribute macro for defining configuration
///
/// # Example
///
/// ```ignore
/// use densha_macros::config;
///
/// #[config]
/// struct AppConfig {
///     database_url: String,
///     port: u16,
/// }
/// ```
#[proc_macro_attribute]
pub fn config(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let input = parse_macro_input!(item as syn::ItemStruct);

    // Get struct name and fields
    let struct_name = &input.ident;

    // Generate implementation for loading configuration
    let expanded = quote! {
        #input

        impl #struct_name {
            /// Load configuration from environment, files, and defaults
            pub fn load() -> Self {
                // TODO: Implement config loading from various sources
                println!("Loading configuration for {}", stringify!(#struct_name));

                // Create a new instance with default values
                // In a real implementation, we would load from env vars, config files, etc.
                Self::default()
            }
        }

        impl Default for #struct_name {
            fn default() -> Self {
                Self {
                    // Default implementation - this would be replaced with actual defaults
                    ..Default::default()
                }
            }
        }
    };

    TokenStream::from(expanded)
}

/// Attribute macro for defining static props function for data fetching at build time
///
/// # Example
///
/// ```ignore
/// use densha_macros::static_props;
/// use serde::Deserialize;
///
/// #[derive(Deserialize)]
/// struct PostParams {
///     id: String,
/// }
///
/// #[static_props(revalidate = 60)]
/// pub async fn get_post_data(params: PostParams) -> Result<serde_json::Value> {
///     // Fetch data at build time
///     Ok(serde_json::json!({
///         "post": {
///             "id": params.id,
///             "title": "Dynamic Post Title",
///             "content": "Content fetched at build time"
///         }
///     }))
/// }
/// ```
#[proc_macro_attribute]
pub fn static_props(attr: TokenStream, item: TokenStream) -> TokenStream {
    let args = parse_macro_input!(attr as StaticPropsArgs);
    let input = parse_macro_input!(item as ItemFn);
    
    // Get function name and attributes
    let fn_name = &input.sig.ident;
    let fn_vis = &input.vis;
    let fn_block = &input.block;
    let fn_inputs = &input.sig.inputs;
    
    // Get revalidation time if specified
    let revalidate = match args.revalidate {
        Some(seconds) => quote! { Some(#seconds) },
        None => quote! { None },
    };
    
    // Generate the function registration with metadata
    let expanded = quote! {
        #[allow(non_upper_case_globals)]
        #fn_vis static #fn_name: ::densha::prelude::StaticPropsFunction = ::densha::prelude::StaticPropsFunction {
            name: stringify!(#fn_name),
            revalidate: #revalidate,
            func: |ctx| async move {
                // Convert context to function parameters
                let params = ::densha::prelude::parse_params_from_context(&ctx)
                    .expect(&format!("Failed to parse parameters for {}", stringify!(#fn_name)));
                
                // Call the actual function implementation
                async fn implementation(#fn_inputs) -> ::anyhow::Result<::serde_json::Value> {
                    #fn_block
                }
                
                implementation(params).await
            },
        };
    };
    
    TokenStream::from(expanded)
}

/// Attribute macro for defining static paths for dynamic routes
///
/// # Example
///
/// ```ignore
/// use densha_macros::static_paths;
///
/// #[static_paths]
/// pub async fn get_post_paths() -> Result<Vec<serde_json::Value>> {
///     // Return all possible path params to pre-render
///     Ok(vec![
///         serde_json::json!({"id": "1"}),
///         serde_json::json!({"id": "2"}),
///         serde_json::json!({"id": "3"})
///     ])
/// }
/// ```
#[proc_macro_attribute]
pub fn static_paths(_attr: TokenStream, item: TokenStream) -> TokenStream {
    let input = parse_macro_input!(item as ItemFn);
    
    // Get function name and attributes
    let fn_name = &input.sig.ident;
    let fn_vis = &input.vis;
    let fn_block = &input.block;
    
    // Generate the function registration with metadata
    let expanded = quote! {
        #[allow(non_upper_case_globals)]
        #fn_vis static #fn_name: ::densha::prelude::StaticPathsFunction = ::densha::prelude::StaticPathsFunction {
            name: stringify!(#fn_name),
            func: || async move {
                // Call the actual function implementation
                async fn implementation() -> ::anyhow::Result<::std::vec::Vec<::serde_json::Value>> {
                    #fn_block
                }
                
                implementation().await
            },
        };
    };
    
    TokenStream::from(expanded)
}

/// Convert a function name to a route path
///
/// Examples:
/// - `index` -> `/`
/// - `about` -> `/about`
/// - `user_profile` -> `/user/profile`
/// - `api_users_get` -> `/api/users/get`
fn fn_name_to_route_path(ident: &Ident) -> String {
    let name = ident.to_string();

    // Special case for index
    if name == "index" {
        return "/".to_string();
    }

    // Convert snake_case to path segments
    let segments: Vec<&str> = name.split('_').collect();
    let path = segments.join("/");

    format!("/{}", path)
}

/// Extract path parameters from function arguments
fn extract_path_params(
    inputs: &syn::punctuated::Punctuated<FnArg, syn::token::Comma>,
) -> Vec<String> {
    let mut params = Vec::new();

    for input in inputs {
        match input {
            FnArg::Typed(PatType { pat, .. }) => {
                if let Pat::Ident(pat_ident) = &**pat {
                    let param_name = pat_ident.ident.to_string();
                    params.push(param_name);
                }
            }
            _ => {}
        }
    }

    params
}