victauri-macros 0.10.0

Proc macros for Victauri — auto-instrumentation of Tauri commands
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
440
#![forbid(unsafe_code)]
//! Procedural macros for Victauri — currently provides the `#[inspectable]` attribute
//! for auto-registering Tauri commands with the MCP introspection layer.

use heck::{ToLowerCamelCase, ToSnakeCase};
use proc_macro::TokenStream;
use quote::quote;
use syn::ext::IdentExt;
use syn::{ItemFn, parse_macro_input};

/// Marks a `#[tauri::command]` as inspectable by Victauri.
///
/// Generates a companion `<fn_name>__schema()` function that returns a
/// `victauri_core::CommandInfo` with the command's name, description,
/// argument types, return type, and NL-resolution metadata.
/// Call the schema function at setup time to register the command in the
/// Victauri `CommandRegistry`.
///
/// # Dependency requirement
///
/// The generated code names `victauri_core::...` by absolute path, so the crate
/// using this attribute must list `victauri-core` in its own `[dependencies]`
/// (this holds whether the macro is imported from `victauri_macros` or via the
/// `victauri_plugin::inspectable` re-export). Without it, compilation fails with
/// `E0433: failed to resolve: use of undeclared crate victauri_core`.
/// `victauri init` adds the dependency automatically.
///
/// # Argument keys
///
/// Tauri renames command arguments to camelCase by default: a `size_kb` argument is
/// invoked as `invoke("cmd", { sizeKb })`. Each registered argument records that IPC
/// key (`CommandArg::key`), so an agent reading the registry passes the key the
/// command actually accepts. `#[tauri::command]` consumes its own attribute before
/// this macro runs, so when the command uses `rename_all = "snake_case"` or
/// `rename = "..."`, repeat it here — `#[inspectable(rename_all = "snake_case")]`,
/// `#[inspectable(rename = "...")]`. (Written *above* `#[tauri::command(...)]`,
/// `#[inspectable]` reads those options itself.)
///
/// # Example
///
/// ```rust,ignore
/// #[tauri::command]
/// #[inspectable(description = "Save API key for a provider")]
/// async fn save_api_key(provider: String, key: String) -> Result<(), String> {
///     // ...
/// }
///
/// // At setup:
/// state.registry.register(save_api_key__schema());
/// ```
///
/// # Release builds
///
/// Everything Victauri-specific is gated on `debug_assertions`, evaluated in YOUR crate's
/// profile (the Victauri plugin is a no-op in release, so nothing could read it):
///
/// - the auto-discovery registration (what `VictauriBuilder::auto_discover()` collects) is not
///   emitted, so a release build has no startup constructor for it;
/// - the `<fn>__schema()` companion still exists — code passing it to
///   `VictauriBuilder::commands(...)` or `register_commands!` keeps compiling — but returns
///   only the command name (and whether it is async): the description, intent, category,
///   examples and argument/return types are not compiled in.
///
/// So none of the metadata strings ship in a release binary.
#[proc_macro_attribute]
pub fn inspectable(attr: TokenStream, item: TokenStream) -> TokenStream {
    let input = parse_macro_input!(item as ItemFn);
    let attrs = match parse_attrs(attr) {
        Ok(a) => a,
        Err(e) => return e.to_compile_error().into(),
    };
    TokenStream::from(expand(input, attrs))
}

/// The expansion of `#[inspectable]` (split out so it can be unit-tested with `proc_macro2`).
fn expand(input: ItemFn, attrs: InspectableAttrs) -> proc_macro2::TokenStream {
    let command_options = tauri_command_options(&input.attrs);

    let fn_name = &input.sig.ident;
    let schema_fn_name = syn::Ident::new(&format!("{fn_name}__schema"), fn_name.span());
    // The name the frontend invokes: Tauri's `rename`, else the bare identifier
    // (`r#type` is invoked as `type`).
    let command_name = attrs
        .rename
        .clone()
        .or(command_options.rename)
        .unwrap_or_else(|| fn_name.unraw().to_string());
    let is_async = input.sig.asyncness.is_some();

    let description = attrs
        .description
        .unwrap_or_else(|| command_name.replace('_', " "));

    let snake_case = attrs
        .snake_case
        .or(command_options.snake_case)
        .unwrap_or(false);
    let args_info = extract_args(&input.sig);
    let arg_tokens: Vec<_> = args_info
        .iter()
        .map(|(name, type_str, required)| {
            let key = invoke_key(name, snake_case);
            quote! {
                victauri_core::registry::CommandArg::new(#name, #type_str, #required)
                    .with_key(#key)
            }
        })
        .collect();

    let return_type = extract_return_type(&input.sig);

    let intent_token = attrs.intent.as_ref().map(|i| quote! { .with_intent(#i) });

    let category_token = attrs
        .category
        .as_ref()
        .map(|c| quote! { .with_category(#c) });

    let example_tokens: Vec<_> = attrs
        .examples
        .iter()
        .map(|e| quote! { #e.to_string() })
        .collect();

    let expanded = quote! {
        #input

        #[allow(dead_code, non_snake_case)]
        fn #schema_fn_name() -> victauri_core::registry::CommandInfo {
            // Built via constructors, not a struct literal: `CommandInfo` and
            // `CommandArg` are `#[non_exhaustive]`, and this code expands in the
            // user's crate.
            #[cfg(debug_assertions)]
            let info = victauri_core::registry::CommandInfo::new(#command_name)
                .with_description(#description)
                .with_args(vec![#(#arg_tokens),*])
                .with_return_type(#return_type)
                .with_async(#is_async)
                #intent_token
                #category_token
                .with_examples(vec![#(#example_tokens),*]);
            // Release (the consumer's profile): the name only, so none of the metadata
            // strings ship — see "Release builds" above.
            #[cfg(not(debug_assertions))]
            let info = victauri_core::registry::CommandInfo::new(#command_name)
                .with_async(#is_async);
            info
        }

        // Debug builds only, in the consumer's profile — see "Release builds" above.
        #[cfg(debug_assertions)]
        victauri_core::inventory::submit! {
            victauri_core::registry::CommandInfoFactory(#schema_fn_name)
        }
    };

    expanded
}

#[derive(Default)]
struct InspectableAttrs {
    description: Option<String>,
    intent: Option<String>,
    category: Option<String>,
    examples: Vec<String>,
    /// `rename = "..."`: the name the command is invoked by.
    rename: Option<String>,
    /// `rename_all = "snake_case" | "camelCase"`: the argument key case.
    snake_case: Option<bool>,
}

/// The options of a `#[tauri::command(...)]` still present on the function, which
/// happens only when `#[inspectable]` is written above it.
#[derive(Default)]
struct CommandOptions {
    rename: Option<String>,
    snake_case: Option<bool>,
}

fn parse_rename_all(lit: &syn::LitStr) -> syn::Result<bool> {
    match lit.value().as_str() {
        "snake_case" => Ok(true),
        "camelCase" => Ok(false),
        _ => Err(syn::Error::new(
            lit.span(),
            "expected \"camelCase\" or \"snake_case\"",
        )),
    }
}

fn tauri_command_options(fn_attrs: &[syn::Attribute]) -> CommandOptions {
    let mut out = CommandOptions::default();
    for attr in fn_attrs {
        let path = attr.path();
        let is_command = path.segments.last().is_some_and(|s| s.ident == "command")
            && (path.segments.len() == 1 || path.segments[0].ident == "tauri");
        if !is_command || !matches!(attr.meta, syn::Meta::List(_)) {
            continue;
        }
        // Best effort: Tauri validates its own attribute (and `async` is a keyword
        // `parse_nested_meta` refuses), so a parse failure here is never an error.
        let _ = attr.parse_nested_meta(|meta| {
            if meta.path.is_ident("rename_all") {
                out.snake_case = Some(parse_rename_all(&meta.value()?.parse()?)?);
            } else if meta.path.is_ident("rename") {
                out.rename = Some(meta.value()?.parse::<syn::LitStr>()?.value());
            } else if meta.input.peek(syn::Token![=]) {
                // Other options (`root = "..."`) are Tauri's business.
                let _: syn::Expr = meta.value()?.parse()?;
            }
            Ok(())
        });
    }
    out
}

/// The IPC key Tauri derives for an argument name (tauri-macros `ArgumentCase`).
fn invoke_key(name: &str, snake_case: bool) -> String {
    if snake_case {
        name.to_snake_case()
    } else {
        name.to_lower_camel_case()
    }
}

fn parse_attrs(attr: TokenStream) -> syn::Result<InspectableAttrs> {
    let mut attrs = InspectableAttrs::default();

    let parser = syn::meta::parser(|meta| {
        if meta.path.is_ident("description") {
            attrs.description = Some(meta.value()?.parse::<syn::LitStr>()?.value());
        } else if meta.path.is_ident("intent") {
            attrs.intent = Some(meta.value()?.parse::<syn::LitStr>()?.value());
        } else if meta.path.is_ident("category") {
            attrs.category = Some(meta.value()?.parse::<syn::LitStr>()?.value());
        } else if meta.path.is_ident("example") {
            attrs
                .examples
                .push(meta.value()?.parse::<syn::LitStr>()?.value());
        } else if meta.path.is_ident("rename") {
            attrs.rename = Some(meta.value()?.parse::<syn::LitStr>()?.value());
        } else if meta.path.is_ident("rename_all") {
            attrs.snake_case = Some(parse_rename_all(&meta.value()?.parse()?)?);
        } else {
            return Err(meta.error("unknown #[inspectable] attribute"));
        }
        Ok(())
    });

    syn::parse::Parser::parse(parser, attr)?;
    Ok(attrs)
}

fn extract_args(sig: &syn::Signature) -> Vec<(String, String, bool)> {
    sig.inputs
        .iter()
        .filter_map(|arg| {
            if let syn::FnArg::Typed(pat_type) = arg {
                let name = match &*pat_type.pat {
                    syn::Pat::Ident(ident) => ident.ident.unraw().to_string(),
                    _ => return None,
                };

                let ty = &*pat_type.ty;
                if is_tauri_framework_type(ty) {
                    return None;
                }
                let type_str = quote!(#ty).to_string();

                let is_option = type_str.starts_with("Option")
                    || type_str.starts_with("Option <")
                    || type_str.contains(":: Option");
                let type_name = type_str;

                Some((name, type_name, !is_option))
            } else {
                None
            }
        })
        .collect()
}

/// Whether Tauri injects this argument itself (the `CommandArg` impls that do not
/// read the invoke payload), so it never appears in the frontend's arguments.
fn is_tauri_framework_type(ty: &syn::Type) -> bool {
    const FRAMEWORK_TYPES: &[&str] = &[
        "AppHandle",
        "State",
        "Window",
        "Webview",
        "WebviewWindow",
        "Request",
        "CommandScope",
        "GlobalScope",
    ];
    let ty = match ty {
        syn::Type::Reference(r) => &*r.elem,
        syn::Type::Paren(p) => &*p.elem,
        syn::Type::Group(g) => &*g.elem,
        other => other,
    };
    // Judge by the path's LAST segment, never by splitting its tokens as a string:
    // `State<'_, my::Pool>` has a `::` inside its generics.
    let syn::Type::Path(path) = ty else {
        return false;
    };
    path.path
        .segments
        .last()
        .is_some_and(|seg| FRAMEWORK_TYPES.iter().any(|t| seg.ident == t))
}

fn extract_return_type(sig: &syn::Signature) -> String {
    match &sig.output {
        syn::ReturnType::Default => "()".to_string(),
        syn::ReturnType::Type(_, ty) => quote!(#ty).to_string(),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    fn fn_attrs(src: &str) -> Vec<syn::Attribute> {
        syn::parse_str::<ItemFn>(src).unwrap().attrs
    }

    #[test]
    fn reads_rename_options_from_a_tauri_command_attribute() {
        let o = tauri_command_options(&fn_attrs(
            "#[tauri::command(rename_all = \"snake_case\", rename = \"x\")] fn f() {}",
        ));
        assert_eq!(o.snake_case, Some(true));
        assert_eq!(o.rename.as_deref(), Some("x"));
    }

    #[test]
    fn tolerates_the_rest_of_tauris_attribute_grammar() {
        for src in [
            "#[tauri::command(async)] fn f() {}",
            "#[command(root = \"crate\", rename_all = \"snake_case\")] fn f() {}",
            "#[tauri::command] fn f() {}",
            "#[other::command(rename = \"no\")] fn f() {}",
        ] {
            let o = tauri_command_options(&fn_attrs(src));
            assert!(o.rename.is_none() || src.contains("root"), "{src}");
        }
        let o = tauri_command_options(&fn_attrs(
            "#[command(root = \"crate\", rename_all = \"snake_case\")] fn f() {}",
        ));
        assert_eq!(o.snake_case, Some(true));
    }

    /// The inventory registration (and with it every description/intent/example string and the
    /// startup constructor) must exist only in debug builds of the CONSUMER, while the
    /// `__schema()` companion stays available in every profile.
    #[test]
    fn registration_is_gated_on_debug_assertions_but_schema_fn_is_not() {
        let item =
            syn::parse_str::<ItemFn>("#[tauri::command] fn greet(name: String) -> String { name }")
                .unwrap();
        let attrs = InspectableAttrs {
            description: Some("Greet a person by name".into()),
            ..InspectableAttrs::default()
        };
        let file: syn::File = syn::parse2(expand(item, attrs)).unwrap();
        let debug_only = |attrs: &[syn::Attribute]| {
            attrs.iter().any(|a| {
                a.path().is_ident("cfg")
                    && a.parse_args::<syn::Ident>()
                        .is_ok_and(|i| i == "debug_assertions")
            })
        };

        let mut saw_schema_fn = false;
        let mut saw_submit = false;
        for item in &file.items {
            match item {
                syn::Item::Fn(f) if f.sig.ident == "greet__schema" => {
                    saw_schema_fn = true;
                    assert!(
                        !debug_only(&f.attrs),
                        "the schema companion must exist in every profile"
                    );
                    // The metadata is built only in the debug `let`; the release one has no
                    // description string.
                    let lets: Vec<&syn::Local> = f
                        .block
                        .stmts
                        .iter()
                        .filter_map(|s| match s {
                            syn::Stmt::Local(l) => Some(l),
                            _ => None,
                        })
                        .collect();
                    assert_eq!(lets.len(), 2, "one debug and one release `let info`");
                    for local in lets {
                        let text = quote!(#local).to_string();
                        if debug_only(&local.attrs) {
                            assert!(text.contains("Greet a person by name"), "{text}");
                        } else {
                            assert!(
                                local.attrs.iter().any(|a| quote!(#a)
                                    .to_string()
                                    .contains("not (debug_assertions)")),
                                "{text}"
                            );
                            assert!(!text.contains("Greet a person by name"), "{text}");
                            assert!(!text.contains("with_description"), "{text}");
                        }
                    }
                }
                syn::Item::Macro(m)
                    if m.mac
                        .path
                        .segments
                        .last()
                        .is_some_and(|s| s.ident == "submit") =>
                {
                    saw_submit = true;
                    assert!(
                        debug_only(&m.attrs),
                        "inventory::submit! must be #[cfg(debug_assertions)]"
                    );
                }
                _ => {}
            }
        }
        assert!(saw_schema_fn, "no greet__schema fn in the expansion");
        assert!(saw_submit, "no inventory::submit! in the expansion");
    }

    #[test]
    fn keys_match_tauri_argument_case() {
        assert_eq!(invoke_key("size_kb", false), "sizeKb");
        assert_eq!(invoke_key("a1_b", false), "a1B");
        assert_eq!(invoke_key("name", false), "name");
        assert_eq!(invoke_key("size_kb", true), "size_kb");
    }
}