Skip to main content

gemini_adk_macros_rs/
lib.rs

1#![cfg_attr(docsrs, feature(doc_cfg))]
2#![forbid(unsafe_code)]
3#![warn(missing_docs)]
4//! Procedural macros for `gemini-adk-rs`.
5//!
6//! This crate provides the [`macro@tool`] attribute macro, which turns a plain
7//! `async fn` into a registrable Gemini tool — eliminating the
8//! `TypedTool::new::<Args>` + separate-args-struct ceremony.
9//!
10//! You normally don't depend on this crate directly. The [`macro@tool`] macro is
11//! re-exported from `gemini-adk-rs` and the `gemini-adk-fluent-rs` prelude:
12//!
13//! ```ignore
14//! use gemini_adk_fluent_rs::prelude::*;   // brings `tool` into scope
15//! use serde_json::{json, Value};
16//!
17//! /// Get the current weather for a city.
18//! ///
19//! /// # Arguments
20//! ///
21//! /// * `city` - The city name.
22//! /// * `units` - "metric" or "imperial"; metric when omitted.
23//! #[tool]
24//! async fn get_weather(city: String, units: Option<String>) -> Result<Value, ToolError> {
25//!     Ok(json!({ "city": city, "units": units.unwrap_or("metric".into()) }))
26//! }
27//!
28//! // `get_weather()` returns a value implementing `ToolFunction`.
29//! let mut d = ToolDispatcher::new();
30//! d.register_function(std::sync::Arc::new(get_weather()));
31//! ```
32
33use proc_macro::TokenStream;
34use proc_macro2::Span;
35use quote::{format_ident, quote};
36use syn::{
37    Data, DeriveInput, Expr, ExprLit, Fields, FnArg, ItemFn, Lit, LitInt, LitStr, Meta, Pat,
38    PatType, ReturnType, Type, TypePath, parse_macro_input,
39};
40
41/// Where the runtime crate (`gemini-adk-rs`) is reachable from the expansion
42/// site, as a path and as the string form the derive `crate = ".."` attributes
43/// want.
44///
45/// A direct dependency wins (under whatever name it was renamed to); a crate
46/// that depends only on `gemini-adk-fluent-rs`, or only on the `gemini-adk`
47/// facade, reaches it through that crate's `gemini_adk_rs` re-export. Inside
48/// `gemini-adk-rs` itself the crate declares `extern crate self as
49/// gemini_adk_rs`, so the plain name works there and in its own tests.
50fn runtime() -> (proc_macro2::TokenStream, String) {
51    use proc_macro_crate::{FoundCrate, crate_name};
52    match crate_name("gemini-adk-rs") {
53        Ok(FoundCrate::Name(name)) => {
54            let ident = format_ident!("{name}");
55            (quote! { ::#ident }, name)
56        }
57        Ok(FoundCrate::Itself) => (quote! { ::gemini_adk_rs }, "gemini_adk_rs".to_string()),
58        // Otherwise through a crate that re-exports it: the `gemini-adk`
59        // facade (first, so its own tests exercise this path), or the fluent
60        // layer it wraps.
61        Err(_) => ["gemini-adk", "gemini-adk-fluent-rs"]
62            .into_iter()
63            .find_map(|facade| match crate_name(facade) {
64                Ok(FoundCrate::Name(name)) => Some(name),
65                Ok(FoundCrate::Itself) => Some(facade.replace('-', "_")),
66                Err(_) => None,
67            })
68            .map_or_else(
69                || (quote! { ::gemini_adk_rs }, "gemini_adk_rs".to_string()),
70                |name| {
71                    let ident = format_ident!("{name}");
72                    (
73                        quote! { ::#ident::gemini_adk_rs },
74                        format!("{name}::gemini_adk_rs"),
75                    )
76                },
77            ),
78    }
79}
80
81/// Turn a documented `async fn` into a registrable Gemini tool.
82///
83/// The function's doc comment is what the model reads: its opening prose is
84/// the tool's description, and a `# Arguments` section describes each
85/// parameter. The parameter types are the schema.
86///
87/// ```ignore
88/// /// Get the current weather for a city.
89/// ///
90/// /// # Arguments
91/// ///
92/// /// * `city` - The city name, e.g. "Paris".
93/// /// * `units` - "metric" or "imperial"; metric when omitted.
94/// #[tool]
95/// async fn get_weather(city: String, units: Option<String>) -> Result<Weather, reqwest::Error> {
96///     fetch_weather(&city, units.as_deref()).await
97/// }
98///
99/// agent.tool(get_weather());
100/// ```
101///
102/// # Description
103///
104/// The doc comment's prose up to its first `#` heading, with wrapped lines
105/// joined. `#[tool("...")]` replaces it when the text for the model should
106/// differ from the text for readers. A tool with neither is a compile error:
107/// the model chooses tools by their descriptions.
108///
109/// # Arguments
110///
111/// Each item of a `# Arguments` (or `# Args`, `# Parameters`) section — in the
112/// rustdoc form ``* `name` - text`` or ``- `name`: text`` — becomes that
113/// parameter's schema `description`. Naming a parameter the function does not
114/// have is a compile error, so the documentation cannot drift from the
115/// signature.
116///
117/// Every parameter type must be `serde::Deserialize + schemars::JsonSchema`
118/// and owned (`String`, not `&str`): arguments are deserialized from the
119/// model's JSON. `Option<T>` parameters are optional. The schema is produced
120/// by `gemini_adk_rs::tool::wire_schema`, so nested types are inlined and
121/// optional fields declare a single type, as the API requires.
122///
123/// # Return type
124///
125/// - A type spelled `Result<T, E>` (under any path: `anyhow::Result<T>`,
126///   `io::Result<T>`) is fallible. `T` is any `serde::Serialize` type; `E` is
127///   any error — a `ToolError` keeps its variant, anything else becomes
128///   `ToolError::ExecutionFailed` with its message.
129/// - Any other type is the tool's output, and the tool cannot fail.
130/// - No return type sends `null`.
131///
132/// A result that is not a JSON object reaches the model as `{"output": ..}`.
133/// A `Result` behind an alias with another name is not recognized; spell the
134/// return type as `Result<..>`.
135///
136/// # What it generates
137///
138/// A constructor `fn get_weather() -> impl ToolFunction` (with the original
139/// visibility and doc comment) whose value you register:
140/// `agent.tool(get_weather())`, or
141/// `dispatcher.register_function(Arc::new(get_weather()))`. The original body
142/// runs in a hidden `async fn`, which keeps the function's other attributes
143/// (`#[allow]`, `#[tracing::instrument]`, ...); `#[cfg]` applies to every
144/// generated item.
145///
146/// # Path hygiene
147///
148/// Generated code reaches `serde`, `schemars`, `serde_json`, and `async_trait`
149/// through the runtime crate's `__macros` module, so none of them need to be
150/// in your `Cargo.toml`. The runtime crate is located at expansion time:
151/// `gemini-adk-rs` if it is a direct dependency (under whatever name), else
152/// through the re-export in `gemini-adk` or `gemini-adk-fluent-rs`.
153#[proc_macro_attribute]
154pub fn tool(attr: TokenStream, item: TokenStream) -> TokenStream {
155    let description = if attr.is_empty() {
156        None
157    } else {
158        Some(parse_macro_input!(attr as LitStr))
159    };
160    let func = parse_macro_input!(item as ItemFn);
161
162    match expand(description, func) {
163        Ok(ts) => ts.into(),
164        Err(e) => e.to_compile_error().into(),
165    }
166}
167
168/// What a `#[tool]` fn's doc comment says, split into the parts the model sees.
169#[derive(Debug, Default, PartialEq)]
170struct ToolDocs {
171    /// Prose before the first heading, paragraphs separated by a blank line.
172    description: String,
173    /// `(parameter, description)` from the `# Arguments` section, in order.
174    arguments: Vec<(String, String)>,
175}
176
177/// The text of each `#[doc = ".."]` attribute, one entry per doc line.
178fn doc_lines(attrs: &[syn::Attribute]) -> Vec<String> {
179    attrs
180        .iter()
181        .filter(|a| a.path().is_ident("doc"))
182        .filter_map(|a| match &a.meta {
183            Meta::NameValue(nv) => match &nv.value {
184                Expr::Lit(ExprLit {
185                    lit: Lit::Str(s), ..
186                }) => Some(s.value()),
187                _ => None,
188            },
189            _ => None,
190        })
191        .flat_map(|text| text.lines().map(str::to_owned).collect::<Vec<_>>())
192        .collect()
193}
194
195/// Split doc lines into the description and the `# Arguments` items.
196fn parse_docs(lines: &[String]) -> ToolDocs {
197    let mut docs = ToolDocs::default();
198    let mut paragraphs: Vec<String> = Vec::new();
199    let mut paragraph = String::new();
200    // `None` before the first heading; then whether we are in an arguments section.
201    let mut section: Option<bool> = None;
202
203    let flush = |paragraph: &mut String, paragraphs: &mut Vec<String>| {
204        if !paragraph.is_empty() {
205            paragraphs.push(std::mem::take(paragraph));
206        }
207    };
208
209    let mut in_code = false;
210    for raw in lines {
211        let line = raw.trim();
212        // Code blocks are for readers, and their `# hidden` lines are not headings.
213        if line.starts_with("```") || line.starts_with("~~~") {
214            in_code = !in_code;
215            continue;
216        }
217        if in_code {
218            continue;
219        }
220        if let Some(heading) = line.strip_prefix('#') {
221            let heading = heading.trim_start_matches('#').trim().to_ascii_lowercase();
222            section = Some(matches!(
223                heading.as_str(),
224                "arguments" | "args" | "parameters" | "params"
225            ));
226            continue;
227        }
228        match section {
229            None if line.is_empty() => flush(&mut paragraph, &mut paragraphs),
230            None => {
231                if !paragraph.is_empty() {
232                    paragraph.push(' ');
233                }
234                paragraph.push_str(line);
235            }
236            Some(true) => {
237                if let Some(item) = line.strip_prefix(['*', '-']) {
238                    if let Some(parsed) = parse_argument_item(item) {
239                        docs.arguments.push(parsed);
240                    }
241                } else if !line.is_empty()
242                    && let Some((_, text)) = docs.arguments.last_mut()
243                {
244                    if !text.is_empty() {
245                        text.push(' ');
246                    }
247                    text.push_str(line);
248                }
249            }
250            Some(false) => {}
251        }
252    }
253    flush(&mut paragraph, &mut paragraphs);
254    docs.description = paragraphs.join("\n\n");
255    docs
256}
257
258/// Parse ``` `name` - text``` / ``name: text`` into `(name, text)`.
259fn parse_argument_item(item: &str) -> Option<(String, String)> {
260    let item = item.trim();
261    let (name, rest) = if let Some(quoted) = item.strip_prefix('`') {
262        let end = quoted.find('`')?;
263        (&quoted[..end], &quoted[end + 1..])
264    } else {
265        let end = item
266            .find(|c: char| !(c.is_alphanumeric() || c == '_'))
267            .unwrap_or(item.len());
268        (&item[..end], &item[end..])
269    };
270    if name.is_empty() {
271        return None;
272    }
273    let text = rest
274        .trim_start()
275        .trim_start_matches(['-', ':', '\u{2013}', '\u{2014}'])
276        .trim();
277    Some((name.to_owned(), text.to_owned()))
278}
279
280/// Whether a return type is spelled `Result<..>` under any path.
281/// Whether `ty` is the runtime's `ToolContext` (by its last path segment),
282/// which `#[tool]` injects rather than asks the model for.
283fn is_tool_context(ty: &Type) -> bool {
284    match ty {
285        Type::Path(path) => path
286            .path
287            .segments
288            .last()
289            .is_some_and(|seg| seg.ident == "ToolContext" && seg.arguments.is_empty()),
290        _ => false,
291    }
292}
293
294fn is_result(ty: &Type) -> bool {
295    let Type::Path(TypePath { qself: None, path }) = ty else {
296        return false;
297    };
298    path.segments
299        .last()
300        .is_some_and(|seg| seg.ident == "Result" && !seg.arguments.is_none())
301}
302
303fn expand(description: Option<LitStr>, func: ItemFn) -> syn::Result<proc_macro2::TokenStream> {
304    let sig = &func.sig;
305
306    if sig.asyncness.is_none() {
307        return Err(syn::Error::new_spanned(
308            sig.fn_token,
309            "#[tool] requires an `async fn`",
310        ));
311    }
312    if let Some(variadic) = &sig.variadic {
313        return Err(syn::Error::new_spanned(
314            variadic,
315            "#[tool] does not support variadic functions",
316        ));
317    }
318    if !sig.generics.params.is_empty() {
319        return Err(syn::Error::new_spanned(
320            sig.generics.clone(),
321            "#[tool] does not support generic functions",
322        ));
323    }
324
325    let fn_name = &sig.ident;
326    let vis = &func.vis;
327    let body = &func.block;
328
329    // Collect (ident, type) for each parameter; reject `self` receivers,
330    // patterns and borrowed types.
331    let mut field_idents = Vec::new();
332    let mut field_types = Vec::new();
333    // Every parameter in declaration order (for the preserved body), and the
334    // one typed `ToolContext`, which the runtime fills instead of the model.
335    let mut param_idents = Vec::new();
336    let mut param_types = Vec::new();
337    let mut context_ident: Option<syn::Ident> = None;
338    for input in &sig.inputs {
339        match input {
340            FnArg::Receiver(r) => {
341                return Err(syn::Error::new_spanned(
342                    r,
343                    "#[tool] cannot be applied to methods taking `self`",
344                ));
345            }
346            FnArg::Typed(PatType { pat, ty, .. }) => {
347                let ident = match pat.as_ref() {
348                    Pat::Ident(pat_ident) => pat_ident.ident.clone(),
349                    other => {
350                        return Err(syn::Error::new_spanned(
351                            other,
352                            "#[tool] parameters must be simple identifiers (no patterns)",
353                        ));
354                    }
355                };
356                param_idents.push(ident.clone());
357                param_types.push((*ty).clone());
358                if is_tool_context(ty) {
359                    if context_ident.is_some() {
360                        return Err(syn::Error::new_spanned(
361                            ty,
362                            "#[tool] takes at most one `ToolContext` parameter",
363                        ));
364                    }
365                    context_ident = Some(ident);
366                    continue;
367                }
368                if let Type::Reference(reference) = ty.as_ref() {
369                    return Err(syn::Error::new_spanned(
370                        reference,
371                        "#[tool] parameters are deserialized from the model's JSON, so they \
372                         must be owned: use `String` for `&str`, `Vec<T>` for `&[T]`",
373                    ));
374                }
375                field_idents.push(ident);
376                field_types.push((*ty).clone());
377            }
378        }
379    }
380
381    // What the model is told: the attribute wins, else the doc comment.
382    let docs = parse_docs(&doc_lines(&func.attrs));
383    for (name, _) in &docs.arguments {
384        if !field_idents.iter().any(|ident| ident == name) {
385            return Err(syn::Error::new_spanned(
386                fn_name,
387                format!(
388                    "the `# Arguments` section documents `{name}`, which is not a parameter \
389                     of `{fn_name}`"
390                ),
391            ));
392        }
393    }
394    let description = match description {
395        Some(text) => text.value(),
396        None if !docs.description.is_empty() => docs.description.clone(),
397        None => {
398            return Err(syn::Error::new_spanned(
399                fn_name,
400                "#[tool] needs a description for the model: add a `///` doc comment to the \
401                 function, or pass one as `#[tool(\"...\")]`",
402            ));
403        }
404    };
405
406    // The body keeps its declared return type; the tool adapts it.
407    let (return_type, adapt) = match &sig.output {
408        ReturnType::Default => (quote! { () }, quote! { tool_output }),
409        ReturnType::Type(_, ty) if is_result(ty) => (quote! { #ty }, quote! { tool_result }),
410        ReturnType::Type(_, ty) => (quote! { #ty }, quote! { tool_output }),
411    };
412
413    // `#[cfg]` gates every generated item; docs and `#[deprecated]` describe
414    // the constructor users call; everything else belongs with the body.
415    let mut cfg_attrs = Vec::new();
416    let mut constructor_attrs = Vec::new();
417    let mut body_attrs = Vec::new();
418    for attr in &func.attrs {
419        let path = attr.path();
420        if path.is_ident("cfg") {
421            cfg_attrs.push(attr);
422        } else if path.is_ident("doc") || path.is_ident("deprecated") {
423            constructor_attrs.push(attr);
424        } else {
425            body_attrs.push(attr);
426        }
427    }
428
429    // Naming for generated items, derived from the (Pascal-cased) fn name.
430    let pascal = to_pascal_case(&fn_name.to_string());
431    let args_struct = format_ident!("__{}Args", pascal);
432    let tool_struct = format_ident!("__{}Tool", pascal);
433    // The inner async fn that holds the original body, invoked from `call`.
434    let inner_fn = format_ident!("__{}_impl", fn_name);
435
436    let fn_name_str = fn_name.to_string();
437
438    // Build the hidden args struct fields; a documented parameter carries its
439    // text as a doc comment, which the schema derive turns into `description`.
440    let struct_fields = field_idents
441        .iter()
442        .zip(field_types.iter())
443        .map(|(ident, ty)| {
444            let doc = docs
445                .arguments
446                .iter()
447                .find(|(name, _)| ident == name)
448                .map(|(_, text)| text.as_str())
449                .filter(|text| !text.is_empty())
450                .map(|text| quote! { #[doc = #text] });
451            // `Option<T>` fields default to `None` when absent from the JSON.
452            // No trailing comma here — `#(#struct_fields),*` adds the separators.
453            let default = is_option(ty).then(|| quote! { #[serde(default)] });
454            quote! {
455                #doc
456                #default
457                #ident: #ty
458            }
459        });
460
461    // Upstream crates are reached through `gemini_adk_rs::__macros` so the consumer
462    // doesn't need them in scope under those exact names.
463    let (rt, rt_str) = runtime();
464    let serde = quote! { #rt::__macros::serde };
465    let schemars = quote! { #rt::__macros::schemars };
466    let async_trait = quote! { #rt::__macros::async_trait };
467    let serde_json = quote! { #rt::__macros::serde_json };
468    let serde_crate = LitStr::new(&format!("{rt_str}::__macros::serde"), Span::call_site());
469    let schemars_crate = LitStr::new(&format!("{rt_str}::__macros::schemars"), Span::call_site());
470
471    // Bind the runtime's context to the parameter that asked for it.
472    let bind_context = match &context_ident {
473        Some(ident) => quote! { let #ident = ctx; },
474        None => quote! { let _ = ctx; },
475    };
476
477    let expanded = quote! {
478        // Hidden args struct: drives both deserialization and schema generation.
479        #(#cfg_attrs)*
480        #[derive(#serde::Deserialize, #schemars::JsonSchema)]
481        #[serde(crate = #serde_crate)]
482        #[schemars(crate = #schemars_crate)]
483        #[allow(non_camel_case_types, non_snake_case)]
484        struct #args_struct {
485            #(#struct_fields),*
486        }
487
488        // The original function body, preserved verbatim as a free async fn.
489        #(#cfg_attrs)*
490        #(#body_attrs)*
491        #[allow(non_snake_case)]
492        async fn #inner_fn ( #(#param_idents : #param_types),* ) -> #return_type #body
493
494        // Hidden tool type implementing `ToolFunction`.
495        #(#cfg_attrs)*
496        #[allow(non_camel_case_types)]
497        #[derive(Clone, Copy, Debug, Default)]
498        #vis struct #tool_struct;
499
500        #(#cfg_attrs)*
501        #[#async_trait::async_trait]
502        impl #rt::tool::ToolFunction for #tool_struct {
503            fn name(&self) -> &str {
504                #fn_name_str
505            }
506
507            fn description(&self) -> &str {
508                #description
509            }
510
511            fn parameters(&self) -> ::core::option::Option<#serde_json::Value> {
512                // The args struct's name is an implementation detail; the
513                // tool's name and description are what the model reads.
514                let mut schema = #rt::tool::wire_schema::<#args_struct>();
515                if let ::core::option::Option::Some(object) = schema.as_object_mut() {
516                    object.remove("title");
517                }
518                ::core::option::Option::Some(schema)
519            }
520
521            async fn call(
522                &self,
523                args: #serde_json::Value,
524            ) -> ::core::result::Result<#serde_json::Value, #rt::error::ToolError> {
525                self.call_with_context(args, #rt::tool::ToolContext::detached()).await
526            }
527
528            async fn call_with_context(
529                &self,
530                args: #serde_json::Value,
531                ctx: #rt::tool::ToolContext,
532            ) -> ::core::result::Result<#serde_json::Value, #rt::error::ToolError> {
533                let #args_struct { #(#field_idents),* } =
534                    #serde_json::from_value(args).map_err(|e| {
535                        #rt::error::ToolError::InvalidArgs(
536                            ::std::format!("Failed to deserialize arguments: {e}"),
537                        )
538                    })?;
539                #bind_context
540                #rt::__macros::#adapt(#inner_fn ( #(#param_idents),* ).await)
541            }
542        }
543
544        // Public constructor: `fn foo() -> __FooTool`.
545        #(#cfg_attrs)*
546        #(#constructor_attrs)*
547        #[allow(non_snake_case)]
548        #vis fn #fn_name () -> #tool_struct {
549            #tool_struct
550        }
551    };
552
553    Ok(expanded)
554}
555
556/// Derive an `Extract` record builder from a struct's fields.
557///
558/// Each field carries a `#[recognize(..)]` attribute naming a deterministic
559/// recognizer; the macro generates an inherent `fn extract() -> Extract` that
560/// builds the record. The field name becomes the record field name and (by
561/// default) its `State` key.
562///
563/// ```ignore
564/// use gemini_adk_rs::extract::Extract;   // the type — same name, type namespace
565/// use gemini_adk_rs::Extract;            // the derive — macro namespace
566///
567/// #[derive(Extract)]
568/// #[extract(name = "order", window = 3)]
569/// struct Order {
570///     #[recognize(integer_near = ["want", "get"])]
571///     quantity: Option<i64>,
572///     #[recognize(one_of = ["pizza", "salad", "soda"])]
573///     item: Option<String>,
574///     #[recognize(datetime)]
575///     #[extract(state = "when")]
576///     pickup: Option<serde_json::Value>,
577///     #[recognize(yes_no)]
578///     confirmed: Option<bool>,
579/// }
580///
581/// let record: Extract = Order::extract();
582/// ```
583///
584/// # Recognizer forms
585///
586/// | Attribute | Recognizer |
587/// |---|---|
588/// | `#[recognize(integer)]` | `Recognizer::integer()` |
589/// | `#[recognize(integer_near = ["a", "b"])]` | `Recognizer::integer_near([..])` |
590/// | `#[recognize(money)]` | `Recognizer::money()` |
591/// | `#[recognize(regex = "pat")]` | `Recognizer::regex("pat")` |
592/// | `#[recognize(one_of = ["a", "b"])]` | `Recognizer::one_of([..])` |
593/// | `#[recognize(fuzzy = ["a", "b"])]` | `Recognizer::fuzzy([..])` |
594/// | `#[recognize(yes_no)]` | `Recognizer::yes_no()` |
595/// | `#[recognize(datetime)]` | `Recognizer::datetime()` |
596///
597/// # Options
598///
599/// - Container `#[extract(name = "...")]` — record name (default: the struct
600///   name in `snake_case`).
601/// - Container `#[extract(window = N)]` — transcript window (default `3`).
602/// - Field `#[extract(state = "key")]` — promote to a custom `State` key.
603///
604/// Fields without a `#[recognize(..)]` attribute are ignored.
605#[proc_macro_derive(Extract, attributes(recognize, extract))]
606pub fn derive_extract(item: TokenStream) -> TokenStream {
607    let input = parse_macro_input!(item as DeriveInput);
608    match expand_extract(input) {
609        Ok(ts) => ts.into(),
610        Err(e) => e.to_compile_error().into(),
611    }
612}
613
614fn expand_extract(input: DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
615    let (rt, _) = runtime();
616    let ident = &input.ident;
617
618    let fields = match &input.data {
619        Data::Struct(s) => match &s.fields {
620            Fields::Named(named) => &named.named,
621            _ => {
622                return Err(syn::Error::new_spanned(
623                    ident,
624                    "#[derive(Extract)] requires a struct with named fields",
625                ));
626            }
627        },
628        _ => {
629            return Err(syn::Error::new_spanned(
630                ident,
631                "#[derive(Extract)] can only be applied to structs",
632            ));
633        }
634    };
635
636    // Container options: name + window.
637    let mut name = to_snake_case(&ident.to_string());
638    let mut window: usize = 3;
639    for attr in &input.attrs {
640        if attr.path().is_ident("extract") {
641            attr.parse_nested_meta(|meta| {
642                if meta.path.is_ident("name") {
643                    let v: LitStr = meta.value()?.parse()?;
644                    name = v.value();
645                } else if meta.path.is_ident("window") {
646                    let v: LitInt = meta.value()?.parse()?;
647                    window = v.base10_parse()?;
648                } else {
649                    return Err(
650                        meta.error("unknown `extract` option (expected `name` or `window`)")
651                    );
652                }
653                Ok(())
654            })?;
655        }
656    }
657
658    // Every named field, referenced by a hidden marker method so that deriving
659    // `Extract` on an otherwise-unread struct does not trip `dead_code`.
660    let all_field_idents: Vec<_> = fields.iter().filter_map(|f| f.ident.clone()).collect();
661
662    // One `.field(..)` / `.field_to(..)` call per recognized field.
663    let mut field_calls = Vec::new();
664    for field in fields {
665        let Some(recognize) = field.attrs.iter().find(|a| a.path().is_ident("recognize")) else {
666            continue;
667        };
668        let fname = field
669            .ident
670            .as_ref()
671            .ok_or_else(|| syn::Error::new_spanned(field, "expected a named field"))?
672            .to_string();
673        let recognizer = recognizer_expr(recognize)?;
674
675        // Optional per-field state-key override.
676        let mut state_key: Option<String> = None;
677        for attr in &field.attrs {
678            if attr.path().is_ident("extract") {
679                attr.parse_nested_meta(|meta| {
680                    if meta.path.is_ident("state") {
681                        let v: LitStr = meta.value()?.parse()?;
682                        state_key = Some(v.value());
683                    } else {
684                        return Err(meta.error("unknown field `extract` option (expected `state`)"));
685                    }
686                    Ok(())
687                })?;
688            }
689        }
690
691        field_calls.push(match state_key {
692            Some(sk) => quote! { .field_to(#fname, #sk, #recognizer) },
693            None => quote! { .field(#fname, #recognizer) },
694        });
695    }
696
697    let doc = format!("The `Extract` record derived from `{ident}`'s `#[recognize(..)]` fields.");
698    Ok(quote! {
699        impl #ident {
700            #[doc = #doc]
701            pub fn extract() -> #rt::extract::Extract {
702                #rt::extract::Extract::record(#name)
703                    #(#field_calls)*
704                    .window(#window)
705                    .build()
706            }
707
708            #[allow(dead_code, reason = "generated helper that only reads the fields so rustc counts them as used")]
709            #[doc(hidden)]
710            fn __extract_mark_fields_used(&self) {
711                #( let _ = &self.#all_field_idents; )*
712            }
713        }
714    })
715}
716
717/// Derive a [`Frame`] impl from a struct's `#[slot(..)]` fields.
718///
719/// Every named field becomes a slot (state key = field name unless overridden).
720/// The generated `fn frame() -> FrameSpec` carries each slot's prompt, reprompt,
721/// confirmation policy, and PII flag — the metadata the conversation compiler and
722/// repair use.
723///
724/// ```ignore
725/// #[derive(Frame)]
726/// #[frame(name = "booking")]
727/// struct Booking {
728///     #[slot(prompt = "For how many people?", confirm = "low_confidence")]
729///     party_size: u8,
730///     #[slot(prompt = "Name?", pii)]
731///     name: String,
732/// }
733/// ```
734///
735/// Field `#[slot(..)]` options: `prompt`, `reprompt`, `confirm`
736/// (`never`/`low_confidence`/`always`), `state` (key override), `pii` (flag).
737/// Container `#[frame(name = "...")]` sets the frame name.
738#[proc_macro_derive(Frame, attributes(slot, frame, recognize))]
739pub fn derive_frame(item: TokenStream) -> TokenStream {
740    let input = parse_macro_input!(item as DeriveInput);
741    match expand_frame(input) {
742        Ok(ts) => ts.into(),
743        Err(e) => e.to_compile_error().into(),
744    }
745}
746
747fn expand_frame(input: DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
748    let (rt, _) = runtime();
749    let ident = &input.ident;
750
751    let fields = match &input.data {
752        Data::Struct(s) => match &s.fields {
753            Fields::Named(named) => &named.named,
754            _ => {
755                return Err(syn::Error::new_spanned(
756                    ident,
757                    "#[derive(Frame)] requires a struct with named fields",
758                ));
759            }
760        },
761        _ => {
762            return Err(syn::Error::new_spanned(
763                ident,
764                "#[derive(Frame)] can only be applied to structs",
765            ));
766        }
767    };
768
769    // Container `#[frame(name = "...")]`.
770    let mut name = to_snake_case(&ident.to_string());
771    for attr in &input.attrs {
772        if attr.path().is_ident("frame") {
773            attr.parse_nested_meta(|meta| {
774                if meta.path.is_ident("name") {
775                    let v: LitStr = meta.value()?.parse()?;
776                    name = v.value();
777                    Ok(())
778                } else {
779                    Err(meta.error("unknown `frame` option (expected `name`)"))
780                }
781            })?;
782        }
783    }
784
785    let all_field_idents: Vec<_> = fields.iter().filter_map(|f| f.ident.clone()).collect();
786
787    let mut slot_exprs = Vec::new();
788    for field in fields {
789        let fname = field
790            .ident
791            .as_ref()
792            .ok_or_else(|| syn::Error::new_spanned(field, "expected a named field"))?
793            .to_string();
794        let mut state_key = fname.clone();
795        let mut prompt: Option<String> = None;
796        let mut reprompt: Option<String> = None;
797        let mut confirm = quote! { #rt::frame::ConfirmPolicy::Never };
798        let mut pii = false;
799        let mut min: Option<f64> = None;
800        let mut max: Option<f64> = None;
801        let mut non_empty = false;
802
803        // Optional `#[recognize(..)]` (same vocabulary as `#[derive(Extract)]`).
804        let recognizer = match field.attrs.iter().find(|a| a.path().is_ident("recognize")) {
805            Some(attr) => {
806                let r = slot_recognizer_expr(attr)?;
807                quote! { Some(#r) }
808            }
809            None => quote! { None },
810        };
811
812        for attr in &field.attrs {
813            if !attr.path().is_ident("slot") {
814                continue;
815            }
816            attr.parse_nested_meta(|meta| {
817                if meta.path.is_ident("prompt") {
818                    let v: LitStr = meta.value()?.parse()?;
819                    prompt = Some(v.value());
820                } else if meta.path.is_ident("reprompt") {
821                    let v: LitStr = meta.value()?.parse()?;
822                    reprompt = Some(v.value());
823                } else if meta.path.is_ident("state") {
824                    let v: LitStr = meta.value()?.parse()?;
825                    state_key = v.value();
826                } else if meta.path.is_ident("confirm") {
827                    let v: LitStr = meta.value()?.parse()?;
828                    confirm = match v.value().as_str() {
829                        "never" => quote! { #rt::frame::ConfirmPolicy::Never },
830                        "low_confidence" => {
831                            quote! { #rt::frame::ConfirmPolicy::LowConfidence }
832                        }
833                        "always" => quote! { #rt::frame::ConfirmPolicy::Always },
834                        other => {
835                            return Err(meta.error(format!(
836                                "unknown confirm policy '{other}' (expected never/low_confidence/always)"
837                            )))
838                        }
839                    };
840                } else if meta.path.is_ident("pii") {
841                    pii = true;
842                } else if meta.path.is_ident("min") {
843                    min = Some(lit_to_f64(&meta.value()?.parse()?)?);
844                } else if meta.path.is_ident("max") {
845                    max = Some(lit_to_f64(&meta.value()?.parse()?)?);
846                } else if meta.path.is_ident("non_empty") {
847                    non_empty = true;
848                } else {
849                    return Err(meta.error(
850                        "unknown `slot` option (expected prompt/reprompt/state/confirm/pii/min/max/non_empty)",
851                    ));
852                }
853                Ok(())
854            })?;
855        }
856
857        // Lower min/max/non_empty into a serializable SlotValidator.
858        let validate = if min.is_some() || max.is_some() {
859            let min_tok = match min {
860                Some(v) => quote! { Some(#v) },
861                None => quote! { None },
862            };
863            let max_tok = match max {
864                Some(v) => quote! { Some(#v) },
865                None => quote! { None },
866            };
867            quote! { Some(#rt::frame::SlotValidator::Range { min: #min_tok, max: #max_tok }) }
868        } else if non_empty {
869            quote! { Some(#rt::frame::SlotValidator::NonEmpty) }
870        } else {
871            quote! { None }
872        };
873
874        let prompt_tok = match prompt {
875            Some(p) => quote! { Some(#p.to_string()) },
876            None => quote! { None },
877        };
878        let reprompt_tok = match reprompt {
879            Some(p) => quote! { Some(#p.to_string()) },
880            None => quote! { None },
881        };
882        slot_exprs.push(quote! {
883            #rt::frame::SlotSpec {
884                name: #fname.to_string(),
885                state_key: #state_key.to_string(),
886                prompt: #prompt_tok,
887                reprompt: #reprompt_tok,
888                confirm: #confirm,
889                pii: #pii,
890                recognizer: #recognizer,
891                validate: #validate,
892            }
893        });
894    }
895
896    let doc = format!("The `FrameSpec` derived from `{ident}`'s `#[slot(..)]` fields.");
897    Ok(quote! {
898        impl #rt::frame::Frame for #ident {
899            #[doc = #doc]
900            fn frame() -> #rt::frame::FrameSpec {
901                #rt::frame::FrameSpec {
902                    name: #name.to_string(),
903                    slots: ::std::vec![ #(#slot_exprs),* ],
904                }
905            }
906        }
907
908        impl #ident {
909            #[allow(dead_code, reason = "generated helper that only reads the fields so rustc counts them as used")]
910            #[doc(hidden)]
911            fn __frame_mark_fields_used(&self) {
912                #( let _ = &self.#all_field_idents; )*
913            }
914        }
915    })
916}
917
918/// Build the `Recognizer::..` expression for a single `#[recognize(..)]` attr.
919fn recognizer_expr(attr: &syn::Attribute) -> syn::Result<proc_macro2::TokenStream> {
920    let (rt, _) = runtime();
921    let r = quote! { #rt::extract::Recognizer };
922    let meta: Meta = attr.parse_args()?;
923    match meta {
924        Meta::Path(p) => {
925            let id = p
926                .get_ident()
927                .ok_or_else(|| syn::Error::new_spanned(&p, "expected a recognizer name"))?;
928            match id.to_string().as_str() {
929                "integer" => Ok(quote! { #r::integer() }),
930                "money" => Ok(quote! { #r::money() }),
931                "yes_no" => Ok(quote! { #r::yes_no() }),
932                "datetime" => Ok(quote! { #r::datetime() }),
933                other => Err(syn::Error::new_spanned(
934                    &p,
935                    format!("unknown recognizer `{other}`"),
936                )),
937            }
938        }
939        Meta::NameValue(nv) => {
940            let id = nv
941                .path
942                .get_ident()
943                .ok_or_else(|| syn::Error::new_spanned(&nv.path, "expected a recognizer name"))?;
944            match id.to_string().as_str() {
945                "integer_near" => {
946                    let a = str_array(&nv.value)?;
947                    Ok(quote! { #r::integer_near([ #(#a),* ]) })
948                }
949                "one_of" => {
950                    let a = str_array(&nv.value)?;
951                    Ok(quote! { #r::one_of([ #(#a),* ]) })
952                }
953                "fuzzy" => {
954                    let a = str_array(&nv.value)?;
955                    Ok(quote! { #r::fuzzy([ #(#a),* ]) })
956                }
957                "regex" => {
958                    let s = str_lit(&nv.value)?;
959                    Ok(quote! { #r::regex(#s) })
960                }
961                other => Err(syn::Error::new_spanned(
962                    &nv.path,
963                    format!("`{other}` does not take a value"),
964                )),
965            }
966        }
967        Meta::List(l) => Err(syn::Error::new_spanned(
968            l,
969            "unexpected nested list in `#[recognize(..)]`",
970        )),
971    }
972}
973
974/// Build a serializable `SlotRecognizer` expression for a `#[recognize(..)]` attr
975/// on a `#[derive(Frame)]` field (same vocabulary as the Extract derive).
976fn slot_recognizer_expr(attr: &syn::Attribute) -> syn::Result<proc_macro2::TokenStream> {
977    let (rt, _) = runtime();
978    let r = quote! { #rt::frame::SlotRecognizer };
979    let meta: Meta = attr.parse_args()?;
980    match meta {
981        Meta::Path(p) => {
982            let id = p
983                .get_ident()
984                .ok_or_else(|| syn::Error::new_spanned(&p, "expected a recognizer name"))?;
985            match id.to_string().as_str() {
986                "integer" => Ok(quote! { #r::Integer }),
987                "money" => Ok(quote! { #r::Money }),
988                "yes_no" => Ok(quote! { #r::YesNo }),
989                "datetime" => Ok(quote! { #r::DateTime }),
990                other => Err(syn::Error::new_spanned(
991                    &p,
992                    format!("unknown recognizer `{other}`"),
993                )),
994            }
995        }
996        Meta::NameValue(nv) => {
997            let id = nv
998                .path
999                .get_ident()
1000                .ok_or_else(|| syn::Error::new_spanned(&nv.path, "expected a recognizer name"))?;
1001            match id.to_string().as_str() {
1002                "integer_near" => {
1003                    let a = str_array(&nv.value)?;
1004                    Ok(quote! { #r::IntegerNear(::std::vec![ #(#a.to_string()),* ]) })
1005                }
1006                "one_of" => {
1007                    let a = str_array(&nv.value)?;
1008                    Ok(quote! { #r::OneOf(::std::vec![ #(#a.to_string()),* ]) })
1009                }
1010                "fuzzy" => {
1011                    let a = str_array(&nv.value)?;
1012                    Ok(quote! { #r::Fuzzy(::std::vec![ #(#a.to_string()),* ]) })
1013                }
1014                "regex" => {
1015                    let s = str_lit(&nv.value)?;
1016                    Ok(quote! { #r::Regex(#s.to_string()) })
1017                }
1018                other => Err(syn::Error::new_spanned(
1019                    &nv.path,
1020                    format!("`{other}` does not take a value"),
1021                )),
1022            }
1023        }
1024        Meta::List(l) => Err(syn::Error::new_spanned(
1025            l,
1026            "unexpected nested list in `#[recognize(..)]`",
1027        )),
1028    }
1029}
1030
1031/// Parse an integer or float literal into an `f64` (for slot `min`/`max`).
1032fn lit_to_f64(lit: &Lit) -> syn::Result<f64> {
1033    match lit {
1034        Lit::Int(i) => i.base10_parse::<f64>(),
1035        Lit::Float(f) => f.base10_parse::<f64>(),
1036        other => Err(syn::Error::new_spanned(
1037            other,
1038            "expected a numeric literal for `min`/`max`",
1039        )),
1040    }
1041}
1042
1043/// Parse an expression that must be an array of string literals.
1044fn str_array(expr: &Expr) -> syn::Result<Vec<LitStr>> {
1045    match expr {
1046        Expr::Array(arr) => arr
1047            .elems
1048            .iter()
1049            .map(|e| match e {
1050                Expr::Lit(ExprLit {
1051                    lit: Lit::Str(s), ..
1052                }) => Ok(s.clone()),
1053                other => Err(syn::Error::new_spanned(
1054                    other,
1055                    "expected a string literal in the array",
1056                )),
1057            })
1058            .collect(),
1059        other => Err(syn::Error::new_spanned(
1060            other,
1061            "expected an array of string literals, e.g. [\"a\", \"b\"]",
1062        )),
1063    }
1064}
1065
1066/// Parse an expression that must be a single string literal.
1067fn str_lit(expr: &Expr) -> syn::Result<LitStr> {
1068    match expr {
1069        Expr::Lit(ExprLit {
1070            lit: Lit::Str(s), ..
1071        }) => Ok(s.clone()),
1072        other => Err(syn::Error::new_spanned(other, "expected a string literal")),
1073    }
1074}
1075
1076/// Convert a `PascalCase`/`camelCase` identifier to `snake_case`.
1077fn to_snake_case(s: &str) -> String {
1078    let mut out = String::with_capacity(s.len() + 4);
1079    for (i, ch) in s.chars().enumerate() {
1080        if ch.is_uppercase() {
1081            if i != 0 {
1082                out.push('_');
1083            }
1084            out.extend(ch.to_lowercase());
1085        } else {
1086            out.push(ch);
1087        }
1088    }
1089    out
1090}
1091
1092/// Returns `true` if `ty` is syntactically an `Option<...>`.
1093///
1094/// Accepts the prelude name (`Option`) and the spelled-out std/core paths
1095/// (`option::Option`, `std::option::Option`, `core::option::Option`, with or
1096/// without a leading `::`). The full path is checked — a user type like
1097/// `my::Option` does NOT match. Purely syntactic: a type alias or renamed
1098/// import of `Option` is invisible to the macro, as with any derive.
1099fn is_option(ty: &Type) -> bool {
1100    let Type::Path(TypePath { qself: None, path }) = ty else {
1101        return false;
1102    };
1103    // Only the final `Option` segment may carry generic arguments.
1104    if path
1105        .segments
1106        .iter()
1107        .rev()
1108        .skip(1)
1109        .any(|seg| !seg.arguments.is_none())
1110    {
1111        return false;
1112    }
1113    let idents: Vec<&syn::Ident> = path.segments.iter().map(|seg| &seg.ident).collect();
1114    match idents.as_slice() {
1115        // `Option<T>` / `option::Option<T>` resolve via the prelude only when
1116        // the path is relative.
1117        [opt] => path.leading_colon.is_none() && *opt == "Option",
1118        [module, opt] => path.leading_colon.is_none() && *module == "option" && *opt == "Option",
1119        // `std::option::Option<T>` / `core::option::Option<T>`, `::`-rooted or not.
1120        [root, module, opt] => {
1121            (*root == "std" || *root == "core") && *module == "option" && *opt == "Option"
1122        }
1123        _ => false,
1124    }
1125}
1126
1127/// Convert a `snake_case` identifier to `PascalCase`.
1128fn to_pascal_case(s: &str) -> String {
1129    let mut out = String::with_capacity(s.len());
1130    let mut upper_next = true;
1131    for ch in s.chars() {
1132        if ch == '_' {
1133            upper_next = true;
1134        } else if upper_next {
1135            out.extend(ch.to_uppercase());
1136            upper_next = false;
1137        } else {
1138            out.push(ch);
1139        }
1140    }
1141    out
1142}
1143
1144#[cfg(test)]
1145mod tests {
1146    use super::{ToolDocs, is_option, is_result, parse_docs};
1147    use syn::parse_quote;
1148
1149    fn docs(text: &str) -> ToolDocs {
1150        let lines: Vec<String> = text.lines().map(|l| format!(" {l}")).collect();
1151        parse_docs(&lines)
1152    }
1153
1154    #[test]
1155    fn description_is_the_prose_before_the_first_heading() {
1156        let parsed =
1157            docs("Get the weather\nfor a city.\n\nUses the cached forecast.\n\n# Errors\n\nNever.");
1158        assert_eq!(
1159            parsed.description,
1160            "Get the weather for a city.\n\nUses the cached forecast."
1161        );
1162        assert!(parsed.arguments.is_empty());
1163    }
1164
1165    #[test]
1166    fn arguments_accept_the_common_rustdoc_forms() {
1167        let parsed = docs(
1168            "Look up.\n\n# Arguments\n\n\
1169             * `city` - The city,\n  e.g. Paris.\n\
1170             - `units`: metric or imperial.\n\
1171             * days \u{2014} how far ahead.\n\n# Examples\n\n* `ignored` - not an argument",
1172        );
1173        assert_eq!(parsed.description, "Look up.");
1174        assert_eq!(
1175            parsed.arguments,
1176            vec![
1177                ("city".to_string(), "The city, e.g. Paris.".to_string()),
1178                ("units".to_string(), "metric or imperial.".to_string()),
1179                ("days".to_string(), "how far ahead.".to_string()),
1180            ]
1181        );
1182    }
1183
1184    #[test]
1185    fn code_blocks_are_neither_description_nor_headings() {
1186        let parsed = docs("Add two numbers.\n```\n# let x = 1;\nadd(1, 2);\n```\nThen return.");
1187        assert_eq!(parsed.description, "Add two numbers. Then return.");
1188    }
1189
1190    #[test]
1191    fn is_result_matches_any_path_ending_in_result() {
1192        assert!(is_result(&parse_quote!(Result<Value, ToolError>)));
1193        assert!(is_result(&parse_quote!(anyhow::Result<u32>)));
1194        assert!(is_result(&parse_quote!(std::io::Result<()>)));
1195        assert!(!is_result(&parse_quote!(SearchResult)));
1196        assert!(!is_result(&parse_quote!(Vec<Result<u8, String>>)));
1197    }
1198
1199    #[test]
1200    fn is_option_accepts_std_core_paths() {
1201        assert!(is_option(&parse_quote!(Option<String>)));
1202        assert!(is_option(&parse_quote!(option::Option<String>)));
1203        assert!(is_option(&parse_quote!(std::option::Option<String>)));
1204        assert!(is_option(&parse_quote!(core::option::Option<String>)));
1205        assert!(is_option(&parse_quote!(::std::option::Option<String>)));
1206        assert!(is_option(&parse_quote!(::core::option::Option<String>)));
1207    }
1208
1209    #[test]
1210    fn is_option_rejects_lookalikes() {
1211        assert!(!is_option(&parse_quote!(String)));
1212        assert!(!is_option(&parse_quote!(Vec<Option<String>>)));
1213        assert!(!is_option(&parse_quote!(my::Option<String>)));
1214        assert!(!is_option(&parse_quote!(my::option::Option<String>)));
1215        assert!(!is_option(&parse_quote!(::option::Option<String>)));
1216        assert!(!is_option(&parse_quote!(<T as Trait>::Option)));
1217    }
1218}