Skip to main content

larastvel_macros/
lib.rs

1use proc_macro::TokenStream;
2use quote::quote;
3use syn::spanned::Spanned;
4use syn::{
5    parse::{Parse, ParseStream},
6    parse_macro_input, Ident, ImplItem, ItemImpl, ItemStruct, ItemTrait, Lit, LitStr,
7};
8
9fn snake_to_pascal(s: &str) -> String {
10    s.split('_')
11        .map(|w| {
12            let mut c = w.chars();
13            match c.next() {
14                None => String::new(),
15                Some(f) => f.to_uppercase().to_string() + c.as_str(),
16            }
17        })
18        .collect()
19}
20
21fn resource_name_from_ident(name: &syn::Ident) -> String {
22    let s = name.to_string();
23    s.strip_suffix("Controller").unwrap_or(&s).to_lowercase()
24}
25
26// ---------------------------------------------------------------------------
27// Derive: Resource
28// ---------------------------------------------------------------------------
29
30#[proc_macro_derive(Resource, attributes(resource))]
31pub fn derive_resource(input: TokenStream) -> TokenStream {
32    let input = parse_macro_input!(input as syn::DeriveInput);
33    let name = &input.ident;
34
35    let resource_name = resource_name_from_ident(name);
36
37    let expanded = quote! {
38        impl larastvel_core::routing::ResourceController for #name {
39            const RESOURCE_NAME: &'static str = #resource_name;
40        }
41
42        impl #name {
43            pub fn register_routes(
44                registrar: &larastvel_core::routing::Registrar,
45            ) {
46                let __name =
47                    <Self as larastvel_core::routing::ResourceController>::RESOURCE_NAME;
48
49                registrar.get(
50                    &format!("/{}", __name),
51                    Self::__resource_index,
52                );
53                registrar.get(
54                    &format!("/{}/create", __name),
55                    Self::__resource_create,
56                );
57                registrar.post(
58                    &format!("/{}", __name),
59                    Self::__resource_store,
60                );
61                registrar.get(
62                    &format!("/{}/{{id}}", __name),
63                    Self::__resource_show,
64                );
65                registrar.get(
66                    &format!("/{}/{{id}}/edit", __name),
67                    Self::__resource_edit,
68                );
69                registrar.put(
70                    &format!("/{}/{{id}}", __name),
71                    Self::__resource_update,
72                );
73                registrar.delete(
74                    &format!("/{}/{{id}}", __name),
75                    Self::__resource_destroy,
76                );
77            }
78
79            async fn __resource_index(
80            ) -> larastvel_core::axum::response::Response {
81                <Self as larastvel_core::routing::ResourceController>::index().await
82            }
83
84            async fn __resource_create(
85            ) -> larastvel_core::axum::response::Response {
86                <Self as larastvel_core::routing::ResourceController>::create().await
87            }
88
89            async fn __resource_store(
90            ) -> larastvel_core::axum::response::Response {
91                <Self as larastvel_core::routing::ResourceController>::store().await
92            }
93
94            async fn __resource_show(
95                larastvel_core::axum::extract::Path(id):
96                    larastvel_core::axum::extract::Path<String>,
97            ) -> larastvel_core::axum::response::Response {
98                <Self as larastvel_core::routing::ResourceController>::show(id).await
99            }
100
101            async fn __resource_edit(
102                larastvel_core::axum::extract::Path(id):
103                    larastvel_core::axum::extract::Path<String>,
104            ) -> larastvel_core::axum::response::Response {
105                <Self as larastvel_core::routing::ResourceController>::edit(id).await
106            }
107
108            async fn __resource_update(
109                larastvel_core::axum::extract::Path(id):
110                    larastvel_core::axum::extract::Path<String>,
111            ) -> larastvel_core::axum::response::Response {
112                <Self as larastvel_core::routing::ResourceController>::update(id).await
113            }
114
115            async fn __resource_destroy(
116                larastvel_core::axum::extract::Path(id):
117                    larastvel_core::axum::extract::Path<String>,
118            ) -> larastvel_core::axum::response::Response {
119                <Self as larastvel_core::routing::ResourceController>::destroy(id).await
120            }
121        }
122    };
123
124    TokenStream::from(expanded)
125}
126
127// ---------------------------------------------------------------------------
128// Attribute: #[controller]
129// ---------------------------------------------------------------------------
130
131#[proc_macro_attribute]
132pub fn controller(_attr: TokenStream, item: TokenStream) -> TokenStream {
133    let input = parse_macro_input!(item as ItemStruct);
134    let name = &input.ident;
135
136    let expanded = quote! {
137        #input
138
139        impl #name {
140            pub fn register_routes(
141                _registrar: &larastvel_core::routing::Registrar,
142            ) {
143            }
144        }
145    };
146
147    TokenStream::from(expanded)
148}
149
150// ---------------------------------------------------------------------------
151// Helper: string literal argument parser
152// ---------------------------------------------------------------------------
153
154struct UriArg {
155    uri: String,
156}
157
158impl Parse for UriArg {
159    fn parse(input: ParseStream) -> syn::Result<Self> {
160        let lit: Lit = input.parse()?;
161        match lit {
162            Lit::Str(s) => Ok(UriArg { uri: s.value() }),
163            _ => Err(syn::Error::new(lit.span(), "expected string literal")),
164        }
165    }
166}
167
168// ---------------------------------------------------------------------------
169// Marker attribute macros: #[get], #[post], #[put], #[patch], #[delete], #[ws]
170// These are identity transforms.  The #[route] macro on the enclosing impl
171// block reads them out of the raw attribute list.
172// ---------------------------------------------------------------------------
173
174/// Marks a handler function for GET requests. Must be used inside a `#[route]` impl block.
175#[proc_macro_attribute]
176pub fn get(_attr: TokenStream, item: TokenStream) -> TokenStream {
177    item
178}
179
180/// Marks a handler function for POST requests. Must be used inside a `#[route]` impl block.
181#[proc_macro_attribute]
182pub fn post(_attr: TokenStream, item: TokenStream) -> TokenStream {
183    item
184}
185
186/// Marks a handler function for PUT requests. Must be used inside a `#[route]` impl block.
187#[proc_macro_attribute]
188pub fn put(_attr: TokenStream, item: TokenStream) -> TokenStream {
189    item
190}
191
192/// Marks a handler function for PATCH requests. Must be used inside a `#[route]` impl block.
193#[proc_macro_attribute]
194pub fn patch(_attr: TokenStream, item: TokenStream) -> TokenStream {
195    item
196}
197
198/// Marks a handler function for DELETE requests. Must be used inside a `#[route]` impl block.
199#[proc_macro_attribute]
200pub fn delete(_attr: TokenStream, item: TokenStream) -> TokenStream {
201    item
202}
203
204/// Marks a handler function for WebSocket upgrades. Must be used inside a `#[route]` impl block.
205#[proc_macro_attribute]
206pub fn ws(_attr: TokenStream, item: TokenStream) -> TokenStream {
207    item
208}
209
210/// Marks a handler function with middleware. Must be used inside a `#[route]` impl block.
211///
212/// Accepts one or more middleware names:
213/// ```ignore
214/// #[middleware("auth")]
215/// #[middleware("auth", "admin")]
216/// ```
217#[proc_macro_attribute]
218pub fn middleware(_attr: TokenStream, item: TokenStream) -> TokenStream {
219    item
220}
221
222// ---------------------------------------------------------------------------
223// Parser for middleware arguments: one or more comma-separated string literals.
224// ---------------------------------------------------------------------------
225
226struct MiddlewareArgs {
227    names: Vec<String>,
228}
229
230impl Parse for MiddlewareArgs {
231    fn parse(input: ParseStream) -> syn::Result<Self> {
232        let mut names = Vec::new();
233        while !input.is_empty() {
234            let lit: Lit = input.parse()?;
235            match lit {
236                Lit::Str(s) => names.push(s.value()),
237                _ => return Err(syn::Error::new(lit.span(), "expected string literal")),
238            }
239            if !input.is_empty() {
240                input.parse::<syn::Token![,]>()?;
241            }
242        }
243        Ok(MiddlewareArgs { names })
244    }
245}
246
247// ---------------------------------------------------------------------------
248// Attribute: #[listener(EventType)]
249//
250// Converts an async function into a zero-sized Listener struct that
251// implements the `Listener<EventType>` trait and provides a `listen()`
252// helper to register it with `EventService`.
253//
254// Usage:
255//   #[listener(OrderShipped)]
256//   async fn send_notification(event: OrderShipped) {
257//       tracing::info!("Order {} shipped", event.order_id);
258//   }
259//
260// Expands to:
261//   struct SendNotificationListener;
262//
263//   #[async_trait]
264//   impl listener<OrderShipped> for SendNotificationListener {
265//       async fn handle(&self, event: OrderShipped) { ... }
266//   }
267//
268//   impl SendNotificationListener {
269//       fn listen() {
270//           EventService::listen::<OrderShipped, Self>(Self);
271//       }
272//   }
273// ---------------------------------------------------------------------------
274
275#[proc_macro_attribute]
276pub fn listener(attr: TokenStream, item: TokenStream) -> TokenStream {
277    let event_ty: syn::Type = parse_macro_input!(attr as syn::Type);
278    let func = parse_macro_input!(item as syn::ItemFn);
279
280    if func.sig.asyncness.is_none() {
281        return syn::Error::new(func.sig.span(), "#[listener] requires async fn")
282            .to_compile_error()
283            .into();
284    }
285
286    let fn_name = &func.sig.ident;
287    let struct_name_str = snake_to_pascal(&fn_name.to_string()) + "Listener";
288    let struct_name = syn::Ident::new(&struct_name_str, fn_name.span());
289    let vis = &func.vis;
290    let body = &func.block;
291    let params = &func.sig.inputs;
292
293    let expanded = quote! {
294        #vis struct #struct_name;
295
296        #[larastvel_core::async_trait]
297        impl larastvel_core::events::Listener<#event_ty> for #struct_name {
298            async fn handle(&self, #params) {
299                #body
300            }
301        }
302
303        impl #struct_name {
304            pub fn listen() {
305                larastvel_core::events::EventService::listen::<#event_ty, Self>(Self);
306            }
307        }
308    };
309
310    TokenStream::from(expanded)
311}
312
313// ---------------------------------------------------------------------------
314// Attribute: #[job]
315//
316// Converts an async function into a queue job struct that implements
317// `ShouldQueue`.  The function parameters become struct fields, and the
318// generated struct provides `new()`, `dispatch()`, and `name()` methods.
319//
320// Usage:
321//   #[job]
322//   async fn process_podcast(podcast_id: i32) -> Result<(), JobError> {
323//       tracing::info!("Processing podcast {}", podcast_id);
324//       Ok(())
325//   }
326//
327// Expands to:
328//   #[derive(Debug)]
329//   pub struct ProcessPodcastJob {
330//       pub podcast_id: i32,
331//   }
332//
333//   impl ProcessPodcastJob {
334//       pub fn new(podcast_id: i32) -> Self { ... }
335//       pub async fn dispatch(self) -> Result<(), JobError> { ... }
336//   }
337//
338//   #[async_trait]
339//   impl ShouldQueue for ProcessPodcastJob {
340//       fn name(&self) -> &str { "process_podcast" }
341//       async fn handle(&self) -> Result<(), JobError> {
342//           __process_podcast_inner(self.podcast_id).await
343//       }
344//   }
345//
346//   async fn __process_podcast_inner(podcast_id: i32) -> Result<(), JobError> { ... }
347// ---------------------------------------------------------------------------
348
349// ---------------------------------------------------------------------------
350// Attribute: #[job(tries = 5, backoff = 10, timeout = 30, fail_on_timeout, delay = 60)]
351//
352// Generates a `*Job` struct implementing `ShouldQueue` from an async fn, with
353// optional Laravel-style queue attributes: `tries`, `backoff`, `timeout`,
354// `fail_on_timeout`, and `delay` (Laravel's `#[Delay]` attribute).
355// ---------------------------------------------------------------------------
356
357#[derive(Default)]
358struct JobAttrs {
359    tries: Option<u64>,
360    backoff: Option<u64>,
361    timeout: Option<u64>,
362    fail_on_timeout: bool,
363    delay: Option<u64>,
364}
365
366impl Parse for JobAttrs {
367    fn parse(input: ParseStream) -> syn::Result<Self> {
368        let mut attrs = JobAttrs::default();
369        while !input.is_empty() {
370            let ident: syn::Ident = input.parse()?;
371            let name = ident.to_string();
372            match name.as_str() {
373                "fail_on_timeout" => attrs.fail_on_timeout = true,
374                "tries" | "backoff" | "timeout" | "delay" => {
375                    input.parse::<syn::Token![=]>()?;
376                    let lit: syn::LitInt = input.parse()?;
377                    let value = lit.base10_parse::<u64>().map_err(|_| {
378                        syn::Error::new(lit.span(), format!("#[job] {name} must be an integer"))
379                    })?;
380                    match name.as_str() {
381                        "tries" => attrs.tries = Some(value),
382                        "backoff" => attrs.backoff = Some(value),
383                        "delay" => attrs.delay = Some(value),
384                        _ => attrs.timeout = Some(value),
385                    }
386                }
387                _ => {
388                    return Err(syn::Error::new(
389                        ident.span(),
390                        format!("unknown #[job] attribute: {name}"),
391                    ))
392                }
393            }
394            if input.is_empty() {
395                break;
396            }
397            input.parse::<syn::Token![,]>()?;
398        }
399        Ok(attrs)
400    }
401}
402
403#[proc_macro_attribute]
404pub fn job(attr: TokenStream, item: TokenStream) -> TokenStream {
405    let attrs = parse_macro_input!(attr as JobAttrs);
406    let func = parse_macro_input!(item as syn::ItemFn);
407
408    if func.sig.asyncness.is_none() {
409        return syn::Error::new(func.sig.span(), "#[job] requires async fn")
410            .to_compile_error()
411            .into();
412    }
413
414    let fn_name = &func.sig.ident;
415    let fn_name_str = fn_name.to_string();
416    // Strip trailing "_job" suffix so `fn simple_job` yields struct `SimpleJob`, not `SimpleJobJob`.
417    let stem = if fn_name_str.ends_with("_job") && fn_name_str.len() > 4 {
418        &fn_name_str[..fn_name_str.len() - 4]
419    } else {
420        &fn_name_str
421    };
422    let struct_name_str = snake_to_pascal(stem) + "Job";
423    let struct_name = syn::Ident::new(&struct_name_str, fn_name.span());
424    let inner_fn_name = syn::Ident::new(&format!("__{}_inner", fn_name_str), fn_name.span());
425    let vis = &func.vis;
426    let output_ty = &func.sig.output;
427    let body = &func.block;
428
429    // Parse function params into struct fields.
430    let mut field_tokens = Vec::new();
431    let mut new_param_tokens = Vec::new();
432    let mut field_assignments = Vec::new();
433    let mut dispatch_args = Vec::new();
434    let mut handle_args = Vec::new();
435
436    for arg in &func.sig.inputs {
437        match arg {
438            syn::FnArg::Typed(pat_type) => {
439                let pat = &pat_type.pat;
440                let ty = &pat_type.ty;
441                field_tokens.push(quote! { pub #pat: #ty });
442                new_param_tokens.push(quote! { #pat: #ty });
443                field_assignments.push(quote! { #pat });
444                // In dispatch(self), self is owned so we can move fields out.
445                dispatch_args.push(quote! { self.#pat });
446                // In handle(&self), we must clone since we only have &self.
447                handle_args.push(quote! { self.#pat.clone() });
448            }
449            syn::FnArg::Receiver(_) => {
450                return syn::Error::new(arg.span(), "#[job] cannot be used on methods with self")
451                    .to_compile_error()
452                    .into();
453            }
454        }
455    }
456
457    let tries = match attrs.tries {
458        Some(t) => quote! { Some(#t) },
459        None => quote! { None },
460    };
461    let backoff = match attrs.backoff {
462        Some(b) => quote! { Some(#b) },
463        None => quote! { None },
464    };
465    let timeout = match attrs.timeout {
466        Some(t) => quote! { Some(#t) },
467        None => quote! { None },
468    };
469    let fail_on_timeout = if attrs.fail_on_timeout {
470        quote! { true }
471    } else {
472        quote! { false }
473    };
474    let delay = match attrs.delay {
475        Some(d) => quote! { Some(#d) },
476        None => quote! { None },
477    };
478
479    let expanded = quote! {
480        #[derive(Debug)]
481        #vis struct #struct_name {
482            #(#field_tokens,)*
483        }
484
485        impl #struct_name {
486            pub fn new(#(#new_param_tokens),*) -> Self {
487                Self {
488                    #(#field_assignments,)*
489                }
490            }
491
492            pub async fn dispatch(self) -> Result<(), larastvel_core::queue::JobError> {
493                #inner_fn_name(#(#dispatch_args),*).await
494            }
495        }
496
497        #[larastvel_core::async_trait]
498        impl larastvel_core::queue::ShouldQueue for #struct_name {
499            fn name(&self) -> &str {
500                #fn_name_str
501            }
502
503            fn max_attempts(&self) -> Option<u64> {
504                #tries
505            }
506
507            fn backoff_seconds(&self) -> Option<u64> {
508                #backoff
509            }
510
511            fn timeout_seconds(&self) -> Option<u64> {
512                #timeout
513            }
514
515            fn fail_on_timeout(&self) -> bool {
516                #fail_on_timeout
517            }
518
519            fn delay_seconds(&self) -> Option<u64> {
520                #delay
521            }
522
523            async fn handle(&self) -> Result<(), larastvel_core::queue::JobError> {
524                #inner_fn_name(#(#handle_args),*).await
525            }
526        }
527
528        #[allow(dead_code)]
529        async fn #inner_fn_name(#(#new_param_tokens),*) #output_ty {
530            #body
531        }
532    };
533
534    TokenStream::from(expanded)
535}
536
537// ---------------------------------------------------------------------------
538// Attribute: #[queued_listener(EventType)]
539//
540// Like `#[listener]` but dispatches the handler as a background job instead
541// of running synchronously.  Generates both a `*Listener` struct (registered
542// with EventService) and a `*Job` struct (implements ShouldQueue).
543//
544// Usage:
545//   #[queued_listener(OrderShipped)]
546//   async fn handle_order_shipped(event: OrderShipped) -> Result<(), JobError> {
547//       tracing::info!("Processing order {}", event.order_id);
548//       Ok(())
549//   }
550//
551// This registers a listener that, on each event, dispatches a
552// `HandleOrderShippedJob` to the default queue.
553// ---------------------------------------------------------------------------
554
555#[proc_macro_attribute]
556pub fn queued_listener(attr: TokenStream, item: TokenStream) -> TokenStream {
557    let event_ty: syn::Type = parse_macro_input!(attr as syn::Type);
558    let func = parse_macro_input!(item as syn::ItemFn);
559
560    if func.sig.asyncness.is_none() {
561        return syn::Error::new(func.sig.span(), "#[queued_listener] requires async fn")
562            .to_compile_error()
563            .into();
564    }
565
566    let fn_name = &func.sig.ident;
567    let fn_name_str = fn_name.to_string();
568
569    // Strip trailing "_listener" for a cleaner struct name.
570    let stem = if fn_name_str.ends_with("_listener") && fn_name_str.len() > 10 {
571        &fn_name_str[..fn_name_str.len() - 9]
572    } else {
573        &fn_name_str
574    };
575    // Strip trailing "_handler" too.
576    let stem = if stem.ends_with("_handler") && stem.len() > 8 {
577        &stem[..stem.len() - 8]
578    } else {
579        stem
580    };
581
582    let struct_stem = snake_to_pascal(stem);
583    let job_struct_name = syn::Ident::new(&(struct_stem.clone() + "Job"), fn_name.span());
584    let listener_struct_name = syn::Ident::new(&(struct_stem + "Listener"), fn_name.span());
585    let inner_fn_name = syn::Ident::new(&format!("__{}_inner", fn_name_str), fn_name.span());
586    let vis = &func.vis;
587    let output = &func.sig.output;
588    let body = &func.block;
589
590    // Extract the event parameter.
591    let event_param = func.sig.inputs.first().and_then(|arg| match arg {
592        syn::FnArg::Typed(pat_type) => Some((pat_type.pat.clone(), pat_type.ty.clone())),
593        _ => None,
594    });
595
596    let Some((event_pat, event_ty_inner)) = event_param else {
597        return syn::Error::new(
598            func.sig.span(),
599            "#[queued_listener] requires exactly one parameter: the event",
600        )
601        .to_compile_error()
602        .into();
603    };
604
605    let expanded = quote! {
606        // --- Job struct ---
607        #[derive(Debug)]
608        #vis struct #job_struct_name {
609            pub #event_pat: #event_ty_inner,
610        }
611
612        impl #job_struct_name {
613            pub fn new(#event_pat: #event_ty_inner) -> Self {
614                Self { #event_pat }
615            }
616
617            pub async fn dispatch(self) -> Result<(), larastvel_core::queue::JobError> {
618                #inner_fn_name(self.#event_pat).await
619            }
620        }
621
622        #[larastvel_core::async_trait]
623        impl larastvel_core::queue::ShouldQueue for #job_struct_name {
624            fn name(&self) -> &str {
625                #fn_name_str
626            }
627
628            async fn handle(&self) -> Result<(), larastvel_core::queue::JobError> {
629                #inner_fn_name(self.#event_pat.clone()).await
630            }
631        }
632
633        #[allow(dead_code)]
634        async fn #inner_fn_name(#event_pat: #event_ty_inner) #output {
635            #body
636        }
637
638        // --- Listener struct ---
639        #vis struct #listener_struct_name;
640
641        #[larastvel_core::async_trait]
642        impl larastvel_core::events::Listener<#event_ty> for #listener_struct_name {
643            async fn handle(&self, #event_pat: #event_ty_inner) {
644                if let Err(e) = #job_struct_name::new(#event_pat).dispatch().await {
645                    tracing::error!("Queued listener failed: {e}");
646                }
647            }
648        }
649
650        impl #listener_struct_name {
651            pub fn listen() {
652                larastvel_core::events::EventService::listen::<#event_ty, Self>(Self);
653            }
654        }
655    };
656
657    TokenStream::from(expanded)
658}
659
660// ---------------------------------------------------------------------------
661// Attribute: #[can("ability")]
662//
663// Adds authorization checking to an async handler function.
664//
665// Prepends `AuthenticatedUser` and `Extension<Gate>` extractor parameters
666// and wraps the body with an ability check.  The function return type is
667// changed to `axum::response::Response`.
668//
669// Usage:
670//   #[can("admin")]
671//   async fn dashboard(Extension(state): Extension<AppState>) -> impl IntoResponse {
672//       Html("<h1>Admin</h1>")
673//   }
674// ---------------------------------------------------------------------------
675
676#[proc_macro_attribute]
677pub fn can(attr: TokenStream, item: TokenStream) -> TokenStream {
678    let parsed = parse_macro_input!(attr as UriArg);
679    let ability = parsed.uri;
680    let func = parse_macro_input!(item as syn::ItemFn);
681
682    if func.sig.asyncness.is_none() {
683        return syn::Error::new(func.sig.span(), "#[can] requires async fn")
684            .to_compile_error()
685            .into();
686    }
687
688    let vis = &func.vis;
689    let name = &func.sig.ident;
690    let inputs = &func.sig.inputs;
691    let body = &func.block;
692
693    for input in inputs {
694        if let syn::FnArg::Receiver(_) = input {
695            return syn::Error::new(input.span(), "#[can] cannot be used on methods with self")
696                .to_compile_error()
697                .into();
698        }
699    }
700
701    let expanded = quote! {
702        #vis async fn #name(
703            __larastvel_auth: larastvel_core::auth::AuthenticatedUser,
704            __larastvel_gate: larastvel_core::axum::Extension<larastvel_core::auth::Gate>,
705            #inputs
706        ) -> larastvel_core::axum::response::Response {
707            if let Err(__larastvel_e) = larastvel_core::auth::check_ability(#ability, &__larastvel_auth, &__larastvel_gate.0).await {
708                return __larastvel_e.into_response();
709            }
710            larastvel_core::axum::response::IntoResponse::into_response(#body)
711        }
712    };
713
714    TokenStream::from(expanded)
715}
716
717// ---------------------------------------------------------------------------
718// Attribute: #[validate(rules_expr)]
719//
720// Validates a JSON request body before the handler runs.
721//
722// The attribute argument must be an expression that evaluates to
723// `Vec<(&str, Vec<Rule>)>`.  The handler must have a `Json<Value>`
724// parameter (typically `Json(body): Json<Value>`).
725//
726// The return type is changed to `axum::response::Response`.
727//
728// Usage:
729//   #[validate(vec![("email", vec![Rule::required(), Rule::email()])])]
730//   async fn store(Json(body): Json<Value>) -> impl IntoResponse {
731//       Json(json!({"ok": true}))
732//   }
733// ---------------------------------------------------------------------------
734
735/// Extracts the binding name from a pattern like `Json(body)` or `body`.
736fn extract_json_binding(pat: &syn::Pat) -> Option<proc_macro2::TokenStream> {
737    match pat {
738        // `Json(body)` — body IS the inner Value
739        syn::Pat::TupleStruct(ps) if ps.elems.len() == 1 => {
740            if let syn::Pat::Ident(inner) = &ps.elems[0] {
741                let id = &inner.ident;
742                return Some(quote! { #id });
743            }
744            None
745        }
746        // `Json { body }` — body IS the inner Value
747        syn::Pat::Struct(ps) => ps.fields.first().and_then(|f| match &*f.pat {
748            syn::Pat::Ident(ident) => {
749                let id = &ident.ident;
750                Some(quote! { #id })
751            }
752            _ => None,
753        }),
754        // `body: Json<Value>` — body IS the Json<Value> struct, need .0
755        syn::Pat::Ident(pi) => {
756            let id = &pi.ident;
757            Some(quote! { #id . 0 })
758        }
759        _ => None,
760    }
761}
762
763#[proc_macro_attribute]
764pub fn validate(attr: TokenStream, item: TokenStream) -> TokenStream {
765    let rules_expr = proc_macro2::TokenStream::from(attr);
766    let func = parse_macro_input!(item as syn::ItemFn);
767
768    if func.sig.asyncness.is_none() {
769        return syn::Error::new(func.sig.span(), "#[validate] requires async fn")
770            .to_compile_error()
771            .into();
772    }
773
774    let vis = &func.vis;
775    let name = &func.sig.ident;
776    let inputs = &func.sig.inputs;
777    let body = &func.block;
778
779    for input in inputs {
780        if let syn::FnArg::Receiver(_) = input {
781            return syn::Error::new(
782                input.span(),
783                "#[validate] cannot be used on methods with self",
784            )
785            .to_compile_error()
786            .into();
787        }
788    }
789
790    // Find the Json<Value> binding in the handler parameters.
791    let body_access = inputs
792        .iter()
793        .find_map(|arg| {
794            if let syn::FnArg::Typed(pat_type) = arg {
795                let ty_str = quote! { #pat_type.ty }.to_string();
796                if ty_str.contains("Json") && ty_str.contains("Value") {
797                    return extract_json_binding(pat_type.pat.as_ref());
798                }
799            }
800            None
801        })
802        .unwrap_or_else(|| {
803            // Fallback: create a synthetic accessor for "__body.0"
804            quote! { __body . 0 }
805        });
806
807    let expanded = quote! {
808        #vis async fn #name(
809            #inputs
810        ) -> larastvel_core::axum::response::Response {
811            use std::collections::HashMap;
812
813            let __larastvel_body: &serde_json::Value = &(#body_access);
814            let __data: HashMap<String, serde_json::Value> = match __larastvel_body.as_object() {
815                Some(map) => map.iter().map(|(k, v)| (k.clone(), v.clone())).collect(),
816                None => {
817                    let mut __errors = larastvel_core::validation::ValidationErrors::new();
818                    __errors.add("_", "Request body must be a JSON object.");
819                    return __errors.into_response();
820                }
821            };
822
823            let __rules = #rules_expr;
824
825            if let Err(__errors) =
826                larastvel_core::validation::validate_async(&__data, __rules).await
827            {
828                return __errors.into_response();
829            }
830
831            larastvel_core::axum::response::IntoResponse::into_response(#body)
832        }
833    };
834
835    TokenStream::from(expanded)
836}
837
838// ---------------------------------------------------------------------------
839// Attribute: #[validated_query(rules_expr)]
840//
841// Validates query-string parameters before the handler runs.
842//
843// The attribute argument must be an expression that evaluates to
844// `Vec<(&str, Vec<Rule>)>`.  The handler must have a `Query<HashMap<String,
845// String>>` parameter (typically `Query(params): Query<HashMap<String, String>>`).
846//
847// The return type is changed to `axum::response::Response`.
848//
849// Usage:
850//   #[validated_query(vec![("page", vec![required(), numeric()])])]
851//   async fn list(Query(params): Query<HashMap<String, String>>) -> impl IntoResponse {
852//       Json(json!({"page": params.get("page")}))
853//   }
854// ---------------------------------------------------------------------------
855
856/// Extracts the binding name from a pattern like `Query(params)` or `params`.
857fn extract_query_binding(pat: &syn::Pat) -> Option<proc_macro2::TokenStream> {
858    // Same logic as extract_json_binding — patterns are identical.
859    extract_json_binding(pat)
860}
861
862#[proc_macro_attribute]
863pub fn validated_query(attr: TokenStream, item: TokenStream) -> TokenStream {
864    let rules_expr = proc_macro2::TokenStream::from(attr);
865    let func = parse_macro_input!(item as syn::ItemFn);
866
867    if func.sig.asyncness.is_none() {
868        return syn::Error::new(func.sig.span(), "#[validated_query] requires async fn")
869            .to_compile_error()
870            .into();
871    }
872
873    let vis = &func.vis;
874    let name = &func.sig.ident;
875    let inputs = &func.sig.inputs;
876    let body = &func.block;
877
878    for input in inputs {
879        if let syn::FnArg::Receiver(_) = input {
880            return syn::Error::new(
881                input.span(),
882                "#[validated_query] cannot be used on methods with self",
883            )
884            .to_compile_error()
885            .into();
886        }
887    }
888
889    // Find the Query<…> binding in the handler parameters.
890    let body_access = inputs
891        .iter()
892        .find_map(|arg| {
893            if let syn::FnArg::Typed(pat_type) = arg {
894                let ty_str = quote! { #pat_type.ty }.to_string();
895                if ty_str.contains("Query") {
896                    return extract_query_binding(pat_type.pat.as_ref());
897                }
898            }
899            None
900        })
901        .unwrap_or_else(|| {
902            quote! { __params }
903        });
904
905    let expanded = quote! {
906        #vis async fn #name(
907            #inputs
908        ) -> larastvel_core::axum::response::Response {
909            use std::collections::HashMap;
910
911            let __raw: &HashMap<String, String> = &(#body_access);
912            let __data: HashMap<String, serde_json::Value> = __raw
913                .iter()
914                .map(|(k, v)| (k.clone(), serde_json::Value::String(v.clone())))
915                .collect();
916
917            let __rules = #rules_expr;
918
919            if let Err(__errors) =
920                larastvel_core::validation::validate_async(&__data, __rules).await
921            {
922                return __errors.into_response();
923            }
924
925            larastvel_core::axum::response::IntoResponse::into_response(#body)
926        }
927    };
928
929    TokenStream::from(expanded)
930}
931
932// ---------------------------------------------------------------------------
933// Attribute: #[table("name")] / #[table("name", route_key = "column")]
934//
935// Converts a plain struct into a full SeaORM entity, eliminating the
936// boilerplate of `DeriveEntityModel`, `Relation`, `ActiveModelBehavior`,
937// and the `DbModel` wrapper.
938//
939// Usage:
940//   #[table("users")]
941//   pub struct User {
942//       #[sea_orm(primary_key)]
943//       pub id: i32,
944//       pub name: String,
945//       pub email: String,
946//       pub password: String,
947//       pub email_verified_at: Option<DateTime>,
948//       pub created_at: DateTime,
949//       pub updated_at: DateTime,
950//   }
951//
952// Expands to a `__table_User` inner module containing a Model struct
953// with `DeriveEntityModel`, a `Relation` enum, `ActiveModelBehavior`,
954// and re-exports `Model`, `Entity`, `ActiveModel`, `Column`.
955// The original struct name is kept as a `DbModel` wrapper.
956//
957// Field-level `#[sea_orm(…)]` attributes are passed through directly
958// to `DeriveEntityModel` – all SeaORM options (primary_key,
959// auto_increment, unique, default_value, indexed, column_type, …)
960// are supported.
961//
962// The optional `route_key = "column"` option (Laravel 13.21's
963// `#[RouteKey('slug')]` attribute) selects the column used by implicit
964// route model binding (`ModelPath`); without it, binding resolves by
965// primary key.
966// ---------------------------------------------------------------------------
967
968#[proc_macro_attribute]
969pub fn table(attr: TokenStream, item: TokenStream) -> TokenStream {
970    let input: syn::ItemStruct = syn::parse_macro_input!(item as syn::ItemStruct);
971
972    use syn::parse::Parser as _;
973
974    let parsed = syn::punctuated::Punctuated::<syn::Expr, syn::Token![,]>::parse_terminated
975        .parse(attr)
976        .unwrap_or_else(|e| {
977            panic!(
978                "#[table] expects `\"table_name\"` or `\"table_name\", route_key = \"column\"`: {}",
979                e
980            )
981        });
982    let mut iter = parsed.iter();
983    let table_name: String = match iter.next() {
984        Some(syn::Expr::Lit(syn::ExprLit {
985            lit: syn::Lit::Str(s),
986            ..
987        })) => s.value(),
988        _ => panic!("#[table] expects a table name string as the first argument"),
989    };
990    let mut route_key: Option<String> = None;
991    for option in iter {
992        if let syn::Expr::Assign(syn::ExprAssign { left, right, .. }) = option {
993            if let (
994                syn::Expr::Path(p),
995                syn::Expr::Lit(syn::ExprLit {
996                    lit: syn::Lit::Str(s),
997                    ..
998                }),
999            ) = (&**left, &**right)
1000            {
1001                if p.path.is_ident("route_key") {
1002                    route_key = Some(s.value());
1003                    continue;
1004                }
1005            }
1006        }
1007        panic!("#[table] unknown option (expected `route_key = \"column\"`)");
1008    }
1009
1010    let name = &input.ident;
1011    let vis = &input.vis;
1012    let fields = &input.fields;
1013    let table = table_name;
1014    let mod_name = syn::Ident::new(&format!("__table_{}", name), name.span());
1015
1016    // route_key = "slug" → Column variant ident (PascalCase of the column).
1017    let route_key_method = match &route_key {
1018        Some(column) => {
1019            let variant = column_variant_ident(column);
1020            quote! {
1021                fn route_key() -> Option<&'static str> {
1022                    Some(#column)
1023                }
1024
1025                async fn find_by_route_key(
1026                    db: &sea_orm::DatabaseConnection,
1027                    value: &str,
1028                ) -> Result<Option<Self>, sea_orm::DbErr> {
1029                    Entity::find()
1030                        .filter(Column::#variant.eq(value.to_string()))
1031                        .one(db)
1032                        .await
1033                }
1034            }
1035        }
1036        None => quote! {},
1037    };
1038
1039    let expanded = quote! {
1040        #[doc(hidden)]
1041        #[allow(non_snake_case)]
1042        mod #mod_name {
1043            use larastvel_core::sea_orm;
1044            use sea_orm::entity::prelude::*;
1045
1046            #[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
1047            #[sea_orm(table_name = #table)]
1048            pub struct Model #fields
1049
1050            #[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
1051            pub enum Relation {}
1052
1053            impl ActiveModelBehavior for ActiveModel {}
1054
1055            #[larastvel_core::async_trait]
1056            impl larastvel_core::routing::RouteKey for Model {
1057                #route_key_method
1058            }
1059        }
1060
1061        pub use #mod_name::Model;
1062        pub use #mod_name::Entity;
1063        pub use #mod_name::ActiveModel;
1064        pub use #mod_name::Column;
1065
1066        #vis struct #name;
1067
1068        impl larastvel_core::models::DbModel for #name {
1069            type Entity = Entity;
1070        }
1071    };
1072
1073    TokenStream::from(expanded)
1074}
1075
1076/// `"user_id"` → `UserId` — the SeaORM column variant name for a column.
1077fn column_variant_ident(column: &str) -> syn::Ident {
1078    let pascal: String = column
1079        .split('_')
1080        .map(|part| {
1081            let mut chars = part.chars();
1082            match chars.next() {
1083                Some(first) => first.to_uppercase().collect::<String>() + chars.as_str(),
1084                None => String::new(),
1085            }
1086        })
1087        .collect();
1088    if pascal.is_empty() {
1089        panic!("#[table] route_key column name must not be empty");
1090    }
1091    syn::Ident::new(&pascal, proc_macro2::Span::call_site())
1092}
1093
1094// ---------------------------------------------------------------------------
1095// Attribute: #[scope]
1096//
1097// Converts a query-scope function into a static method on a DbModel wrapper
1098// struct (designed for use inside an `impl Model` block).
1099//
1100// The first parameter (the SeaORM Select builder) is removed from the
1101// public signature; the generated method internally calls `Self::query()`
1102// and passes it as that parameter.
1103//
1104// The function name may optionally start with `scope_` — the prefix is
1105// stripped for the public name (matching Laravel conventions).
1106//
1107// Usage:
1108//   impl User {
1109//       #[scope]
1110//       fn popular(query: Select<Entity>, min_likes: i64) -> Select<Entity> {
1111//           query.filter(Column::Likes.gte(min_likes))
1112//       }
1113//   }
1114//
1115// Expands to:
1116//   impl User {
1117//       pub fn popular(min_likes: i64) -> Select<Entity> {
1118//           let query = Self::query();
1119//           query.filter(Column::Likes.gte(min_likes))
1120//       }
1121//   }
1122// ---------------------------------------------------------------------------
1123
1124#[proc_macro_attribute]
1125pub fn scope(_attr: TokenStream, item: TokenStream) -> TokenStream {
1126    let func = parse_macro_input!(item as syn::ItemFn);
1127
1128    // Reject methods that take self.
1129    for arg in &func.sig.inputs {
1130        if matches!(arg, syn::FnArg::Receiver(_)) {
1131            return syn::Error::new(
1132                func.sig.span(),
1133                "#[scope] cannot be used on methods with `self`",
1134            )
1135            .to_compile_error()
1136            .into();
1137        }
1138    }
1139
1140    // Require at least one parameter (the query).
1141    if func.sig.inputs.is_empty() {
1142        return syn::Error::new(
1143            func.sig.span(),
1144            "#[scope] requires at least one parameter (the SeaORM query)",
1145        )
1146        .to_compile_error()
1147        .into();
1148    }
1149
1150    let fn_name = &func.sig.ident;
1151    let name_str = fn_name.to_string();
1152
1153    // Strip optional "scope_" prefix (Laravel convention).
1154    let public_name_str = name_str.strip_prefix("scope_").unwrap_or(&name_str);
1155    let public_name = syn::Ident::new(public_name_str, fn_name.span());
1156
1157    let vis = &func.vis;
1158    let output_ty = &func.sig.output;
1159
1160    // Name of the first parameter (the query builder).
1161    let first_pat = match func.sig.inputs.first().unwrap() {
1162        syn::FnArg::Typed(pat_type) => pat_type.pat.as_ref().clone(),
1163        _ => unreachable!(),
1164    };
1165
1166    // Remaining params (everything after the query).
1167    let remaining: Vec<_> = func.sig.inputs.iter().skip(1).cloned().collect();
1168
1169    // Prepend `let <query> = Self::query();` to the function body.
1170    let mut stmts = func.block.stmts;
1171    let query_stmt: syn::Stmt = syn::parse_quote! {
1172        let #first_pat = Self::query();
1173    };
1174    stmts.insert(0, query_stmt);
1175
1176    let expanded = quote! {
1177        #vis fn #public_name(#(#remaining),*) #output_ty {
1178            #(#stmts)*
1179        }
1180    };
1181
1182    TokenStream::from(expanded)
1183}
1184
1185// ---------------------------------------------------------------------------
1186// Attribute: #[route]  (on impl blocks)
1187//
1188// Scans method-level #[get("…")], #[post("…")] etc. markers and generates
1189// a `register_routes(&Registrar)` method.
1190//
1191// Usage:
1192//   #[route]
1193//   impl MyController {
1194//       #[get("/users")]
1195//       async fn index() -> impl IntoResponse { … }
1196//
1197//       #[post("/users")]
1198//       async fn store(Json(body): Json<Input>) -> impl IntoResponse { … }
1199//   }
1200// ---------------------------------------------------------------------------
1201
1202#[proc_macro_attribute]
1203pub fn route(_attr: TokenStream, item: TokenStream) -> TokenStream {
1204    let item_str = item.to_string();
1205
1206    // Only process impl blocks.
1207    if !item_str.starts_with("impl") {
1208        return item;
1209    }
1210
1211    let input: ItemImpl = syn::parse(item.clone()).unwrap();
1212    let self_ty = input.self_ty.clone();
1213    let mut registrations = Vec::new();
1214    let mut clean_fns = Vec::new();
1215
1216    // First pass: collect registrations and rebuild clean methods.
1217    for method_item in &input.items {
1218        if let ImplItem::Fn(m) = method_item {
1219            let mut method_name: Option<String> = None;
1220            let mut uri: Option<String> = None;
1221            let mut middleware_names: Vec<String> = Vec::new();
1222
1223            for attr in &m.attrs {
1224                if let Some(ident) = attr.path().get_ident() {
1225                    let name = ident.to_string();
1226                    if matches!(
1227                        name.as_str(),
1228                        "get" | "post" | "put" | "patch" | "delete" | "ws"
1229                    ) {
1230                        let parsed: UriArg = attr.parse_args().unwrap();
1231                        method_name = Some(name.to_uppercase());
1232                        uri = Some(parsed.uri);
1233                    } else if name == "middleware" {
1234                        let parsed: MiddlewareArgs = attr.parse_args().unwrap();
1235                        middleware_names = parsed.names;
1236                    }
1237                }
1238            }
1239
1240            let fn_name = &m.sig.ident;
1241            let (attrs, vis, sig, block) = (&m.attrs, &m.vis, &m.sig, &m.block);
1242
1243            // Keep attributes that are NOT route markers or middleware.
1244            let kept_attrs: Vec<_> = attrs
1245                .iter()
1246                .filter(|a| {
1247                    a.path().get_ident().map(|i| i.to_string()).is_none_or(|n| {
1248                        !matches!(
1249                            n.as_str(),
1250                            "get" | "post" | "put" | "patch" | "delete" | "ws" | "middleware"
1251                        )
1252                    })
1253                })
1254                .collect();
1255
1256            clean_fns.push(quote! {
1257                #(#kept_attrs)*
1258                #vis #sig #block
1259            });
1260
1261            if let (Some(method), Some(uri)) = (method_name, uri) {
1262                let method_ident =
1263                    syn::Ident::new(&method.to_lowercase(), proc_macro2::Span::call_site());
1264
1265                // Set per-route middleware.
1266                let mw_strings: Vec<_> = middleware_names
1267                    .iter()
1268                    .map(|n| proc_macro2::Literal::string(n))
1269                    .collect();
1270                let mw_set = if mw_strings.is_empty() {
1271                    quote! { registrar.with_middleware(Vec::<&str>::new()); }
1272                } else {
1273                    quote! { registrar.with_middleware(vec![#(#mw_strings),*]); }
1274                };
1275
1276                let registrar_call = if method == "WS" {
1277                    quote! {
1278                        #mw_set
1279                        registrar.ws(#uri, Self::#fn_name);
1280                    }
1281                } else {
1282                    quote! {
1283                        #mw_set
1284                        registrar.#method_ident(#uri, Self::#fn_name);
1285                    }
1286                };
1287                registrations.push(registrar_call);
1288            }
1289        }
1290    }
1291
1292    let gen = quote! {
1293        impl #self_ty {
1294            #(#clean_fns)*
1295        }
1296
1297        impl #self_ty {
1298            pub fn register_routes(registrar: &larastvel_core::routing::Registrar) {
1299                #(#registrations)*
1300            }
1301        }
1302    };
1303
1304    TokenStream::from(gen)
1305}
1306
1307// ---------------------------------------------------------------------------
1308// Attribute: #[notification]
1309//
1310// Generates a Notification trait implementation from an impl block by
1311// scanning for notification-specific methods (via, to_mail, to_broadcast,
1312// to_database, to_webhook, to_sms).  Non-notification methods remain on
1313// the original impl block.
1314//
1315// Usage:
1316// ```rust,ignore
1317// #[derive(Debug)]
1318// struct InvoicePaid {
1319//     invoice_id: i32,
1320// }
1321//
1322// #[notification]
1323// impl InvoicePaid {
1324//     fn via(&self) -> Vec<NotificationChannel> {
1325//         vec![NotificationChannel::Mail]
1326//     }
1327//
1328//     fn to_mail(&self) -> Option<Mailable> {
1329//         Some(Mailable::html(vec![], "Invoice Paid", "<p>...</p>"))
1330//     }
1331// }
1332// ```
1333// ---------------------------------------------------------------------------
1334
1335#[proc_macro_attribute]
1336pub fn notification(_attr: TokenStream, item: TokenStream) -> TokenStream {
1337    let input: syn::ItemImpl = parse_macro_input!(item as syn::ItemImpl);
1338    let struct_ty = &input.self_ty;
1339    let generics = &input.generics;
1340    let where_clause = &input.generics.where_clause;
1341
1342    let known_methods: [&str; 6] = [
1343        "via",
1344        "to_mail",
1345        "to_broadcast",
1346        "to_database",
1347        "to_webhook",
1348        "to_sms",
1349    ];
1350
1351    let mut notification_impls = Vec::new();
1352    let mut kept_items = Vec::new();
1353
1354    for item in input.items {
1355        if let syn::ImplItem::Fn(method) = &item {
1356            if known_methods.contains(&method.sig.ident.to_string().as_str()) {
1357                notification_impls.push(item);
1358                continue;
1359            }
1360        }
1361        kept_items.push(item);
1362    }
1363
1364    let expanded = quote! {
1365        impl #generics #struct_ty #where_clause {
1366            #(#kept_items)*
1367        }
1368
1369        impl #generics larastvel_core::notifications::Notification for #struct_ty #where_clause {
1370            #(#notification_impls)*
1371        }
1372    };
1373
1374    TokenStream::from(expanded)
1375}
1376
1377// ---------------------------------------------------------------------------
1378// Attribute: #[rule]
1379//
1380// Generates a ValidationRule trait implementation from an impl block by
1381// scanning for a `validate` method.  The `name()` method is auto-derived
1382// from the struct name (snake_case).  Non-rule methods remain on the
1383// original impl block.
1384//
1385// Usage:
1386// ```rust,ignore
1387// #[derive(Debug, Clone)]
1388// struct UpperCaseRule;
1389//
1390// #[rule]
1391// impl UpperCaseRule {
1392//     fn validate(&self, field: &str, value: &str) -> Result<(), ValidationError> {
1393//         if value.chars().any(|c| c.is_lowercase()) {
1394//             return Err(ValidationError::new(
1395//                 format!("The {} must be uppercase.", field),
1396//             ));
1397//         }
1398//         Ok(())
1399//     }
1400// }
1401// ```
1402// ---------------------------------------------------------------------------
1403
1404#[proc_macro_attribute]
1405pub fn rule(_attr: TokenStream, item: TokenStream) -> TokenStream {
1406    let input: syn::ItemImpl = parse_macro_input!(item as syn::ItemImpl);
1407    let struct_ty = &input.self_ty;
1408    let generics = &input.generics;
1409    let where_clause = &input.generics.where_clause;
1410
1411    // Derive name() from the struct name: PascalCase -> snake_case
1412    let struct_name = struct_ty_to_string(struct_ty);
1413    let rule_name = pascal_to_snake(&struct_name);
1414
1415    let mut validate_method: Option<syn::ImplItemFn> = None;
1416    let mut kept_items = Vec::new();
1417
1418    for item in input.items {
1419        if let syn::ImplItem::Fn(method) = &item {
1420            if method.sig.ident == "validate" {
1421                validate_method = Some(method.clone());
1422                continue;
1423            }
1424        }
1425        kept_items.push(item);
1426    }
1427
1428    let validate = match validate_method {
1429        Some(m) => quote! { #m },
1430        None => {
1431            return syn::Error::new(
1432                proc_macro2::Span::call_site(),
1433                "#[rule] requires a `validate` method on the impl block",
1434            )
1435            .to_compile_error()
1436            .into();
1437        }
1438    };
1439
1440    let expanded = quote! {
1441        impl #generics #struct_ty #where_clause {
1442            #(#kept_items)*
1443        }
1444
1445        impl #generics larastvel_core::validation::ValidationRule for #struct_ty #where_clause {
1446            fn name(&self) -> &str {
1447                #rule_name
1448            }
1449
1450            #validate
1451        }
1452    };
1453
1454    TokenStream::from(expanded)
1455}
1456
1457fn struct_ty_to_string(ty: &syn::Type) -> String {
1458    // Extract the simple type name: e.g. MyRule<T> -> "MyRule"
1459    match ty {
1460        syn::Type::Path(p) => p
1461            .path
1462            .segments
1463            .last()
1464            .map(|s| s.ident.to_string())
1465            .unwrap_or_default(),
1466        _ => String::new(),
1467    }
1468}
1469
1470fn pascal_to_snake(s: &str) -> String {
1471    let mut result = String::new();
1472    for (i, c) in s.char_indices() {
1473        if i > 0 && c.is_uppercase() {
1474            result.push('_');
1475        }
1476        result.push(c.to_ascii_lowercase());
1477    }
1478    result
1479}
1480
1481// ---------------------------------------------------------------------------
1482// Attribute: #[observer(Model)]
1483//
1484// Generates Listener implementations for model lifecycle events based on
1485// hook methods defined on an impl block.
1486//
1487// The attribute goes on an impl block for an observer struct. Hook methods
1488// are scanned by name (`created`, `updated`, `deleted`, `saved`,
1489// `retrieved`) and each generates a `Listener<ModelEvent<M::Entity>>`
1490// implementation.  An `observe()` method is also generated to register
1491// all listeners with `EventService`.
1492//
1493// Usage:
1494// ```rust,ignore
1495// struct UserObserver;
1496//
1497// #[observer(User)]
1498// impl UserObserver {
1499//     async fn created(&self, model: Model) {
1500//         tracing::info!("User created: {}", model.email);
1501//     }
1502//
1503//     async fn deleted(&self, model: Model) {
1504//         tracing::info!("User deleted: {}", model.email);
1505//     }
1506// }
1507//
1508// // Register the observer at app boot:
1509// UserObserver::observe();
1510// ```
1511// ---------------------------------------------------------------------------
1512
1513#[proc_macro_attribute]
1514pub fn observer(attr: TokenStream, item: TokenStream) -> TokenStream {
1515    let model_ty: syn::Type = parse_macro_input!(attr as syn::Type);
1516    let input: syn::ItemImpl = parse_macro_input!(item as syn::ItemImpl);
1517
1518    let struct_ty = &input.self_ty;
1519
1520    let entity_ty = quote! {
1521        <#model_ty as larastvel_core::models::DbModel>::Entity
1522    };
1523    let event_mod = quote! { larastvel_core::events };
1524    let listener_trait = quote! { larastvel_core::events::Listener };
1525
1526    // Known hook method names and their corresponding event type stems
1527    let hooks: [(&str, &str); 5] = [
1528        ("created", "ModelCreated"),
1529        ("updated", "ModelUpdated"),
1530        ("deleted", "ModelDeleted"),
1531        ("saved", "ModelSaved"),
1532        ("retrieved", "ModelRetrieved"),
1533    ];
1534
1535    // Scan the impl block for hook methods
1536    let mut listener_impls = Vec::new();
1537    let mut observe_calls = Vec::new();
1538
1539    for item in &input.items {
1540        if let syn::ImplItem::Fn(method) = item {
1541            let method_name = method.sig.ident.to_string();
1542            if let Some(&(_, event_stem)) = hooks.iter().find(|(name, _)| *name == method_name) {
1543                let event_ident = syn::Ident::new(event_stem, method.sig.ident.span());
1544                let hook_method = &method.sig.ident;
1545
1546                // Generate Listener<ModelEvent<M::Entity>> implementation
1547                listener_impls.push(quote! {
1548                    #[larastvel_core::async_trait]
1549                    impl #listener_trait<#event_mod::#event_ident<#entity_ty>> for #struct_ty {
1550                        async fn handle(&self, event: #event_mod::#event_ident<#entity_ty>) {
1551                            self.#hook_method(event.0).await;
1552                        }
1553                    }
1554                });
1555
1556                // Generate the observe() registration call
1557                observe_calls.push(quote! {
1558                    larastvel_core::events::EventService::listen::<#event_mod::#event_ident<#entity_ty>, Self>(Self);
1559                });
1560            }
1561        }
1562    }
1563
1564    let expanded = quote! {
1565        #input
1566
1567        #(#listener_impls)*
1568
1569        impl #struct_ty {
1570            /// Register this observer's hook methods as event listeners.
1571            pub fn observe() {
1572                #(#observe_calls)*
1573            }
1574        }
1575    };
1576
1577    TokenStream::from(expanded)
1578}
1579
1580// ---------------------------------------------------------------------------
1581// Attribute: command
1582// ---------------------------------------------------------------------------
1583
1584struct CommandArgs {
1585    name: String,
1586    description: String,
1587}
1588
1589impl Parse for CommandArgs {
1590    fn parse(input: ParseStream) -> syn::Result<Self> {
1591        let name: syn::LitStr = input.parse()?;
1592        let mut description = String::new();
1593        if input.peek(syn::Token![,]) {
1594            input.parse::<syn::Token![,]>()?;
1595            let ident: syn::Ident = input.parse()?;
1596            if ident == "description" {
1597                input.parse::<syn::Token![=]>()?;
1598                description = input.parse::<syn::LitStr>()?.value();
1599            }
1600        }
1601        Ok(CommandArgs {
1602            name: name.value(),
1603            description,
1604        })
1605    }
1606}
1607
1608#[proc_macro_attribute]
1609pub fn command(attr: TokenStream, item: TokenStream) -> TokenStream {
1610    let args = parse_macro_input!(attr as CommandArgs);
1611    let input = parse_macro_input!(item as ItemStruct);
1612    let name = &input.ident;
1613
1614    let command_name = &args.name;
1615    let description = &args.description;
1616
1617    let expanded = quote! {
1618        #input
1619
1620        impl larastvel_core::console::Command for #name {
1621            fn name(&self) -> &'static str {
1622                #command_name
1623            }
1624
1625            fn description(&self) -> &'static str {
1626                #description
1627            }
1628
1629            fn handle(
1630                &self,
1631                app: &larastvel_core::foundation::Application,
1632                args: &[String],
1633            ) -> Result<(), larastvel_core::console::ConsoleError> {
1634                self.run(app, args)
1635            }
1636        }
1637    };
1638
1639    TokenStream::from(expanded)
1640}
1641
1642// ---------------------------------------------------------------------------
1643// Attribute: policy
1644// ---------------------------------------------------------------------------
1645
1646#[proc_macro_attribute]
1647pub fn policy(attr: TokenStream, item: TokenStream) -> TokenStream {
1648    let resource_name = parse_macro_input!(attr as syn::LitStr);
1649    let input = parse_macro_input!(item as ItemStruct);
1650    let name = &input.ident;
1651    let resource = resource_name.value();
1652
1653    let expanded = quote! {
1654        #input
1655
1656        impl #name {
1657            /// Register this policy with the given gate.
1658            pub fn register(gate: &larastvel_core::auth::Gate) {
1659                gate.register_policy(#resource, std::sync::Arc::new(#name));
1660            }
1661        }
1662
1663        impl larastvel_core::auth::Policy for #name {
1664            fn resource(&self) -> &str {
1665                #resource
1666            }
1667
1668            fn check(
1669                &self,
1670                user: &larastvel_core::auth::AuthenticatedUser,
1671                ability: &str,
1672                args: &[String],
1673            ) -> Option<larastvel_core::auth::GateCheck> {
1674                self.check_ability(user, ability, args)
1675            }
1676        }
1677    };
1678
1679    TokenStream::from(expanded)
1680}
1681
1682// ---------------------------------------------------------------------------
1683// Attribute: factory
1684// ---------------------------------------------------------------------------
1685
1686#[proc_macro_attribute]
1687pub fn factory(attr: TokenStream, item: TokenStream) -> TokenStream {
1688    let model_name = parse_macro_input!(attr as syn::LitStr);
1689    let input = parse_macro_input!(item as ItemStruct);
1690    let name = &input.ident;
1691    let model = model_name.value();
1692    let model_ident = syn::Ident::new(&model, model_name.span());
1693
1694    let expanded = quote! {
1695        #input
1696
1697        impl larastvel_core::models::factory::ModelFactory for #name {
1698            type ActiveModel = crate::models::#model_ident::ActiveModel;
1699
1700            fn definition() -> Self::ActiveModel {
1701                Self::define()
1702            }
1703        }
1704    };
1705
1706    TokenStream::from(expanded)
1707}
1708
1709// ---------------------------------------------------------------------------
1710// Attribute: seeder
1711// ---------------------------------------------------------------------------
1712
1713struct SeederArgs {
1714    name: Option<String>,
1715}
1716
1717impl Parse for SeederArgs {
1718    fn parse(input: ParseStream) -> syn::Result<Self> {
1719        if input.is_empty() {
1720            Ok(SeederArgs { name: None })
1721        } else {
1722            let name: syn::LitStr = input.parse()?;
1723            Ok(SeederArgs {
1724                name: Some(name.value()),
1725            })
1726        }
1727    }
1728}
1729
1730#[proc_macro_attribute]
1731pub fn seeder(attr: TokenStream, item: TokenStream) -> TokenStream {
1732    let args = parse_macro_input!(attr as SeederArgs);
1733    let input = parse_macro_input!(item as ItemStruct);
1734    let name = &input.ident;
1735    let seeder_name = args
1736        .name
1737        .unwrap_or_else(|| pascal_to_snake(&name.to_string()));
1738
1739    let expanded = quote! {
1740        #input
1741
1742        #[larastvel_core::async_trait]
1743        impl larastvel_core::database::Seeder for #name {
1744            fn name() -> &'static str {
1745                #seeder_name
1746            }
1747
1748            async fn run(
1749                conn: &larastvel_core::sea_orm::DbConn,
1750            ) -> Result<(), Box<dyn std::error::Error>> {
1751                Self::seed(conn).await
1752            }
1753        }
1754    };
1755
1756    TokenStream::from(expanded)
1757}
1758
1759// ---------------------------------------------------------------------------
1760// Attribute: provider
1761// ---------------------------------------------------------------------------
1762
1763#[proc_macro_attribute]
1764pub fn provider(_attr: TokenStream, item: TokenStream) -> TokenStream {
1765    let input = parse_macro_input!(item as ItemStruct);
1766    let name = &input.ident;
1767
1768    let expanded = quote! {
1769        #input
1770
1771        impl larastvel_core::foundation::ServiceProvider for #name {
1772            fn register(&self, app: &larastvel_core::foundation::Application) {
1773                self.register_services(app)
1774            }
1775        }
1776    };
1777
1778    TokenStream::from(expanded)
1779}
1780
1781// ---------------------------------------------------------------------------
1782// Attribute: api_resource
1783// ---------------------------------------------------------------------------
1784
1785struct ApiResourceArgs {
1786    model_type: syn::Type,
1787}
1788
1789impl Parse for ApiResourceArgs {
1790    fn parse(input: ParseStream) -> syn::Result<Self> {
1791        let model_type: syn::Type = input.parse()?;
1792        Ok(ApiResourceArgs { model_type })
1793    }
1794}
1795
1796#[proc_macro_attribute]
1797pub fn api_resource(attr: TokenStream, item: TokenStream) -> TokenStream {
1798    let args = parse_macro_input!(attr as ApiResourceArgs);
1799    let input = parse_macro_input!(item as ItemStruct);
1800    let name = &input.ident;
1801    let model_ty = &args.model_type;
1802
1803    let expanded = quote! {
1804        #input
1805
1806        impl larastvel_core::models::serialization::ApiResource<#model_ty> for #name {
1807            fn transform(model: &#model_ty) -> serde_json::Value {
1808                Self::to_array(model)
1809            }
1810        }
1811    };
1812
1813    TokenStream::from(expanded)
1814}
1815
1816// ---------------------------------------------------------------------------
1817// Attribute: json_api_resource
1818// ---------------------------------------------------------------------------
1819
1820struct JsonApiResourceArgs {
1821    model_type: syn::Type,
1822}
1823
1824impl Parse for JsonApiResourceArgs {
1825    fn parse(input: ParseStream) -> syn::Result<Self> {
1826        let model_type: syn::Type = input.parse()?;
1827        Ok(JsonApiResourceArgs { model_type })
1828    }
1829}
1830
1831#[proc_macro_attribute]
1832pub fn json_api_resource(attr: TokenStream, item: TokenStream) -> TokenStream {
1833    let args = parse_macro_input!(attr as JsonApiResourceArgs);
1834    let input = parse_macro_input!(item as ItemImpl);
1835    let name = &input.self_ty;
1836    let model_ty = &args.model_type;
1837
1838    let mut methods = std::collections::HashSet::new();
1839    for impl_item in &input.items {
1840        if let syn::ImplItem::Fn(fun) = impl_item {
1841            methods.insert(fun.sig.ident.to_string());
1842        }
1843    }
1844
1845    let mut generated = Vec::new();
1846    if methods.contains("attributes") {
1847        generated.push(quote! {
1848            fn attributes(model: &#model_ty) -> serde_json::Value {
1849                Self::attributes(model)
1850            }
1851        });
1852    }
1853    if methods.contains("id") {
1854        generated.push(quote! {
1855            fn id(model: &#model_ty) -> String {
1856                Self::id(model)
1857            }
1858        });
1859    }
1860    if methods.contains("type_") {
1861        generated.push(quote! {
1862            fn type_() -> String {
1863                Self::type_()
1864            }
1865        });
1866    }
1867    if methods.contains("relationships") {
1868        generated.push(quote! {
1869            fn relationships(
1870                model: &#model_ty,
1871                query: &larastvel_core::models::jsonapi::JsonApiQuery,
1872            ) -> serde_json::Value {
1873                Self::relationships(model, query)
1874            }
1875        });
1876    }
1877    if methods.contains("links") {
1878        generated.push(quote! {
1879            fn links(model: &#model_ty) -> serde_json::Value {
1880                Self::links(model)
1881            }
1882        });
1883    }
1884    if methods.contains("meta") {
1885        generated.push(quote! {
1886            fn meta(model: &#model_ty) -> serde_json::Value {
1887                Self::meta(model)
1888            }
1889        });
1890    }
1891
1892    let expanded = quote! {
1893        #input
1894
1895        impl larastvel_core::models::jsonapi::JsonApiResource<#model_ty> for #name {
1896            #(#generated)*
1897        }
1898    };
1899
1900    TokenStream::from(expanded)
1901}
1902
1903// ---------------------------------------------------------------------------
1904// Attribute: broadcast_event
1905// ---------------------------------------------------------------------------
1906
1907#[proc_macro_attribute]
1908pub fn broadcast_event(attr: TokenStream, item: TokenStream) -> TokenStream {
1909    let event_name = parse_macro_input!(attr as syn::LitStr);
1910    let input = parse_macro_input!(item as ItemStruct);
1911    let name = &input.ident;
1912    let name_str = event_name.value();
1913
1914    let expanded = quote! {
1915        #input
1916
1917        impl larastvel_core::broadcasting::BroadcastEvent for #name {
1918            fn broadcast_event_name(&self) -> &str {
1919                #name_str
1920            }
1921
1922            fn broadcast_channels(&self) -> Vec<larastvel_core::broadcasting::Channel> {
1923                self.channels()
1924            }
1925        }
1926    };
1927
1928    TokenStream::from(expanded)
1929}
1930
1931// ---------------------------------------------------------------------------
1932// Attribute: mail
1933// ---------------------------------------------------------------------------
1934
1935struct MailArgs {
1936    subject: String,
1937    from: Option<String>,
1938    reply_to: Option<String>,
1939}
1940
1941impl Parse for MailArgs {
1942    fn parse(input: ParseStream) -> syn::Result<Self> {
1943        let mut subject = None;
1944        let mut from = None;
1945        let mut reply_to = None;
1946
1947        while !input.is_empty() {
1948            let ident: syn::Ident = input.parse()?;
1949            input.parse::<syn::Token![=]>()?;
1950            let value: syn::LitStr = input.parse()?;
1951            match ident.to_string().as_str() {
1952                "subject" => subject = Some(value.value()),
1953                "from" => from = Some(value.value()),
1954                "reply_to" => reply_to = Some(value.value()),
1955                other => {
1956                    return Err(syn::Error::new(
1957                        ident.span(),
1958                        format!("unknown mail argument: {}", other),
1959                    ));
1960                }
1961            }
1962            if !input.is_empty() {
1963                input.parse::<syn::Token![,]>()?;
1964            }
1965        }
1966
1967        let subject = subject.ok_or_else(|| {
1968            syn::Error::new(proc_macro2::Span::call_site(), "#[mail] requires `subject`")
1969        })?;
1970
1971        Ok(MailArgs {
1972            subject,
1973            from,
1974            reply_to,
1975        })
1976    }
1977}
1978
1979#[proc_macro_attribute]
1980pub fn mail(attr: TokenStream, item: TokenStream) -> TokenStream {
1981    let args = parse_macro_input!(attr as MailArgs);
1982    let input = parse_macro_input!(item as ItemStruct);
1983    let name = &input.ident;
1984    let subject = &args.subject;
1985
1986    let from_chain = args.from.as_ref().map(|f| {
1987        quote! { .from(#f) }
1988    });
1989
1990    let reply_to_chain = args.reply_to.as_ref().map(|r| {
1991        quote! { .reply_to(#r) }
1992    });
1993
1994    let expanded = quote! {
1995        #input
1996
1997        impl #name {
1998            /// Send this mail using the given mailer.
1999            pub async fn send(
2000                &self,
2001                mailer: &dyn larastvel_core::mail::Mailer,
2002            ) -> Result<(), larastvel_core::mail::MailError> {
2003                let mailable = larastvel_core::mail::Mailable::html(
2004                    self.to.clone(),
2005                    #subject,
2006                    &self.html(),
2007                )
2008                #from_chain
2009                #reply_to_chain;
2010                mailer.send(mailable).await
2011            }
2012        }
2013    };
2014
2015    TokenStream::from(expanded)
2016}
2017
2018// ---------------------------------------------------------------------------
2019// Attribute: #[bind_when(alias = "name", condition_key = "config.path")]
2020//
2021// Mirrors Laravel 13.22's `#[BindWhen]`: declares a conditional container
2022// binding on a trait. Conditions are evaluated at resolve time; when the
2023// config value at `condition_key` is truthy, the binding resolves the
2024// configured instance for the trait's alias.
2025//
2026// Usage:
2027//   #[bind_when(alias = "payment-gateway", condition_key = "features.payments.beta")]
2028//   trait PaymentGateway: Send + Sync + 'static {}
2029//
2030// Expands to (in addition to the original trait) a companion struct
2031// `PaymentGatewayConditionalBindings` with:
2032//   pub const ALIAS: &'static str = "payment-gateway";
2033//   pub const CONDITION_KEY: &'static str = "features.payments.beta";
2034//   pub fn conditional_enabled(app: &Application) -> bool;
2035//   pub fn register_conditional_binding(
2036//       app, when_enabled: impl FnOnce() -> Arc<dyn PaymentGateway>,
2037//   ) { app.bind_if_config(...); }
2038//   pub fn resolve(app) -> Option<Arc<dyn PaymentGateway>> { ... }
2039// ---------------------------------------------------------------------------
2040
2041#[proc_macro_attribute]
2042pub fn bind_when(attr: TokenStream, item: TokenStream) -> TokenStream {
2043    let args = parse_macro_input!(attr as BindWhenArgs);
2044    let input = parse_macro_input!(item as ItemTrait);
2045    let name = &input.ident;
2046    let helper = syn::Ident::new(&format!("{}ConditionalBindings", name), name.span());
2047    let alias = &args.alias;
2048    let condition_key = &args.condition_key;
2049
2050    let expanded = quote! {
2051        #input
2052
2053        /// Auto-generated registry for this trait's `#[bind_when]` conditional
2054        /// container bindings (declared next to the trait, like Laravel's
2055        /// `#[BindWhen]` attribute).
2056        #[allow(non_camel_case_types)]
2057        pub struct #helper;
2058
2059        impl #helper {
2060            /// The container alias registered for this trait's conditional bindings.
2061            pub const ALIAS: &'static str = #alias;
2062
2063            /// Config key gating the conditional binding.
2064            pub const CONDITION_KEY: &'static str = #condition_key;
2065
2066            /// Whether the conditional binding is currently enabled per config.
2067            pub fn conditional_enabled(app: &larastvel_core::foundation::Application) -> bool {
2068                app.config_bool(Self::CONDITION_KEY)
2069            }
2070
2071            /// Register this trait's conditional binding.
2072            ///
2073            /// The binding is stored under [`Self::ALIAS`] and can be resolved
2074            /// again with [`resolve`](Self::resolve). Conditions are evaluated
2075            /// at resolve time against the live application config.
2076            pub fn register_conditional_binding(
2077                app: &larastvel_core::foundation::Application,
2078                when_enabled: impl FnOnce() -> std::sync::Arc<dyn #name>,
2079            ) {
2080                app.bind_if_config(Self::ALIAS, Self::CONDITION_KEY, when_enabled());
2081            }
2082
2083            /// Resolve the conditional binding for this trait, if the
2084            /// condition is currently satisfied.
2085            pub fn resolve(
2086                app: &larastvel_core::foundation::Application,
2087            ) -> Option<std::sync::Arc<dyn #name>> {
2088                app.make_by_alias(Self::ALIAS)
2089            }
2090        }
2091    };
2092
2093    TokenStream::from(expanded)
2094}
2095
2096struct BindWhenArgs {
2097    alias: String,
2098    condition_key: String,
2099}
2100
2101impl Parse for BindWhenArgs {
2102    fn parse(input: ParseStream) -> syn::Result<Self> {
2103        let mut alias = None;
2104        let mut condition_key = None;
2105
2106        while !input.is_empty() {
2107            let ident: Ident = input.parse()?;
2108            input.parse::<syn::Token![=]>()?;
2109            let value: LitStr = input.parse()?;
2110            let name = ident.to_string();
2111            if name == "alias" {
2112                alias = Some(value.value());
2113            } else if name == "condition_key" {
2114                condition_key = Some(value.value());
2115            } else {
2116                return Err(syn::Error::new(
2117                    ident.span(),
2118                    format!("unknown #[bind_when] attribute: {name}"),
2119                ));
2120            }
2121            if !input.is_empty() {
2122                input.parse::<syn::Token![,]>()?;
2123            }
2124        }
2125
2126        Ok(BindWhenArgs {
2127            alias: alias.ok_or_else(|| input.error("missing `alias = \"...\"` argument"))?,
2128            condition_key: condition_key
2129                .ok_or_else(|| input.error("missing `condition_key = \"...\"` argument"))?,
2130        })
2131    }
2132}