Skip to main content

daimon_macros/
lib.rs

1//! Proc macros for the Daimon AI agent framework.
2//!
3//! Provides `#[tool_fn]` to derive [`Tool`](https://docs.rs/daimon/latest/daimon/tool/trait.Tool.html)
4//! implementations from plain async functions.
5
6use proc_macro::TokenStream;
7use proc_macro2::TokenStream as TokenStream2;
8use quote::{format_ident, quote};
9use syn::{
10    Attribute, Expr, FnArg, Ident, ItemFn, Lit, Meta, Pat, PatType, Token, Type,
11    parse::{Parse, ParseStream},
12    parse_macro_input,
13};
14
15struct ToolFnArgs {
16    crate_path: Option<syn::Path>,
17    name_override: Option<String>,
18    description_override: Option<String>,
19}
20
21impl Parse for ToolFnArgs {
22    fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
23        let mut crate_path = None;
24        let mut name_override = None;
25        let mut description_override = None;
26
27        while !input.is_empty() {
28            let key: Ident = input.parse()?;
29            input.parse::<Token![=]>()?;
30
31            match key.to_string().as_str() {
32                "crate_path" => {
33                    let lit: Lit = input.parse()?;
34                    if let Lit::Str(s) = lit {
35                        crate_path = Some(s.parse()?);
36                    }
37                }
38                "name" => {
39                    let lit: Lit = input.parse()?;
40                    if let Lit::Str(s) = lit {
41                        name_override = Some(s.value());
42                    }
43                }
44                "description" => {
45                    let lit: Lit = input.parse()?;
46                    if let Lit::Str(s) = lit {
47                        description_override = Some(s.value());
48                    }
49                }
50                other => {
51                    return Err(syn::Error::new(
52                        key.span(),
53                        format!("unknown attribute `{other}`"),
54                    ));
55                }
56            }
57
58            if !input.is_empty() {
59                input.parse::<Token![,]>()?;
60            }
61        }
62
63        Ok(Self {
64            crate_path,
65            name_override,
66            description_override,
67        })
68    }
69}
70
71struct ParamInfo {
72    name: String,
73    ty: Type,
74    doc: Option<String>,
75    optional: bool,
76    inner_ty: Option<Type>,
77}
78
79/// Derives a [`Tool`] implementation from an async function.
80///
81/// The function's parameters become the tool's JSON Schema properties.
82/// Doc comments on the function become the tool description; doc comments
83/// on individual parameters become property descriptions.
84///
85/// # Supported types
86///
87/// `String`, `i8`–`i128`, `u8`–`u128`, `isize`, `usize`, `f32`, `f64`,
88/// `bool`, `Option<T>` (marks the parameter as not required).
89///
90/// # Attributes
91///
92/// - `name = "..."` — override the tool name (defaults to the function name)
93/// - `description = "..."` — override the description (defaults to doc comments)
94/// - `crate_path = "..."` — override the path to the daimon crate (defaults to `::daimon`)
95///
96/// # Example
97///
98/// ```ignore
99/// use daimon::prelude::*;
100/// use daimon::tool_fn;
101///
102/// /// Adds two numbers together.
103/// #[tool_fn]
104/// async fn add(
105///     /// The first number.
106///     a: f64,
107///     /// The second number.
108///     b: f64,
109/// ) -> daimon::Result<ToolOutput> {
110///     Ok(ToolOutput::text(format!("{}", a + b)))
111/// }
112///
113/// // Use the generated struct:
114/// let agent = Agent::builder()
115///     .model(model)
116///     .tool(Add) // PascalCase struct generated from `add`
117///     .build()?;
118/// ```
119#[proc_macro_attribute]
120pub fn tool_fn(attr: TokenStream, item: TokenStream) -> TokenStream {
121    let args = parse_macro_input!(attr as ToolFnArgs);
122    let func = parse_macro_input!(item as ItemFn);
123
124    match expand_tool_fn(args, func) {
125        Ok(tokens) => tokens.into(),
126        Err(e) => e.to_compile_error().into(),
127    }
128}
129
130fn expand_tool_fn(args: ToolFnArgs, func: ItemFn) -> syn::Result<TokenStream2> {
131    let crate_path = args
132        .crate_path
133        .map(|p| quote!(#p))
134        .unwrap_or_else(|| quote!(::daimon));
135
136    let fn_name = &func.sig.ident;
137    let struct_name = format_ident!("{}", to_pascal_case(&fn_name.to_string()));
138    let tool_name_str = args.name_override.unwrap_or_else(|| fn_name.to_string());
139
140    let description = args
141        .description_override
142        .unwrap_or_else(|| extract_doc_comments(&func.attrs));
143
144    if func.sig.asyncness.is_none() {
145        return Err(syn::Error::new_spanned(
146            func.sig.fn_token,
147            "tool_fn requires an async function",
148        ));
149    }
150
151    let params = extract_params(&func)?;
152    let schema_tokens = generate_schema(&params, &crate_path);
153    let extraction_tokens = generate_extraction(&params, &crate_path);
154    let body = &func.block;
155
156    Ok(quote! {
157        /// Auto-generated tool struct from `#[tool_fn]` on [`#fn_name`].
158        pub struct #struct_name;
159
160        impl #crate_path::tool::Tool for #struct_name {
161            fn name(&self) -> &str {
162                #tool_name_str
163            }
164
165            fn description(&self) -> &str {
166                #description
167            }
168
169            fn parameters_schema(&self) -> ::serde_json::Value {
170                #schema_tokens
171            }
172
173            async fn execute(
174                &self,
175                __daimon_input: &::serde_json::Value,
176            ) -> #crate_path::Result<#crate_path::tool::ToolOutput> {
177                #extraction_tokens
178                #body
179            }
180        }
181    })
182}
183
184fn extract_doc_comments(attrs: &[Attribute]) -> String {
185    let mut lines = Vec::new();
186    for attr in attrs {
187        if attr.path().is_ident("doc")
188            && let Meta::NameValue(nv) = &attr.meta
189            && let Expr::Lit(lit) = &nv.value
190            && let Lit::Str(s) = &lit.lit
191        {
192            lines.push(s.value().trim().to_string());
193        }
194    }
195    lines.join(" ").trim().to_string()
196}
197
198fn extract_params(func: &ItemFn) -> syn::Result<Vec<ParamInfo>> {
199    let mut params = Vec::new();
200
201    for arg in &func.sig.inputs {
202        if let FnArg::Typed(PatType { pat, ty, attrs, .. }) = arg {
203            let name = match pat.as_ref() {
204                Pat::Ident(ident) => ident.ident.to_string(),
205                _ => {
206                    return Err(syn::Error::new_spanned(pat, "expected a simple identifier"));
207                }
208            };
209
210            let doc = extract_doc_comments(attrs);
211            let doc = if doc.is_empty() { None } else { Some(doc) };
212
213            let (optional, inner_ty) = unwrap_option(ty);
214
215            params.push(ParamInfo {
216                name,
217                ty: *ty.clone(),
218                doc,
219                optional,
220                inner_ty,
221            });
222        }
223    }
224
225    Ok(params)
226}
227
228fn unwrap_option(ty: &Type) -> (bool, Option<Type>) {
229    if let Type::Path(tp) = ty
230        && let Some(seg) = tp.path.segments.last()
231        && seg.ident == "Option"
232        && let syn::PathArguments::AngleBracketed(ab) = &seg.arguments
233        && let Some(syn::GenericArgument::Type(inner)) = ab.args.first()
234    {
235        return (true, Some(inner.clone()));
236    }
237    (false, None)
238}
239
240fn type_to_json_schema(ty: &Type) -> TokenStream2 {
241    if let Type::Path(tp) = ty
242        && let Some(seg) = tp.path.segments.last()
243    {
244        let name = seg.ident.to_string();
245        match name.as_str() {
246            "String" | "str" => return quote!(::serde_json::json!({"type": "string"})),
247            "bool" => return quote!(::serde_json::json!({"type": "boolean"})),
248            "f32" | "f64" => return quote!(::serde_json::json!({"type": "number"})),
249            "i8" | "i16" | "i32" | "i64" | "i128" | "isize" | "u8" | "u16" | "u32" | "u64"
250            | "u128" | "usize" => {
251                return quote!(::serde_json::json!({"type": "integer"}));
252            }
253            "Vec" => {
254                if let syn::PathArguments::AngleBracketed(ab) = &seg.arguments
255                    && let Some(syn::GenericArgument::Type(inner)) = ab.args.first()
256                {
257                    let inner_schema = type_to_json_schema(inner);
258                    return quote!(::serde_json::json!({"type": "array", "items": #inner_schema}));
259                }
260                return quote!(::serde_json::json!({"type": "array"}));
261            }
262            "Value" => return quote!(::serde_json::json!({})),
263            _ => {}
264        }
265    }
266    quote!(::serde_json::json!({}))
267}
268
269fn generate_schema(params: &[ParamInfo], _crate_path: &TokenStream2) -> TokenStream2 {
270    let mut prop_entries = Vec::new();
271    let mut required_names = Vec::new();
272
273    for param in params {
274        let name = &param.name;
275        let effective_ty = param.inner_ty.as_ref().unwrap_or(&param.ty);
276        let schema = type_to_json_schema(effective_ty);
277
278        if let Some(doc) = &param.doc {
279            prop_entries.push(quote! {
280                let mut __prop = #schema;
281                if let Some(obj) = __prop.as_object_mut() {
282                    obj.insert("description".to_string(), ::serde_json::Value::String(#doc.to_string()));
283                }
284                __props.insert(#name.to_string(), __prop);
285            });
286        } else {
287            prop_entries.push(quote! {
288                __props.insert(#name.to_string(), #schema);
289            });
290        }
291
292        if !param.optional {
293            required_names.push(quote!(#name));
294        }
295    }
296
297    quote! {
298        {
299            let mut __props = ::serde_json::Map::new();
300            #(#prop_entries)*
301            let mut __schema = ::serde_json::Map::new();
302            __schema.insert("type".to_string(), ::serde_json::Value::String("object".to_string()));
303            __schema.insert("properties".to_string(), ::serde_json::Value::Object(__props));
304            let __required: Vec<&str> = vec![#(#required_names),*];
305            if !__required.is_empty() {
306                __schema.insert(
307                    "required".to_string(),
308                    ::serde_json::Value::Array(
309                        __required.into_iter().map(|s| ::serde_json::Value::String(s.to_string())).collect()
310                    ),
311                );
312            }
313            ::serde_json::Value::Object(__schema)
314        }
315    }
316}
317
318fn generate_extraction(params: &[ParamInfo], crate_path: &TokenStream2) -> TokenStream2 {
319    let mut extractions = Vec::new();
320
321    for param in params {
322        let name_str = &param.name;
323        let name_ident = format_ident!("{}", &param.name);
324        let ty = &param.ty;
325
326        if param.optional {
327            let inner = param.inner_ty.as_ref().unwrap_or(&param.ty);
328            extractions.push(quote! {
329                let #name_ident: #ty = match __daimon_input.get(#name_str) {
330                    Some(v) if !v.is_null() => {
331                        Some(::serde_json::from_value::<#inner>(v.clone()).map_err(|__e| {
332                            #crate_path::DaimonError::Other(
333                                format!("parameter '{}': {}", #name_str, __e)
334                            )
335                        })?)
336                    }
337                    _ => None,
338                };
339            });
340        } else {
341            extractions.push(quote! {
342                let #name_ident: #ty = ::serde_json::from_value(
343                    __daimon_input
344                        .get(#name_str)
345                        .cloned()
346                        .unwrap_or(::serde_json::Value::Null),
347                )
348                .map_err(|__e| {
349                    #crate_path::DaimonError::Other(
350                        format!("parameter '{}': {}", #name_str, __e)
351                    )
352                })?;
353            });
354        }
355    }
356
357    quote! { #(#extractions)* }
358}
359
360fn to_pascal_case(s: &str) -> String {
361    s.split('_')
362        .filter(|part| !part.is_empty())
363        .map(|part| {
364            let mut chars = part.chars();
365            match chars.next() {
366                Some(c) => c.to_uppercase().to_string() + &chars.as_str().to_lowercase(),
367                None => String::new(),
368            }
369        })
370        .collect()
371}
372
373#[cfg(test)]
374mod tests {
375    use super::*;
376
377    #[test]
378    fn test_to_pascal_case() {
379        assert_eq!(to_pascal_case("add"), "Add");
380        assert_eq!(to_pascal_case("fetch_weather"), "FetchWeather");
381        assert_eq!(to_pascal_case("get_user_by_id"), "GetUserById");
382        assert_eq!(to_pascal_case("a"), "A");
383    }
384}