ai_agent_macro/lib.rs
1extern crate proc_macro;
2
3use proc_macro::TokenStream;
4use quote::quote;
5use syn::{parse_macro_input, Data, DeriveInput, Fields};
6
7// #[proc_macro_derive(KeywordString)]
8// pub fn print_keyword_derive(input: TokenStream) -> TokenStream {
9// let input = parse_macro_input!(input as DeriveInput);
10//
11// let struct_name = &input.ident; // The name of the struct
12//
13// // Constructing the display implementation
14// let output = quote! {
15// impl ToKeywordString for #struct_name {
16// fn to_keyword_string() -> String {
17// let test_struct = #struct_name::default();
18// let result = serde_json::to_string(&test_struct).unwrap();
19// result
20// .replace("\"", "")
21// .replace("0", "")
22// .replace(".", "")
23// .replace(":", "")
24// .replace(",", ", ")
25// // format!("{}{{{}}}", stringify!(#struct_name), field_names.join(", "))
26// }
27// }
28// };
29//
30// TokenStream::from(output)
31// }
32//
33#[proc_macro_derive(KeywordString)]
34pub fn print_keyword_derive(input: TokenStream) -> TokenStream {
35 let input = parse_macro_input!(input as DeriveInput);
36
37 let struct_name = &input.ident; // The name of the struct
38
39 // Process fields to generate a list of field names
40 let fields_tokens = if let Data::Struct(data) = input.data {
41 match data.fields {
42 Fields::Named(fields) => fields
43 .named
44 .into_iter()
45 .map(|f| {
46 let field_name = f.ident.expect("Expected named field").to_string();
47 quote! { format!("{}",#field_name)}
48 // quote! { format!("{}: {{}}", stringify!(#field_name), <_ as ToKeywordString>::to_keyword_string()) }
49 })
50 .collect::<Vec<_>>(),
51 _ => panic!("KeywordString only supports structs with named fields"),
52 }
53 } else {
54 panic!("KeywordString can only be applied to structs");
55 };
56
57 // Constructing the display implementation
58 let output = quote! {
59 impl ToKeywordString for #struct_name {
60 fn to_keyword_string() -> String {
61 let field_names = vec![#(#fields_tokens),*];
62 format!("{{{}}}", field_names.join(", "))
63 // format!("{}{{{}}}", stringify!(#struct_name), field_names.join(", "))
64 }
65 }
66 };
67
68 TokenStream::from(output)
69}