Skip to main content

dioxus_openapi_macros/
lib.rs

1use proc_macro::TokenStream;
2use proc_macro2::TokenStream as TokenStream2;
3use quote::{ToTokens, format_ident, quote};
4use syn::{
5    Expr, FnArg, GenericArgument, Ident, ItemFn, LitBool, LitStr, Meta, Pat, PathArguments,
6    ReturnType, Token, Type,
7    parse::{Parse, ParseStream},
8};
9
10/// `#[api_get("/path", tag = "...", ...)]`
11#[proc_macro_attribute]
12pub fn api_get(attr: TokenStream, item: TokenStream) -> TokenStream {
13    expand("get", attr, item)
14}
15
16/// `#[api_post("/path", tag = "...", ...)]`
17#[proc_macro_attribute]
18pub fn api_post(attr: TokenStream, item: TokenStream) -> TokenStream {
19    expand("post", attr, item)
20}
21
22/// `#[api_put("/path", tag = "...", ...)]`
23#[proc_macro_attribute]
24pub fn api_put(attr: TokenStream, item: TokenStream) -> TokenStream {
25    expand("put", attr, item)
26}
27
28/// `#[api_delete("/path", tag = "...", ...)]`
29#[proc_macro_attribute]
30pub fn api_delete(attr: TokenStream, item: TokenStream) -> TokenStream {
31    expand("delete", attr, item)
32}
33
34/// `#[api_patch("/path", tag = "...", ...)]`
35#[proc_macro_attribute]
36pub fn api_patch(attr: TokenStream, item: TokenStream) -> TokenStream {
37    expand("patch", attr, item)
38}
39
40fn expand(method: &str, attr: TokenStream, item: TokenStream) -> TokenStream {
41    let args = syn::parse_macro_input!(attr as ApiArgs);
42    let mut func = syn::parse_macro_input!(item as ItemFn);
43
44    let dioxus_attr = dioxus_route_attr(method, &args.path, &args.forward);
45
46    if args.openapi == Some(false) {
47        return quote! {
48            #dioxus_attr
49            #func
50        }
51        .into();
52    }
53
54    let tag = match &args.tag {
55        Some(t) => t.clone(),
56        None => {
57            return syn::Error::new_spanned(
58                &func.sig.ident,
59                "api_* macros require `tag = \"...\"` (or `openapi = false`)",
60            )
61            .to_compile_error()
62            .into();
63        }
64    };
65
66    let path_lit = &args.path;
67    let path_value = path_lit.value();
68    let fn_ident = func.sig.ident.clone();
69    let openapi_fn = format_ident!("__openapi_{}", fn_ident);
70    let body_struct = format_ident!("__openapi_body_{}", fn_ident);
71    let operation_id = fn_ident.to_string();
72
73    let path_params = parse_path_params(&path_value);
74    let arg_map = fn_arg_map(&func);
75
76    // Path param entries for utoipa.
77    let mut param_tokens = Vec::new();
78    for name in &path_params {
79        let Some((_, (ty, _))) = arg_map.iter().find(|(n, _)| n == name) else {
80            return syn::Error::new_spanned(
81                &func.sig.ident,
82                format!("path parameter `{{{name}}}` has no matching function argument"),
83            )
84            .to_compile_error()
85            .into();
86        };
87        let name_lit = LitStr::new(name, proc_macro2::Span::call_site());
88        param_tokens.push(quote! {
89            (#name_lit = #ty, Path, description = #name_lit)
90        });
91    }
92
93    let body_fields: Vec<_> = arg_map
94        .iter()
95        .filter(|(name, _)| !path_params.iter().any(|p| p == name))
96        .map(|(name, (ty, _))| {
97            let ident = format_ident!("{}", name);
98            (ident, ty.clone())
99        })
100        .collect();
101
102    // Dioxus packs non-path args as a named JSON object for methods that take a body.
103    let has_body = matches!(method, "post" | "put" | "patch")
104        && !body_fields.is_empty()
105        && args.request_body.is_none();
106    let request_body_override = args.request_body.clone();
107
108    // Resolve response body type + optional media type.
109    // `ServerEvents<T>` (Dioxus SSE) unwraps to body `T` with
110    // `text/event-stream` unless the caller overrides `response` / `content_type`.
111    let extracted_ok = match extract_result_ok(&func.sig.output) {
112        Ok(ty) => ty,
113        Err(e) => return e.to_compile_error().into(),
114    };
115    let (response_ty, content_type) = resolve_response(
116        args.response.clone(),
117        args.content_type.clone(),
118        extracted_ok,
119    );
120
121    let method_ident = format_ident!("{}", method);
122
123    // Doc comments on the real fn; copy onto the openapi stub so utoipa
124    // picks up summary/description.
125    let docs: Vec<_> = func
126        .attrs
127        .iter()
128        .filter(|a| a.path().is_ident("doc"))
129        .cloned()
130        .collect();
131
132    // Strip nothing else; leave user attrs on the real function.
133    let _ = &mut func;
134
135    let body_struct_tokens = if has_body {
136        let fields = body_fields.iter().map(|(ident, ty)| {
137            quote! { pub #ident: #ty }
138        });
139        quote! {
140            #[cfg(feature = "server")]
141            #[derive(utoipa::ToSchema)]
142            #[allow(non_camel_case_types)]
143            #[doc(hidden)]
144            pub struct #body_struct {
145                #(#fields,)*
146            }
147        }
148    } else {
149        quote! {}
150    };
151
152    let request_body_tokens = if let Some(ty) = request_body_override {
153        quote! { request_body = #ty, }
154    } else if has_body {
155        quote! { request_body = #body_struct, }
156    } else {
157        quote! {}
158    };
159
160    let params_tokens = if param_tokens.is_empty() {
161        quote! {}
162    } else {
163        quote! { params( #(#param_tokens),* ), }
164    };
165
166    let content_type_tokens = match &content_type {
167        Some(ct) => quote! { content_type = #ct, },
168        None => quote! {},
169    };
170
171    let responses_tokens = match response_ty {
172        None => quote! {
173            responses(
174                (status = 200, description = "OK"),
175                (status = 500, description = "Server error")
176            )
177        },
178        Some(Type::Tuple(t)) if t.elems.is_empty() => quote! {
179            responses(
180                (status = 200, description = "OK"),
181                (status = 500, description = "Server error")
182            )
183        },
184        Some(ty) => quote! {
185            responses(
186                (status = 200, description = "OK", #content_type_tokens body = #ty),
187                (status = 500, description = "Server error")
188            )
189        },
190    };
191
192    // utoipa names the Path impl struct `__path_{fn_name}`.
193    let path_type = format_ident!("__path_{}", openapi_fn);
194
195    quote! {
196        #dioxus_attr
197        #func
198
199        #body_struct_tokens
200
201        #[cfg(feature = "server")]
202        #(#docs)*
203        #[utoipa::path(
204            #method_ident,
205            path = #path_lit,
206            operation_id = #operation_id,
207            tag = #tag,
208            #params_tokens
209            #request_body_tokens
210            #responses_tokens
211        )]
212        #[doc(hidden)]
213        pub fn #openapi_fn() {}
214
215        // Auto-register with the dioxus-openapi inventory so apps do not need
216        // a hand-maintained paths(...) / schemas(...) list. Uses
217        // append_tagged_path so utoipa Tags land on the operation.
218        #[cfg(feature = "server")]
219        ::dioxus_openapi::inventory::submit! {
220            ::dioxus_openapi::RegisteredPath {
221                append: |paths| ::dioxus_openapi::append_tagged_path::<#path_type>(paths),
222                schemas: |schemas| {
223                    <#path_type as ::utoipa::__dev::SchemaReferences>::schemas(schemas);
224                },
225            }
226        }
227    }
228    .into()
229}
230
231fn dioxus_route_attr(method: &str, path: &LitStr, forward: &[TokenStream2]) -> TokenStream2 {
232    let forward = forward.iter();
233    match method {
234        "get" => quote! { #[::dioxus::prelude::get(#path #(, #forward)*)] },
235        "post" => quote! { #[::dioxus::prelude::post(#path #(, #forward)*)] },
236        "put" => quote! { #[::dioxus::prelude::put(#path #(, #forward)*)] },
237        "delete" => quote! { #[::dioxus::prelude::delete(#path #(, #forward)*)] },
238        "patch" => quote! { #[::dioxus::prelude::patch(#path #(, #forward)*)] },
239        other => {
240            let msg = format!("unsupported method {other}");
241            quote! { compile_error!(#msg) }
242        }
243    }
244}
245
246/// OpenAPI-only keys consumed by this crate (not forwarded to Dioxus).
247fn is_openapi_key(ident: &Ident) -> bool {
248    matches!(
249        ident.to_string().as_str(),
250        "tag" | "request_body" | "response" | "content_type" | "openapi"
251    )
252}
253
254struct ApiArgs {
255    path: LitStr,
256    tag: Option<LitStr>,
257    request_body: Option<Type>,
258    response: Option<Type>,
259    /// Override response media type (e.g. `"text/event-stream"` for SSE).
260    content_type: Option<LitStr>,
261    openapi: Option<bool>,
262    /// Raw tokens forwarded to the underlying Dioxus `#[get]`/`#[post]`/… macro.
263    forward: Vec<TokenStream2>,
264}
265
266impl Parse for ApiArgs {
267    fn parse(input: ParseStream) -> syn::Result<Self> {
268        let path: LitStr = input.parse()?;
269        let mut tag = None;
270        let mut request_body = None;
271        let mut response = None;
272        let mut content_type = None;
273        let mut openapi = None;
274        let mut forward = Vec::new();
275
276        while !input.is_empty() {
277            input.parse::<Token![,]>()?;
278            if input.is_empty() {
279                break;
280            }
281
282            // `key = value` OpenAPI keys consumed; unknown keys forwarded to Dioxus.
283            // Before FnArg so `tag = "..."` is never treated as an extractor.
284            if input.peek(Ident) && input.peek2(Token![=]) {
285                let ident: Ident = input.fork().parse()?;
286                if is_openapi_key(&ident) {
287                    let meta: Meta = input.parse()?;
288                    let Meta::NameValue(nv) = meta else {
289                        return Err(syn::Error::new_spanned(
290                            ident,
291                            "expected `key = value` for OpenAPI options",
292                        ));
293                    };
294                    let key = nv
295                        .path
296                        .get_ident()
297                        .ok_or_else(|| syn::Error::new_spanned(&nv.path, "expected ident key"))?;
298                    match key.to_string().as_str() {
299                        "tag" => tag = Some(expr_to_lit_str(&nv.value)?),
300                        "request_body" => request_body = Some(expr_to_type(&nv.value)?),
301                        "response" => response = Some(expr_to_type(&nv.value)?),
302                        "content_type" => content_type = Some(expr_to_lit_str(&nv.value)?),
303                        "openapi" => openapi = Some(expr_to_bool(&nv.value)?),
304                        _ => unreachable!("filtered by is_openapi_key"),
305                    }
306                    continue;
307                }
308
309                forward.push(parse_forward_item(input)?);
310                continue;
311            }
312
313            // Dioxus server extractors are full `FnArg`s (same as axum handlers):
314            //   `session: Session`
315            //   `axum::Extension(me): axum::Extension<Principal>`
316            if input.fork().parse::<FnArg>().is_ok() {
317                let arg: FnArg = input.parse()?;
318                forward.push(arg.into_token_stream());
319                continue;
320            }
321
322            // Anything else (future Dioxus syntax): forward as a comma-item.
323            forward.push(parse_forward_item(input)?);
324        }
325
326        Ok(Self {
327            path,
328            tag,
329            request_body,
330            response,
331            content_type,
332            openapi,
333            forward,
334        })
335    }
336}
337
338/// Capture one comma-separated attribute item as raw tokens.
339///
340/// Nested commas inside `()`, `[]`, or `{}` stay inside a single `Group`
341/// token tree, so a top-level `peek(Token![,])` correctly ends the item.
342fn parse_forward_item(input: ParseStream) -> syn::Result<TokenStream2> {
343    let mut out = TokenStream2::new();
344    while !input.is_empty() {
345        if input.peek(Token![,]) {
346            break;
347        }
348        let tt: proc_macro2::TokenTree = input.parse()?;
349        out.extend(std::iter::once(tt));
350    }
351    if out.is_empty() {
352        return Err(input.error("expected attribute argument to forward to Dioxus"));
353    }
354    Ok(out)
355}
356
357fn expr_to_lit_str(expr: &Expr) -> syn::Result<LitStr> {
358    match expr {
359        Expr::Lit(syn::ExprLit {
360            lit: syn::Lit::Str(s),
361            ..
362        }) => Ok(s.clone()),
363        _ => Err(syn::Error::new_spanned(expr, "expected string literal")),
364    }
365}
366
367fn expr_to_bool(expr: &Expr) -> syn::Result<bool> {
368    match expr {
369        Expr::Lit(syn::ExprLit {
370            lit: syn::Lit::Bool(LitBool { value, .. }),
371            ..
372        }) => Ok(*value),
373        _ => Err(syn::Error::new_spanned(expr, "expected bool literal")),
374    }
375}
376
377fn expr_to_type(expr: &Expr) -> syn::Result<Type> {
378    // `response = Vec<Mac>` comes through as an expression path / etc.
379    // Re-parse the token stream as a Type.
380    syn::parse2(quote! { #expr })
381}
382
383/// `{serial}` / `{role}` captures in an axum-style path.
384fn parse_path_params(path: &str) -> Vec<String> {
385    let mut out = Vec::new();
386    let mut rest = path;
387    while let Some(start) = rest.find('{') {
388        rest = &rest[start + 1..];
389        let Some(end) = rest.find('}') else { break };
390        let name = &rest[..end];
391        // Skip wildcards like `{*path}` if ever used.
392        let name = name.strip_prefix('*').unwrap_or(name);
393        if !name.is_empty() {
394            out.push(name.to_string());
395        }
396        rest = &rest[end + 1..];
397    }
398    out
399}
400
401/// Map arg name -> (type, original index). Skips receivers.
402fn fn_arg_map(func: &ItemFn) -> Vec<(String, (Type, usize))> {
403    // Use Vec to preserve order (important for body field order matching Dioxus).
404    let mut out = Vec::new();
405    for (i, arg) in func.sig.inputs.iter().enumerate() {
406        let FnArg::Typed(pat_ty) = arg else {
407            continue;
408        };
409        let Pat::Ident(pat_ident) = pat_ty.pat.as_ref() else {
410            continue;
411        };
412        out.push((pat_ident.ident.to_string(), ((*pat_ty.ty).clone(), i)));
413    }
414    out
415}
416
417/// `Result<T>` / `Result<T, E>` -> `Some(T)`; bare non-Result is error for now.
418fn extract_result_ok(ret: &ReturnType) -> syn::Result<Option<Type>> {
419    let ReturnType::Type(_, ty) = ret else {
420        return Ok(None);
421    };
422    let Type::Path(type_path) = ty.as_ref() else {
423        return Ok(Some(ty.as_ref().clone()));
424    };
425    let last = type_path
426        .path
427        .segments
428        .last()
429        .ok_or_else(|| syn::Error::new_spanned(ty, "empty return type path"))?;
430    if last.ident != "Result" {
431        return Ok(Some(ty.as_ref().clone()));
432    }
433    let PathArguments::AngleBracketed(args) = &last.arguments else {
434        return Ok(None);
435    };
436    let mut generics = args.args.iter().filter_map(|a| match a {
437        GenericArgument::Type(t) => Some(t.clone()),
438        _ => None,
439    });
440    Ok(generics.next())
441}
442
443/// Last path segment ident (`ServerEvents`, `Vec`, …).
444fn type_last_ident(ty: &Type) -> Option<&Ident> {
445    let Type::Path(type_path) = ty else {
446        return None;
447    };
448    type_path.path.segments.last().map(|s| &s.ident)
449}
450
451/// First type generic argument (`Foo<T, U>` -> `T`).
452fn first_type_arg(ty: &Type) -> Option<Type> {
453    let Type::Path(type_path) = ty else {
454        return None;
455    };
456    let last = type_path.path.segments.last()?;
457    let PathArguments::AngleBracketed(args) = &last.arguments else {
458        return None;
459    };
460    args.args.iter().find_map(|a| match a {
461        GenericArgument::Type(t) => Some(t.clone()),
462        _ => None,
463    })
464}
465
466/// Pick OpenAPI response body + media type from overrides and the fn return type.
467///
468/// Dioxus `ServerEvents<T>` is documented as SSE: body `T`,
469/// `content_type = "text/event-stream"`.
470fn resolve_response(
471    response_override: Option<Type>,
472    content_type_override: Option<LitStr>,
473    extracted_ok: Option<Type>,
474) -> (Option<Type>, Option<LitStr>) {
475    if let Some(ty) = response_override {
476        return (Some(ty), content_type_override);
477    }
478
479    let Some(ok) = extracted_ok else {
480        return (None, content_type_override);
481    };
482
483    if type_last_ident(&ok).is_some_and(|id| id == "ServerEvents") {
484        let inner = first_type_arg(&ok).unwrap_or(ok);
485        let ct = content_type_override
486            .unwrap_or_else(|| LitStr::new("text/event-stream", proc_macro2::Span::call_site()));
487        return (Some(inner), Some(ct));
488    }
489
490    (Some(ok), content_type_override)
491}