by-macros 0.6.16

Biyard Macros
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
436
437
438
439
//! Proc-macro implementations for `#[get]`, `#[post]`, `#[put]`, `#[patch]`,
//! `#[delete]` attributes that wrap dioxus-fullstack's macros and add a
//! reqwest-based client stub for the `tauri-web` feature.
//!
//! Under `cfg(not(tauri-web))`, the original `#[::dioxus::fullstack::<method>]`
//! attribute is re-attached so dioxus generates server + browser-client code
//! exactly as before. Under `cfg(tauri-web)`, the original function body is
//! dropped on the client side and replaced by a small stub that calls
//! `crate::common::fullstack::server_fn::<method>` with a URL built from the
//! macro's path literal and the handler's own arguments.
//!
//! Attribute syntax matches dioxus's:
//!
//!     #[post("/api/posts/{post_id}/comments?after", user: User)]
//!     pub async fn add_comment(
//!         post_id: FeedPartition,
//!         after: Option<String>,
//!         req: AddCommentRequest,
//!     ) -> Result<Comment> { ... }
//!
//! - `{post_id}` in the path = path segment substitution; matched by name
//!   against the function's args.
//! - `?after` in the path = query string; matched by name against args.
//!   Multiple query keys separate with `&` (e.g. `?a&b`).
//! - `user: User`, `_x: Foo`, `role: SpaceUserRole`, etc. = server-side
//!   extractor params. Stripped from the client stub (server fills them
//!   from request context).
//! - Remaining args (not path, not query, not extractor) for POST/PUT/PATCH
//!   become the JSON body. Exactly one such arg is expected.

use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::{format_ident, quote};
use std::collections::HashSet;
use syn::parse::{Parse, ParseStream};
use syn::{parse_macro_input, FnArg, Ident, ItemFn, LitStr, Pat, PatType, Token, Type};

/// `#[get("/path", extractor: T, ...)]` — parsed attribute args.
struct RouteAttr {
    path: LitStr,
    /// Names of server-only extractor params (e.g. `user`, `role`, `_space`).
    /// Stripped from client stubs.
    extractors: HashSet<String>,
    /// Raw tokens of `, name: Type, name: Type, ...` after the path literal.
    /// Preserved so we can re-emit the attribute for the dioxus-fullstack
    /// passthrough with a normalized path literal (`:name` → `{name}`).
    extractor_tokens: TokenStream2,
}

impl Parse for RouteAttr {
    fn parse(input: ParseStream) -> syn::Result<Self> {
        let path: LitStr = input.parse()?;
        let mut extractors = HashSet::new();
        let mut extractor_tokens = TokenStream2::new();
        while !input.is_empty() {
            let comma: Token![,] = input.parse()?;
            let name: Ident = input.parse()?;
            let colon: Token![:] = input.parse()?;
            let ty: Type = input.parse()?;
            extractors.insert(name.to_string());
            extractor_tokens.extend(quote! { #comma #name #colon #ty });
        }
        Ok(RouteAttr {
            path,
            extractors,
            extractor_tokens,
        })
    }
}

/// Detect `Option<T>` syntactically by looking at the last segment of the
/// type path. Catches `Option<_>`, `std::option::Option<_>`,
/// `::std::option::Option<_>`. Conservative: anything else returns false.
fn is_option_type(ty: &Type) -> bool {
    if let Type::Path(tp) = ty {
        if let Some(seg) = tp.path.segments.last() {
            return seg.ident == "Option";
        }
    }
    false
}

/// If `ty` is `Form<T>` (any path), return the inner `T`. Otherwise None.
/// Matches `Form<...>`, `dioxus::dioxus_fullstack::Form<...>`,
/// `dioxus_fullstack::Form<...>`, etc.
fn unwrap_form_type(ty: &Type) -> Option<Type> {
    if let Type::Path(tp) = ty {
        if let Some(seg) = tp.path.segments.last() {
            if seg.ident == "Form" {
                if let syn::PathArguments::AngleBracketed(args) = &seg.arguments {
                    if let Some(syn::GenericArgument::Type(inner)) = args.args.first() {
                        return Some(inner.clone());
                    }
                }
            }
        }
    }
    None
}

/// Parse `/api/posts/{id}/comments?after&before` into:
///  - format-string template `"/api/posts/{}/comments"` (path piece only)
///  - path placeholder names in order: `["id"]`
///  - query placeholder names: `["after", "before"]`
///
/// Both `{name}` (axum 0.8+ / dioxus-fullstack) and `:name` (axum 0.7 style)
/// placeholders are accepted. A `:name` segment begins immediately after a
/// `/` and runs until the next `/` or end of path.
fn parse_path(path: &str) -> (String, Vec<String>, Vec<String>) {
    let (path_part, query_part) = match path.find('?') {
        Some(i) => (&path[..i], Some(&path[i + 1..])),
        None => (path, None),
    };

    let mut path_args = Vec::new();
    let mut template = String::new();
    let mut chars = path_part.chars().peekable();
    let mut prev = '\0';
    while let Some(c) = chars.next() {
        if c == '{' {
            let mut name = String::new();
            while let Some(&nc) = chars.peek() {
                if nc == '}' {
                    chars.next();
                    break;
                }
                name.push(nc);
                chars.next();
            }
            path_args.push(name);
            template.push_str("{}");
            prev = '}';
        } else if c == ':' && (prev == '\0' || prev == '/') {
            // `:name` placeholder — read until next '/' or end.
            let mut name = String::new();
            while let Some(&nc) = chars.peek() {
                if nc == '/' {
                    break;
                }
                name.push(nc);
                chars.next();
            }
            prev = name.chars().last().unwrap_or(':');
            path_args.push(name);
            template.push_str("{}");
        } else if c == '}' {
            // unbalanced — keep literal
            template.push(c);
            prev = c;
        } else {
            template.push(c);
            prev = c;
        }
    }

    let query_args = query_part
        .map(|q| {
            q.split('&')
                .filter(|s| !s.is_empty())
                .map(|s| s.to_string())
                .collect()
        })
        .unwrap_or_default();

    (template, path_args, query_args)
}

/// Rewrite any `:name` path placeholders into `{name}` so the path can be
/// forwarded verbatim to `#[::dioxus::fullstack::<method>(...)]`, which
/// expects axum 0.8+ `{name}` syntax. Query strings are passed through
/// unchanged.
fn normalize_path_for_dioxus(path: &str) -> String {
    let (path_part, query_part) = match path.find('?') {
        Some(i) => (&path[..i], Some(&path[i..])), // keep '?' in query_part
        None => (path, None),
    };

    let mut out = String::with_capacity(path.len());
    let mut chars = path_part.chars().peekable();
    let mut prev = '\0';
    while let Some(c) = chars.next() {
        if c == ':' && (prev == '\0' || prev == '/') {
            out.push('{');
            let mut last = ':';
            while let Some(&nc) = chars.peek() {
                if nc == '/' {
                    break;
                }
                out.push(nc);
                last = nc;
                chars.next();
            }
            out.push('}');
            prev = last;
        } else {
            out.push(c);
            prev = c;
        }
    }

    if let Some(q) = query_part {
        out.push_str(q);
    }
    out
}

pub fn server_fn_impl(method: &str, attr: TokenStream, item: TokenStream) -> TokenStream {
    // Keep a raw passthrough copy of the item — we re-emit it under the
    // `cfg(not(tauri-web))` branch with the dioxus-fullstack attribute so
    // dioxus generates the normal SSR + browser-RPC code path for web
    // builds. The attribute itself is rebuilt below from the parsed
    // `RouteAttr` so that `:name` placeholders in the path literal are
    // normalized to `{name}` (dioxus-fullstack expects axum 0.8+ syntax).
    let item_passthrough: TokenStream2 = item.clone().into();

    let route = parse_macro_input!(attr as RouteAttr);
    let func = parse_macro_input!(item as ItemFn);

    let fn_vis = &func.vis;
    let fn_sig = &func.sig;
    let fn_name = &fn_sig.ident;
    let fn_generics = &fn_sig.generics;
    let fn_output = &fn_sig.output;
    let fn_attrs = &func.attrs;

    let (path_template, path_args, query_args) = parse_path(&route.path.value());
    let path_arg_set: HashSet<&String> = path_args.iter().collect();
    let query_arg_set: HashSet<&String> = query_args.iter().collect();

    // Collect typed args from the original signature.
    let typed_args: Vec<(&Ident, &Type)> = fn_sig
        .inputs
        .iter()
        .filter_map(|input| match input {
            FnArg::Typed(PatType { pat, ty, .. }) => {
                if let Pat::Ident(pi) = pat.as_ref() {
                    Some((&pi.ident, ty.as_ref()))
                } else {
                    None
                }
            }
            _ => None,
        })
        .collect();

    // Args that survive on the client stub = everything except server
    // extractors.
    let client_args: Vec<(&Ident, &Type)> = typed_args
        .iter()
        .filter(|(name, _)| !route.extractors.contains(&name.to_string()))
        .copied()
        .collect();

    // Path-substituted args, by position in the template.
    let path_idents: Vec<&Ident> = path_args
        .iter()
        .filter_map(|name| {
            client_args
                .iter()
                .find(|(n, _)| n.to_string() == *name)
                .map(|(n, _)| *n)
        })
        .collect();

    // Query string args.
    let query_idents: Vec<&Ident> = query_args
        .iter()
        .filter_map(|name| {
            client_args
                .iter()
                .find(|(n, _)| n.to_string() == *name)
                .map(|(n, _)| *n)
        })
        .collect();
    let query_names: Vec<String> = query_idents.iter().map(|i| i.to_string()).collect();

    // Body args = client args that aren't path or query.
    let body_idents: Vec<&Ident> = client_args
        .iter()
        .filter(|(n, _)| {
            let s = n.to_string();
            !path_arg_set.contains(&s) && !query_arg_set.contains(&s)
        })
        .map(|(n, _)| *n)
        .collect();

    // Function-arg declarations for the stub signature (same as original
    // minus extractors). If a body arg is `Form<T>`, the stub takes `T`
    // directly — we don't want to leak dioxus's Form wrapper into the
    // tauri-web client path (it isn't Serialize).
    let stub_inputs: Vec<TokenStream2> = client_args
        .iter()
        .map(|(name, ty)| {
            if let Some(inner) = unwrap_form_type(ty) {
                quote! { #name: #inner }
            } else {
                quote! { #name: #ty }
            }
        })
        .collect();

    // --- Body for the tauri-web stub ----------------------------------------

    let path_format = if path_idents.is_empty() {
        quote! { let __path: ::std::string::String = #path_template.to_string(); }
    } else {
        // Go through `to_url_value` (serde-based) so any `Serialize` value
        // works, including enums with `#[serde(rename_all = ...)]`, without
        // requiring `Display`. Then percent-encode each segment.
        let tpl = LitStr::new(&path_template, route.path.span());
        quote! {
            let __path: ::std::string::String = format!(
                #tpl,
                #( ::urlencoding::encode(
                    &crate::common::fullstack::server_fn::to_url_value(&#path_idents)
                ) ),*
            );
        }
    };

    let query_attach = if query_idents.is_empty() {
        quote! { let __url: ::std::string::String = __path; }
    } else {
        // Build `?k=v&k2=v2`, skipping None values. We detect `Option<T>`
        // by inspecting the type syntactically so we can emit an
        // `if let Some(v) = ...` branch for those and an unconditional
        // push for non-Option args. Rendering uses Display via to_string().
        let pushers = query_idents.iter().zip(query_names.iter()).map(|(ident, name)| {
            // Look up the type for this ident.
            let ty = client_args
                .iter()
                .find(|(n, _)| n.to_string() == ident.to_string())
                .map(|(_, t)| *t);
            let is_option = ty.map(is_option_type).unwrap_or(false);
            if is_option {
                quote! {
                    if let ::std::option::Option::Some(v) = &#ident {
                        if __has_q { __url.push('&'); } else { __url.push('?'); __has_q = true; }
                        __url.push_str(#name);
                        __url.push('=');
                        __url.push_str(&::urlencoding::encode(
                            &crate::common::fullstack::server_fn::to_url_value(v)
                        ));
                    }
                }
            } else {
                quote! {
                    {
                        if __has_q { __url.push('&'); } else { __url.push('?'); __has_q = true; }
                        __url.push_str(#name);
                        __url.push('=');
                        __url.push_str(&::urlencoding::encode(
                            &crate::common::fullstack::server_fn::to_url_value(&#ident)
                        ));
                    }
                }
            }
        });
        quote! {
            let mut __url = __path;
            let mut __has_q = false;
            #( #pushers )*
        }
    };

    let send_call = match method {
        "GET" | "DELETE" => {
            let fn_name = format_ident!("{}", method.to_lowercase());
            quote! {
                crate::common::fullstack::server_fn::#fn_name(&__url)
                .await
                .map_err(::std::convert::Into::into)
            }
        }
        "POST" | "PUT" | "PATCH" => {
            let fn_name = format_ident!("{}", method.to_lowercase());
            // dioxus-fullstack's server-side request decoder expects the
            // body JSON to be an object keyed by the handler's argument
            // names, e.g. for `fn handler(req: T)` it parses
            // `{"req": <T>}`. The auto-generated args struct fails to
            // deserialize a bare `T`. Wrap accordingly.
            //
            // If none, send `&()` — an empty JSON object isn't required
            // (dioxus accepts an empty body for zero-arg POSTs).
            if let Some(body) = body_idents.first() {
                let body_name = LitStr::new(&body.to_string(), body.span());
                quote! {
                    crate::common::fullstack::server_fn::#fn_name(
                        &__url,
                        &::serde_json::json!({ #body_name: &#body }),
                    )
                    .await
                    .map_err(::std::convert::Into::into)
                }
            } else {
                quote! {
                    crate::common::fullstack::server_fn::#fn_name(&__url, &())
                .await
                .map_err(::std::convert::Into::into)
                }
            }
        }
        _ => unreachable!("unsupported method {method}"),
    };

    let tauri = quote! {
        #(#fn_attrs)*
        #[allow(unused_variables, unused_mut)]
        #fn_vis async fn #fn_name #fn_generics ( #( #stub_inputs ),* ) #fn_output {
            #path_format
            #query_attach
            #send_call
        }
    };

    // Re-attach dioxus-fullstack's own attribute macro on the not-tauri-web
    // branch. dioxus-fullstack's `#[get]/#[post]/...` accept the same
    // attribute syntax (`"/path", extractor: Type, ...`) we parsed, BUT only
    // recognize `{name}` path placeholders. Rebuild the attribute from the
    // normalized path + the preserved extractor tokens so callers can write
    // either `{name}` or `:name` and the dioxus side always sees `{name}`.
    let method_ident = format_ident!("{}", method.to_lowercase());
    let normalized_path = normalize_path_for_dioxus(&route.path.value());
    let normalized_path_lit = LitStr::new(&normalized_path, route.path.span());
    let extractor_tokens = &route.extractor_tokens;
    let dioxus_passthrough = quote! {
        #[::dioxus::fullstack::#method_ident( #normalized_path_lit #extractor_tokens )]
        #item_passthrough
    };

    quote! {
        #[cfg(feature = "tauri-web")]
        #tauri

        #[cfg(not(feature = "tauri-web"))]
        #dioxus_passthrough
    }
    .into()
}