Skip to main content

luxid_macros/
lib.rs

1//! Procedural macros for Luxid.
2//!
3//! Neither macro emits salvo types — generated code depends only on Luxid's own
4//! traits, which keeps the substrate sealed even in macro output.
5
6mod model;
7mod relation;
8mod testing;
9mod validate;
10
11use proc_macro::TokenStream;
12use proc_macro2::TokenStream as TokenStream2;
13use quote::{format_ident, quote};
14use syn::parse::{Parse, ParseStream};
15use syn::{
16    Attribute, FnArg, ImplItem, ImplItemFn, ItemImpl, LitInt, LitStr, Token, Type,
17    parse_macro_input, parse_quote,
18};
19
20/// Turn an inherent `impl` block into routable actions.
21///
22/// Every `async fn name(ctx: HttpContext) -> Result<Response>` becomes a
23/// zero-sized handler exposed as an associated constant, so routes read
24/// `UsersController::index` with no parentheses. Other items are left alone.
25#[proc_macro_attribute]
26pub fn controller(_attr: TokenStream, item: TokenStream) -> TokenStream {
27    let mut block = parse_macro_input!(item as ItemImpl);
28
29    let self_ty = block.self_ty.clone();
30    let ty_ident = match inherent_ident(&block) {
31        Ok(ident) => ident,
32        Err(err) => return err.to_compile_error().into(),
33    };
34
35    let mut handlers: Vec<TokenStream2> = Vec::new();
36    let mut constants: Vec<TokenStream2> = Vec::new();
37    let mut resource: Vec<TokenStream2> = Vec::new();
38
39    for item in &mut block.items {
40        let ImplItem::Fn(func) = item else { continue };
41        if !is_action(func) {
42            continue;
43        }
44
45        // `#[openapi(..)]` is not a real attribute; the controller macro owns it.
46        let documentation = match take_openapi(&mut func.attrs) {
47            Ok(documentation) => documentation,
48            Err(err) => return err.to_compile_error().into(),
49        };
50
51        let action = func.sig.ident.clone();
52        let inner = format_ident!("__luxid_action_{}", action);
53        func.sig.ident = inner.clone();
54        func.vis = parse_quote!(pub);
55
56        let handler_ty = format_ident!("__LuxidAction_{}_{}", ty_ident, action);
57        let docs = format!("Route handler for [`{ty_ident}::{action}`].");
58        let action_label = format!("{ty_ident}::{action}");
59
60        handlers.push(quote! {
61            #[doc = #docs]
62            #[doc(hidden)]
63            #[allow(non_camel_case_types)]
64            #[derive(Clone, Copy, Debug, Default)]
65            pub struct #handler_ty;
66
67            impl ::luxid::__private::Action for #handler_ty {
68                fn call(
69                    &self,
70                    ctx: ::luxid::HttpContext,
71                ) -> ::luxid::__private::BoxFuture<'static, ::luxid::Result<::luxid::Response>> {
72                    ::std::boxed::Box::pin(#self_ty::#inner(ctx))
73                }
74
75                fn name(&self) -> &'static str {
76                    #action_label
77                }
78
79                #documentation
80            }
81        });
82
83        constants.push(quote! {
84            #[allow(non_upper_case_globals)]
85            pub const #action: #handler_ty = #handler_ty;
86        });
87
88        // Only the actions that exist become routes.
89        let registration = match action.to_string().as_str() {
90            "index" => Some(quote!(router.get("", Self::index);)),
91            "store" => Some(quote!(router.post("", Self::store);)),
92            "show" => Some(quote!(router.get("/{id}", Self::show);)),
93            "update" => Some(quote!(router.put("/{id}", Self::update);)),
94            "destroy" => Some(quote!(router.delete("/{id}", Self::destroy);)),
95            _ => None,
96        };
97
98        if let Some(registration) = registration {
99            resource.push(registration);
100        }
101    }
102
103    // A controller with none of the five resource actions gets no impl, so
104    // `r.resource(..)` on it is a compile error rather than a route table that
105    // silently registers nothing.
106    let resource_impl = if resource.is_empty() {
107        quote!()
108    } else {
109        quote! {
110            impl ::luxid::__private::ResourceRoutes for #self_ty {
111                fn register(router: &mut ::luxid::Router) {
112                    #(#resource)*
113                }
114            }
115        }
116    };
117
118    quote! {
119        #block
120
121        #(#handlers)*
122
123        impl #self_ty {
124            #(#constants)*
125        }
126
127        #resource_impl
128    }
129    .into()
130}
131
132/// Implement `Middleware` from an inherent
133/// `async fn handle(&self, ctx: HttpContext, next: Next) -> Result<Response>`.
134#[proc_macro_attribute]
135pub fn middleware(_attr: TokenStream, item: TokenStream) -> TokenStream {
136    let mut block = parse_macro_input!(item as ItemImpl);
137
138    let self_ty = block.self_ty.clone();
139    if let Err(err) = inherent_ident(&block) {
140        return err.to_compile_error().into();
141    }
142
143    let mut found = false;
144
145    for item in &mut block.items {
146        let ImplItem::Fn(func) = item else { continue };
147        if func.sig.ident != "handle" {
148            continue;
149        }
150
151        if func.sig.asyncness.is_none() {
152            return syn::Error::new_spanned(&func.sig, "`handle` must be an async fn")
153                .to_compile_error()
154                .into();
155        }
156        if !matches!(func.sig.inputs.first(), Some(FnArg::Receiver(_))) {
157            return syn::Error::new_spanned(
158                &func.sig,
159                "`handle` must take `&self` so configured middleware can hold state",
160            )
161            .to_compile_error()
162            .into();
163        }
164
165        func.sig.ident = format_ident!("__luxid_middleware_handle");
166        found = true;
167        break;
168    }
169
170    if !found {
171        return syn::Error::new_spanned(
172            &self_ty,
173            "#[luxid::middleware] expects `async fn handle(&self, ctx: HttpContext, next: Next) -> Result<Response>`",
174        )
175        .to_compile_error()
176        .into();
177    }
178
179    quote! {
180        #block
181
182        impl ::luxid::__private::Middleware for #self_ty {
183            fn handle<'__luxid>(
184                &'__luxid self,
185                ctx: ::luxid::HttpContext,
186                next: ::luxid::Next,
187            ) -> ::luxid::__private::BoxFuture<'__luxid, ::luxid::Result<::luxid::Response>> {
188                ::std::boxed::Box::pin(Self::__luxid_middleware_handle(self, ctx, next))
189            }
190        }
191    }
192    .into()
193}
194
195/// Actions are `async fn name(ctx: HttpContext) -> Result<Response>`. Anything
196/// else in the block is a helper and stays untouched.
197///
198/// The argument's *type* is checked, not merely its count: a helper taking
199/// `&HttpContext` is a helper, and turning it into a route would be surprising.
200fn is_action(func: &ImplItemFn) -> bool {
201    if func.sig.asyncness.is_none() || func.sig.inputs.len() != 1 {
202        return false;
203    }
204
205    let Some(FnArg::Typed(argument)) = func.sig.inputs.first() else {
206        return false;
207    };
208
209    // By name rather than by resolution — a macro cannot resolve types, and an
210    // alias for `HttpContext` is vanishingly rare next to helpers taking a
211    // reference to one.
212    matches!(&*argument.ty, Type::Path(path)
213        if path.path.segments.last().is_some_and(|last| last.ident == "HttpContext"))
214}
215
216fn inherent_ident(block: &ItemImpl) -> syn::Result<syn::Ident> {
217    if block.trait_.is_some() {
218        return Err(syn::Error::new_spanned(
219            &block.self_ty,
220            "expected a plain inherent impl, not a trait implementation",
221        ));
222    }
223
224    match &*block.self_ty {
225        Type::Path(path) => path
226            .path
227            .segments
228            .last()
229            .map(|segment| segment.ident.clone())
230            .ok_or_else(|| syn::Error::new_spanned(&block.self_ty, "expected a named type")),
231        other => Err(syn::Error::new_spanned(
232            other,
233            "expected a named type, e.g. `impl UsersController`",
234        )),
235    }
236}
237
238/// Derive model operations and typed columns for a SeaORM entity model.
239///
240/// The model name used in 404s comes from `#[sea_orm(table_name = "...")]`,
241/// singularized. Override it with `#[luxid(name = "Person")]` when the naive
242/// rules get it wrong.
243#[proc_macro_derive(Model, attributes(luxid))]
244pub fn derive_model(item: TokenStream) -> TokenStream {
245    model::derive(item)
246}
247
248/// Declare a model's relations.
249///
250/// ```ignore
251/// #[luxid::model(
252///     has_many(posts = Post, fk = "user_id"),
253///     belongs_to(team = Team),
254/// )]
255/// impl User {}
256/// ```
257#[proc_macro_attribute]
258pub fn model(attr: TokenStream, item: TokenStream) -> TokenStream {
259    relation::model(attr, item)
260}
261
262/// A test that leaves the database as it found it.
263///
264/// See [`testing`](crate) for the full form; without `db = ..` this is
265/// `#[tokio::test]` with `Result` unwrapping.
266#[proc_macro_attribute]
267pub fn test(attr: TokenStream, item: TokenStream) -> TokenStream {
268    testing::test(attr, item)
269}
270
271/// Derive form-request validation.
272///
273/// Synchronous rules (`length`, `email`, `range`, `custom`) run first;
274/// asynchronous ones (`unique`, `exists`) run afterwards against the request's
275/// ambient database connection, skipping fields that already failed.
276#[proc_macro_derive(Validate, attributes(validate, luxid))]
277pub fn derive_validate(item: TokenStream) -> TokenStream {
278    validate::derive(item)
279}
280
281/// One `#[openapi(..)]` entry.
282struct OpenApi {
283    summary: Option<String>,
284    tag: Option<String>,
285    body: Option<Type>,
286    responses: Vec<(u16, Option<Type>)>,
287}
288
289impl Parse for OpenApi {
290    fn parse(input: ParseStream) -> syn::Result<Self> {
291        let mut documentation = OpenApi {
292            summary: None,
293            tag: None,
294            body: None,
295            responses: Vec::new(),
296        };
297
298        while !input.is_empty() {
299            let key: syn::Ident = input.parse()?;
300            let label = key.to_string();
301
302            match label.as_str() {
303                // `no_content` is a bare flag: 204 carries nothing by definition.
304                "no_content" => documentation.responses.push((204, None)),
305
306                "errors" => {
307                    input.parse::<Token![=]>()?;
308                    let statuses;
309                    syn::bracketed!(statuses in input);
310
311                    while !statuses.is_empty() {
312                        let status: LitInt = statuses.parse()?;
313                        documentation.responses.push((status.base10_parse()?, None));
314
315                        if statuses.peek(Token![,]) {
316                            statuses.parse::<Token![,]>()?;
317                        }
318                    }
319                }
320
321                "summary" | "tag" => {
322                    input.parse::<Token![=]>()?;
323                    let value: LitStr = input.parse()?;
324
325                    if label == "summary" {
326                        documentation.summary = Some(value.value());
327                    } else {
328                        documentation.tag = Some(value.value());
329                    }
330                }
331
332                "body" => {
333                    input.parse::<Token![=]>()?;
334                    documentation.body = Some(input.parse()?);
335                }
336
337                "ok" | "created" | "accepted" => {
338                    input.parse::<Token![=]>()?;
339                    let status = match label.as_str() {
340                        "ok" => 200,
341                        "created" => 201,
342                        _ => 202,
343                    };
344                    documentation.responses.push((status, Some(input.parse()?)));
345                }
346
347                other => {
348                    return Err(syn::Error::new_spanned(
349                        &key,
350                        format!(
351                            "`{other}` is not a recognised #[openapi] key. Expected one of: \
352                             summary, tag, body, ok, created, accepted, no_content, errors"
353                        ),
354                    ));
355                }
356            }
357
358            if input.peek(Token![,]) {
359                input.parse::<Token![,]>()?;
360            }
361        }
362
363        Ok(documentation)
364    }
365}
366
367/// Remove `#[openapi(..)]` from an action and render it as an `Action::openapi`
368/// implementation.
369fn take_openapi(attrs: &mut Vec<Attribute>) -> syn::Result<TokenStream2> {
370    let Some(index) = attrs
371        .iter()
372        .position(|attr| attr.path().is_ident("openapi"))
373    else {
374        return Ok(TokenStream2::new());
375    };
376
377    let attr = attrs.remove(index);
378    let documentation: OpenApi = attr.parse_args()?;
379
380    let summary = match &documentation.summary {
381        Some(text) => quote!(::std::option::Option::Some(#text)),
382        None => quote!(::std::option::Option::None),
383    };
384    let tag = match &documentation.tag {
385        Some(text) => quote!(::std::option::Option::Some(#text)),
386        None => quote!(::std::option::Option::None),
387    };
388    let body = match &documentation.body {
389        Some(ty) => quote!(::std::option::Option::Some(::luxid::__private::schema_of::<#ty>)),
390        None => quote!(::std::option::Option::None),
391    };
392
393    let responses = documentation.responses.iter().map(|(status, ty)| {
394        let schema = match ty {
395            Some(ty) => quote!(::std::option::Option::Some(::luxid::__private::schema_of::<#ty>)),
396            None => quote!(::std::option::Option::None),
397        };
398        quote! {
399            ::luxid::__private::ResponseSpec { status: #status, schema: #schema }
400        }
401    });
402
403    Ok(quote! {
404        fn openapi(&self) -> ::std::option::Option<::luxid::__private::Operation> {
405            ::std::option::Option::Some(::luxid::__private::Operation {
406                summary: #summary,
407                tag: #tag,
408                body: #body,
409                responses: ::std::vec![#(#responses),*],
410            })
411        }
412    })
413}