dioxus-openapi-macros 0.1.1

Proc macros for dioxus-openapi: dual Dioxus server-fn + utoipa path expansion
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::{ToTokens, format_ident, quote};
use syn::{
    Expr, FnArg, GenericArgument, Ident, ItemFn, LitBool, LitStr, Meta, Pat, PathArguments,
    ReturnType, Token, Type,
    parse::{Parse, ParseStream},
};

/// `#[api_get("/path", tag = "...", ...)]`
#[proc_macro_attribute]
pub fn api_get(attr: TokenStream, item: TokenStream) -> TokenStream {
    expand("get", attr, item)
}

/// `#[api_post("/path", tag = "...", ...)]`
#[proc_macro_attribute]
pub fn api_post(attr: TokenStream, item: TokenStream) -> TokenStream {
    expand("post", attr, item)
}

/// `#[api_put("/path", tag = "...", ...)]`
#[proc_macro_attribute]
pub fn api_put(attr: TokenStream, item: TokenStream) -> TokenStream {
    expand("put", attr, item)
}

/// `#[api_delete("/path", tag = "...", ...)]`
#[proc_macro_attribute]
pub fn api_delete(attr: TokenStream, item: TokenStream) -> TokenStream {
    expand("delete", attr, item)
}

/// `#[api_patch("/path", tag = "...", ...)]`
#[proc_macro_attribute]
pub fn api_patch(attr: TokenStream, item: TokenStream) -> TokenStream {
    expand("patch", attr, item)
}

fn expand(method: &str, attr: TokenStream, item: TokenStream) -> TokenStream {
    let args = syn::parse_macro_input!(attr as ApiArgs);
    let mut func = syn::parse_macro_input!(item as ItemFn);

    let dioxus_attr = dioxus_route_attr(method, &args.path, &args.forward);

    if args.openapi == Some(false) {
        return quote! {
            #dioxus_attr
            #func
        }
        .into();
    }

    let tag = match &args.tag {
        Some(t) => t.clone(),
        None => {
            return syn::Error::new_spanned(
                &func.sig.ident,
                "api_* macros require `tag = \"...\"` (or `openapi = false`)",
            )
            .to_compile_error()
            .into();
        }
    };

    let path_lit = &args.path;
    let path_value = path_lit.value();
    let fn_ident = func.sig.ident.clone();
    let openapi_fn = format_ident!("__openapi_{}", fn_ident);
    let body_struct = format_ident!("__openapi_body_{}", fn_ident);
    let operation_id = fn_ident.to_string();

    let path_params = parse_path_params(&path_value);
    let arg_map = fn_arg_map(&func);

    // Path param entries for utoipa.
    let mut param_tokens = Vec::new();
    for name in &path_params {
        let Some((_, (ty, _))) = arg_map.iter().find(|(n, _)| n == name) else {
            return syn::Error::new_spanned(
                &func.sig.ident,
                format!("path parameter `{{{name}}}` has no matching function argument"),
            )
            .to_compile_error()
            .into();
        };
        let name_lit = LitStr::new(name, proc_macro2::Span::call_site());
        param_tokens.push(quote! {
            (#name_lit = #ty, Path, description = #name_lit)
        });
    }

    let body_fields: Vec<_> = arg_map
        .iter()
        .filter(|(name, _)| !path_params.iter().any(|p| p == name))
        .map(|(name, (ty, _))| {
            let ident = format_ident!("{}", name);
            (ident, ty.clone())
        })
        .collect();

    // Dioxus packs non-path args as a named JSON object for methods that take a body.
    let has_body = matches!(method, "post" | "put" | "patch")
        && !body_fields.is_empty()
        && args.request_body.is_none();
    let request_body_override = args.request_body.clone();

    let response_ty = match &args.response {
        Some(ty) => Some(ty.clone()),
        None => match extract_result_ok(&func.sig.output) {
            Ok(ty) => ty,
            Err(e) => return e.to_compile_error().into(),
        },
    };

    let method_ident = format_ident!("{}", method);

    // Doc comments on the real fn; copy onto the openapi stub so utoipa
    // picks up summary/description.
    let docs: Vec<_> = func
        .attrs
        .iter()
        .filter(|a| a.path().is_ident("doc"))
        .cloned()
        .collect();

    // Strip nothing else; leave user attrs on the real function.
    let _ = &mut func;

    let body_struct_tokens = if has_body {
        let fields = body_fields.iter().map(|(ident, ty)| {
            quote! { pub #ident: #ty }
        });
        quote! {
            #[cfg(feature = "server")]
            #[derive(utoipa::ToSchema)]
            #[allow(non_camel_case_types)]
            #[doc(hidden)]
            pub struct #body_struct {
                #(#fields,)*
            }
        }
    } else {
        quote! {}
    };

    let request_body_tokens = if let Some(ty) = request_body_override {
        quote! { request_body = #ty, }
    } else if has_body {
        quote! { request_body = #body_struct, }
    } else {
        quote! {}
    };

    let params_tokens = if param_tokens.is_empty() {
        quote! {}
    } else {
        quote! { params( #(#param_tokens),* ), }
    };

    let responses_tokens = match response_ty {
        None => quote! {
            responses(
                (status = 200, description = "OK"),
                (status = 500, description = "Server error")
            )
        },
        Some(Type::Tuple(t)) if t.elems.is_empty() => quote! {
            responses(
                (status = 200, description = "OK"),
                (status = 500, description = "Server error")
            )
        },
        Some(ty) => quote! {
            responses(
                (status = 200, description = "OK", body = #ty),
                (status = 500, description = "Server error")
            )
        },
    };

    // utoipa names the Path impl struct `__path_{fn_name}`.
    let path_type = format_ident!("__path_{}", openapi_fn);

    quote! {
        #dioxus_attr
        #func

        #body_struct_tokens

        #[cfg(feature = "server")]
        #(#docs)*
        #[utoipa::path(
            #method_ident,
            path = #path_lit,
            operation_id = #operation_id,
            tag = #tag,
            #params_tokens
            #request_body_tokens
            #responses_tokens
        )]
        #[doc(hidden)]
        pub fn #openapi_fn() {}

        // Auto-register with the dioxus-openapi inventory so apps do not need
        // a hand-maintained paths(...) / schemas(...) list. Uses
        // append_tagged_path so utoipa Tags land on the operation.
        #[cfg(feature = "server")]
        ::dioxus_openapi::inventory::submit! {
            ::dioxus_openapi::RegisteredPath {
                append: |paths| ::dioxus_openapi::append_tagged_path::<#path_type>(paths),
                schemas: |schemas| {
                    <#path_type as ::utoipa::__dev::SchemaReferences>::schemas(schemas);
                },
            }
        }
    }
    .into()
}

fn dioxus_route_attr(method: &str, path: &LitStr, forward: &[TokenStream2]) -> TokenStream2 {
    let forward = forward.iter();
    match method {
        "get" => quote! { #[::dioxus::prelude::get(#path #(, #forward)*)] },
        "post" => quote! { #[::dioxus::prelude::post(#path #(, #forward)*)] },
        "put" => quote! { #[::dioxus::prelude::put(#path #(, #forward)*)] },
        "delete" => quote! { #[::dioxus::prelude::delete(#path #(, #forward)*)] },
        "patch" => quote! { #[::dioxus::prelude::patch(#path #(, #forward)*)] },
        other => {
            let msg = format!("unsupported method {other}");
            quote! { compile_error!(#msg) }
        }
    }
}

/// OpenAPI-only keys consumed by this crate (not forwarded to Dioxus).
fn is_openapi_key(ident: &Ident) -> bool {
    matches!(
        ident.to_string().as_str(),
        "tag" | "request_body" | "response" | "openapi"
    )
}

struct ApiArgs {
    path: LitStr,
    tag: Option<LitStr>,
    request_body: Option<Type>,
    response: Option<Type>,
    openapi: Option<bool>,
    /// Raw tokens forwarded to the underlying Dioxus `#[get]`/`#[post]`/… macro.
    forward: Vec<TokenStream2>,
}

impl Parse for ApiArgs {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let path: LitStr = input.parse()?;
        let mut tag = None;
        let mut request_body = None;
        let mut response = None;
        let mut openapi = None;
        let mut forward = Vec::new();

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

            // Server extractors and any `pat: Type` form Dioxus accepts.
            // Must be checked before Meta `auth: Session` is not valid Meta.
            if is_typed_arg_start(input) {
                let arg: FnArg = input.parse()?;
                forward.push(arg.into_token_stream());
                continue;
            }

            // `key = value` OpenAPI keys consumed; everything else forwarded.
            if input.peek(Ident) && input.peek2(Token![=]) {
                let ident: Ident = input.fork().parse()?;
                if is_openapi_key(&ident) {
                    let meta: Meta = input.parse()?;
                    let Meta::NameValue(nv) = meta else {
                        return Err(syn::Error::new_spanned(
                            ident,
                            "expected `key = value` for OpenAPI options",
                        ));
                    };
                    let key = nv
                        .path
                        .get_ident()
                        .ok_or_else(|| syn::Error::new_spanned(&nv.path, "expected ident key"))?;
                    match key.to_string().as_str() {
                        "tag" => tag = Some(expr_to_lit_str(&nv.value)?),
                        "request_body" => request_body = Some(expr_to_type(&nv.value)?),
                        "response" => response = Some(expr_to_type(&nv.value)?),
                        "openapi" => openapi = Some(expr_to_bool(&nv.value)?),
                        _ => unreachable!("filtered by is_openapi_key"),
                    }
                    continue;
                }

                // Forward opaque `key = value` (and multi-token values) to Dioxus.
                forward.push(parse_forward_item(input)?);
                continue;
            }

            // Anything else (future Dioxus syntax): forward as a comma-item.
            forward.push(parse_forward_item(input)?);
        }

        Ok(Self {
            path,
            tag,
            request_body,
            response,
            openapi,
            forward,
        })
    }
}

/// `ident: Type` or `mut ident: Type` - Dioxus server-extractor shape.
fn is_typed_arg_start(input: ParseStream) -> bool {
    let fork = input.fork();
    // optional `mut`
    if fork.peek(Token![mut]) {
        let _ = fork.parse::<Token![mut]>();
    }
    fork.peek(Ident) && fork.peek2(Token![:])
}

/// Capture one comma-separated attribute item as raw tokens.
///
/// Nested commas inside `()`, `[]`, or `{}` stay inside a single `Group`
/// token tree, so a top-level `peek(Token![,])` correctly ends the item.
fn parse_forward_item(input: ParseStream) -> syn::Result<TokenStream2> {
    let mut out = TokenStream2::new();
    while !input.is_empty() {
        if input.peek(Token![,]) {
            break;
        }
        let tt: proc_macro2::TokenTree = input.parse()?;
        out.extend(std::iter::once(tt));
    }
    if out.is_empty() {
        return Err(input.error("expected attribute argument to forward to Dioxus"));
    }
    Ok(out)
}

fn expr_to_lit_str(expr: &Expr) -> syn::Result<LitStr> {
    match expr {
        Expr::Lit(syn::ExprLit {
            lit: syn::Lit::Str(s),
            ..
        }) => Ok(s.clone()),
        _ => Err(syn::Error::new_spanned(expr, "expected string literal")),
    }
}

fn expr_to_bool(expr: &Expr) -> syn::Result<bool> {
    match expr {
        Expr::Lit(syn::ExprLit {
            lit: syn::Lit::Bool(LitBool { value, .. }),
            ..
        }) => Ok(*value),
        _ => Err(syn::Error::new_spanned(expr, "expected bool literal")),
    }
}

fn expr_to_type(expr: &Expr) -> syn::Result<Type> {
    // `response = Vec<Mac>` comes through as an expression path / etc.
    // Re-parse the token stream as a Type.
    syn::parse2(quote! { #expr })
}

/// `{serial}` / `{role}` captures in an axum-style path.
fn parse_path_params(path: &str) -> Vec<String> {
    let mut out = Vec::new();
    let mut rest = path;
    while let Some(start) = rest.find('{') {
        rest = &rest[start + 1..];
        let Some(end) = rest.find('}') else { break };
        let name = &rest[..end];
        // Skip wildcards like `{*path}` if ever used.
        let name = name.strip_prefix('*').unwrap_or(name);
        if !name.is_empty() {
            out.push(name.to_string());
        }
        rest = &rest[end + 1..];
    }
    out
}

/// Map arg name -> (type, original index). Skips receivers.
fn fn_arg_map(func: &ItemFn) -> Vec<(String, (Type, usize))> {
    // Use Vec to preserve order (important for body field order matching Dioxus).
    let mut out = Vec::new();
    for (i, arg) in func.sig.inputs.iter().enumerate() {
        let FnArg::Typed(pat_ty) = arg else {
            continue;
        };
        let Pat::Ident(pat_ident) = pat_ty.pat.as_ref() else {
            continue;
        };
        out.push((pat_ident.ident.to_string(), ((*pat_ty.ty).clone(), i)));
    }
    out
}

/// `Result<T>` / `Result<T, E>` -> `Some(T)`; bare non-Result is error for now.
fn extract_result_ok(ret: &ReturnType) -> syn::Result<Option<Type>> {
    let ReturnType::Type(_, ty) = ret else {
        return Ok(None);
    };
    let Type::Path(type_path) = ty.as_ref() else {
        return Ok(Some(ty.as_ref().clone()));
    };
    let last = type_path
        .path
        .segments
        .last()
        .ok_or_else(|| syn::Error::new_spanned(ty, "empty return type path"))?;
    if last.ident != "Result" {
        return Ok(Some(ty.as_ref().clone()));
    }
    let PathArguments::AngleBracketed(args) = &last.arguments else {
        return Ok(None);
    };
    let mut generics = args.args.iter().filter_map(|a| match a {
        GenericArgument::Type(t) => Some(t.clone()),
        _ => None,
    });
    Ok(generics.next())
}