1use proc_macro::TokenStream;
2use quote::quote;
3use syn::{
4 Attribute, Data, DeriveInput, Fields, FnArg, ItemFn, Lit, Meta, Pat, Type, parse_macro_input,
5};
6
7#[proc_macro_attribute]
26pub fn gemini_function(_attr: TokenStream, item: TokenStream) -> TokenStream {
27 let mut input_fn = parse_macro_input!(item as ItemFn);
28 let fn_name = &input_fn.sig.ident;
29 let fn_description = extract_doc_comments(&input_fn.attrs);
30
31 let mut properties = Vec::new();
32 let mut required = Vec::new();
33 let mut param_names = Vec::new();
34 let mut param_types = Vec::new();
35
36 for arg in input_fn.sig.inputs.iter_mut() {
37 if let FnArg::Typed(pat_type) = arg {
38 if let Pat::Ident(pat_ident) = &*pat_type.pat {
39 let param_name = pat_ident.ident.clone();
40 let param_name_str = param_name.to_string();
41 let param_type = (*pat_type.ty).clone();
42 let param_desc = extract_doc_comments(&pat_type.attrs);
43
44 if has_reference(¶m_type) {
45 return syn::Error::new_spanned(
46 ¶m_type,
47 "references are not supported in gemini_function. Use owned types like String instead.",
48 )
49 .to_compile_error()
50 .into();
51 }
52
53 pat_type.attrs.retain(|attr| !attr.path().is_ident("doc"));
55
56 let is_optional = is_option(¶m_type);
57
58 properties.push(quote! {
59 let mut schema = <#param_type as GeminiSchema>::gemini_schema();
60 if !#param_desc.is_empty() {
61 if let Some(obj) = schema.as_object_mut() {
62 obj.insert("description".to_string(), serde_json::json!(#param_desc));
63 }
64 }
65 props.insert(#param_name_str.to_string(), schema);
66 });
67
68 if !is_optional {
69 required.push(param_name_str);
70 }
71
72 param_names.push(param_name);
73 param_types.push(param_type);
74 }
75 }
76 }
77
78 let fn_name_str = fn_name.to_string();
79 let is_async = input_fn.sig.asyncness.is_some();
80 let call_await = if is_async {
81 quote! { .await }
82 } else {
83 quote! {}
84 };
85
86 let is_result = match &input_fn.sig.output {
87 syn::ReturnType::Default => false,
88 syn::ReturnType::Type(_, ty) => {
89 let s = quote!(#ty).to_string();
90 s.contains("Result")
91 }
92 };
93
94 let result_handling = if is_result {
95 quote! {
96 match result {
97 Ok(v) => Ok(serde_json::json!(v)),
98 Err(e) => Err(e.to_string()),
99 }
100 }
101 } else {
102 quote! {
103 Ok(serde_json::json!(result))
104 }
105 };
106
107 let expanded = quote! {
108 #input_fn
109
110 #[allow(non_camel_case_types)]
111 pub struct #fn_name { }
112
113 impl GeminiSchema for #fn_name {
114 fn gemini_schema() -> serde_json::Value {
115 use serde_json::{json, Map};
116 let mut props = Map::new();
117 #(#properties)*
118
119 json!({
120 "name": #fn_name_str,
121 "description": #fn_description,
122 "parameters": {
123 "type": "OBJECT",
124 "properties": props,
125 "required": [#(#required),*]
126 }
127 })
128 }
129 }
130
131 impl #fn_name {
132 pub async fn execute(args: serde_json::Value) -> Result<serde_json::Value, String> {
133 use serde::Deserialize;
134 #[derive(Deserialize)]
135 struct Args {
136 #(#param_names: #param_types,)*
137 }
138 let args = Args::deserialize(&args).map_err(|e| e.to_string())?;
139 let result = #fn_name(#(args.#param_names),*) #call_await;
140 #result_handling
141 }
142 }
143 };
144
145 TokenStream::from(expanded)
146}
147
148#[proc_macro]
168pub fn execute_function_calls_with_callback(input: TokenStream) -> TokenStream {
169 use syn::parse::{Parse, ParseStream};
170 use syn::{Expr, Token};
171
172 struct ExecuteWithCallbackInput {
173 session: Expr,
174 _comma1: Token![,],
175 callback: Expr,
176 _comma2: Token![,],
177 functions: syn::punctuated::Punctuated<syn::Path, Token![,]>,
178 }
179
180 impl Parse for ExecuteWithCallbackInput {
181 fn parse(input: ParseStream) -> syn::Result<Self> {
182 Ok(ExecuteWithCallbackInput {
183 session: input.parse()?,
184 _comma1: input.parse()?,
185 callback: input.parse()?,
186 _comma2: input.parse()?,
187 functions: input.parse_terminated(syn::Path::parse, Token![,])?,
188 })
189 }
190 }
191
192 let input = parse_macro_input!(input as ExecuteWithCallbackInput);
193 generate_execute_logic(&input.session, &input.callback, &input.functions)
194}
195
196#[proc_macro_attribute]
218pub fn gemini_schema(_attr: TokenStream, item: TokenStream) -> TokenStream {
219 let input = parse_macro_input!(item as DeriveInput);
220 let name = &input.ident;
221 let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
222 let description = extract_doc_comments(&input.attrs);
223
224 let expanded = match &input.data {
225 Data::Struct(data) => {
226 let mut properties = Vec::new();
227 let mut required = Vec::new();
228
229 match &data.fields {
230 Fields::Named(fields) => {
231 for field in &fields.named {
232 let field_name = field.ident.as_ref().unwrap();
233 let field_name_str = field_name.to_string();
234 let field_type = &field.ty;
235 let field_desc = extract_doc_comments(&field.attrs);
236
237 if has_reference(field_type) {
238 return syn::Error::new_spanned(
239 field_type,
240 "references are not supported in gemini_schema. Use owned types instead.",
241 )
242 .to_compile_error()
243 .into();
244 }
245
246 let is_optional = is_option(field_type);
247
248 properties.push(quote! {
249 let mut schema = <#field_type as GeminiSchema>::gemini_schema();
250 if !#field_desc.is_empty() {
251 if let Some(obj) = schema.as_object_mut() {
252 obj.insert("description".to_string(), serde_json::json!(#field_desc));
253 }
254 }
255 props.insert(#field_name_str.to_string(), schema);
256 });
257
258 if !is_optional {
259 required.push(field_name_str);
260 }
261 }
262 }
263 _ => panic!("gemini_schema only supports named fields in structs"),
264 }
265
266 quote! {
267 impl #impl_generics GeminiSchema for #name #ty_generics #where_clause {
268 fn gemini_schema() -> serde_json::Value {
269 use serde_json::{json, Map};
270 let mut props = Map::new();
271 #(#properties)*
272
273 let mut schema = json!({
274 "type": "OBJECT",
275 "properties": props,
276 "required": [#(#required),*]
277 });
278
279 if !#description.is_empty() {
280 if let Some(obj) = schema.as_object_mut() {
281 obj.insert("description".to_string(), json!(#description));
282 }
283 }
284 schema
285 }
286 }
287 }
288 }
289 Data::Enum(data) => {
290 let mut variants = Vec::new();
291 for variant in &data.variants {
292 if !matches!(variant.fields, Fields::Unit) {
293 panic!("gemini_schema only supports unit variants in enums");
294 }
295 variants.push(variant.ident.to_string());
296 }
297
298 quote! {
299 impl #impl_generics GeminiSchema for #name #ty_generics #where_clause {
300 fn gemini_schema() -> serde_json::Value {
301 use serde_json::json;
302 let mut schema = json!({
303 "type": "STRING",
304 "enum": [#(#variants),*]
305 });
306
307 if !#description.is_empty() {
308 if let Some(obj) = schema.as_object_mut() {
309 obj.insert("description".to_string(), json!(#description));
310 }
311 }
312 schema
313 }
314 }
315 }
316 }
317 _ => panic!("gemini_schema only supports structs and enums"),
318 };
319
320 let output = quote! {
321 #input
322 #expanded
323 };
324
325 TokenStream::from(output)
326}
327
328fn extract_doc_comments(attrs: &[Attribute]) -> String {
329 let mut doc_comments = Vec::new();
330 for attr in attrs {
331 if attr.path().is_ident("doc") {
332 if let Meta::NameValue(nv) = &attr.meta {
333 if let syn::Expr::Lit(expr_lit) = &nv.value {
334 if let Lit::Str(lit_str) = &expr_lit.lit {
335 doc_comments.push(lit_str.value().trim().to_string());
336 }
337 }
338 }
339 }
340 }
341 doc_comments.join("\n")
342}
343
344fn is_option(ty: &Type) -> bool {
345 if let Type::Path(tp) = ty {
346 if let Some(seg) = tp.path.segments.last() {
347 return seg.ident == "Option";
348 }
349 }
350 false
351}
352
353fn has_reference(ty: &Type) -> bool {
354 match ty {
355 Type::Reference(_) => true,
356 Type::Path(tp) => {
357 for seg in &tp.path.segments {
358 if let syn::PathArguments::AngleBracketed(ab) = &seg.arguments {
359 for arg in &ab.args {
360 if let syn::GenericArgument::Type(inner) = arg {
361 if has_reference(inner) {
362 return true;
363 }
364 }
365 }
366 }
367 }
368 false
369 }
370 _ => false,
371 }
372}
373
374#[proc_macro]
391pub fn execute_function_calls(input: TokenStream) -> TokenStream {
392 use syn::parse::{Parse, ParseStream};
393 use syn::{Expr, Token};
394
395 struct ExecuteInput {
396 session: Expr,
397 _comma: Token![,],
398 functions: syn::punctuated::Punctuated<syn::Path, Token![,]>,
399 }
400
401 impl Parse for ExecuteInput {
402 fn parse(input: ParseStream) -> syn::Result<Self> {
403 Ok(ExecuteInput {
404 session: input.parse()?,
405 _comma: input.parse()?,
406 functions: input.parse_terminated(syn::Path::parse, Token![,])?,
407 })
408 }
409 }
410
411 let input = parse_macro_input!(input as ExecuteInput);
412 let callback: Expr = syn::parse_quote! {
413 |_name: String, result: Result<gemini_client_api::serde_json::Value, String>| {
414 match result {
415 Ok(value) => value,
416 Err(e) => gemini_client_api::serde_json::json!({"Error": e}),
417 }
418 }
419 };
420
421 generate_execute_logic(&input.session, &callback, &input.functions)
422}
423
424fn generate_execute_logic(
425 session: &syn::Expr,
426 callback: &syn::Expr,
427 functions: &syn::punctuated::Punctuated<syn::Path, syn::Token![,]>,
428) -> TokenStream {
429 let num_funcs = functions.len();
430
431 let match_arms = functions.iter().enumerate().map(|(i, path)| {
432 let name_str = path.segments.last().unwrap().ident.to_string();
433 quote! {
434 #name_str => {
435 let args = call.args().clone().unwrap_or(gemini_client_api::serde_json::json!({}));
436 let fut: gemini_client_api::futures::future::BoxFuture<'static, (usize, String, Result<gemini_client_api::serde_json::Value, String>)> = Box::pin(async move {
437 (#i, #name_str.to_string(), #path::execute(args).await)
438 });
439 futures.push(fut);
440 }
441 }
442 });
443
444 let expanded = quote! {
445 {
446 let mut results_array = vec![None; #num_funcs];
447 let mut result_callback = #callback;
449
450 if let Some(chat) = #session.get_last_chat() {
451 let mut futures = Vec::new();
452 for part in chat.parts() {
453 if let gemini_client_api::gemini::types::request::PartType::FunctionCall(call) = part.data() {
454 match call.name().as_str() {
455 #(#match_arms)*
456 _ => {}
457 }
458 }
459 }
460 if !futures.is_empty() {
461 let results = gemini_client_api::futures::future::join_all(futures).await;
462 for (idx, name, res) in results {
463 let val_to_add = result_callback(name.clone(), res.clone());
465
466 if let Err(e) = #session.add_function_response(name.clone(), val_to_add) {
467 results_array[idx] = Some(Err(format!(
468 "failed to add function response for `{}`: {}",
469 name, e
470 )));
471 continue;
472 }
473 results_array[idx] = Some(res);
474 }
475 }
476 }
477 results_array
478 }
479 };
480
481 TokenStream::from(expanded)
482}