1#![cfg_attr(docsrs, feature(doc_cfg))]
2#![forbid(unsafe_code)]
3#![warn(missing_docs)]
4use 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
41fn 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 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#[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#[derive(Debug, Default, PartialEq)]
170struct ToolDocs {
171 description: String,
173 arguments: Vec<(String, String)>,
175}
176
177fn 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
195fn 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 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 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
258fn 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 ("ed[..end], "ed[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
280fn 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 let mut field_idents = Vec::new();
332 let mut field_types = Vec::new();
333 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 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 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 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 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 let inner_fn = format_ident!("__{}_impl", fn_name);
435
436 let fn_name_str = fn_name.to_string();
437
438 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 let default = is_option(ty).then(|| quote! { #[serde(default)] });
454 quote! {
455 #doc
456 #default
457 #ident: #ty
458 }
459 });
460
461 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 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 #(#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 #(#cfg_attrs)*
490 #(#body_attrs)*
491 #[allow(non_snake_case)]
492 async fn #inner_fn ( #(#param_idents : #param_types),* ) -> #return_type #body
493
494 #(#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 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 #(#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#[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 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 let all_field_idents: Vec<_> = fields.iter().filter_map(|f| f.ident.clone()).collect();
661
662 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 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#[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 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 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 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
918fn 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
974fn 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
1031fn 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
1043fn 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
1066fn 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
1076fn 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
1092fn is_option(ty: &Type) -> bool {
1100 let Type::Path(TypePath { qself: None, path }) = ty else {
1101 return false;
1102 };
1103 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 [opt] => path.leading_colon.is_none() && *opt == "Option",
1118 [module, opt] => path.leading_colon.is_none() && *module == "option" && *opt == "Option",
1119 [root, module, opt] => {
1121 (*root == "std" || *root == "core") && *module == "option" && *opt == "Option"
1122 }
1123 _ => false,
1124 }
1125}
1126
1127fn 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}