1use proc_macro::TokenStream;
2use quote::{format_ident, quote};
3use syn::{
4 parse_macro_input, FnArg, GenericParam, ItemTrait, LitInt, Receiver, ReturnType, TraitItem,
5 Type,
6};
7
8use rs_schema;
9
10#[proc_macro_attribute]
11pub fn trait_schema(attr: TokenStream, item: TokenStream) -> TokenStream {
13 let mut input = parse_macro_input!(item as ItemTrait);
14 let trait_ident = input.ident.clone();
15 let schema_fn_ident = format_ident!("{}_schema", trait_ident);
17
18 let generic_annotations = parse_generic_annotations_attr(proc_macro2::TokenStream::from(attr));
21
22 let trait_generics = build_trait_generics(&input.generics, &generic_annotations);
24
25 let trait_functions = extract_trait_functions(&mut input.items);
26
27 let trait_supertraits = extract_supertraits(&input.supertraits);
28
29 let trait_name_string = trait_ident.to_string();
30 let trait_schema = rs_schema::TraitSchema {
31 name: trait_name_string,
32 functions: trait_functions,
33 generics: trait_generics,
34 supertraits: trait_supertraits,
35 };
36
37 let trait_tokens: proc_macro2::TokenStream = trait_schema.into();
38
39 let output = quote! {
40 #input
41
42 #[allow(non_snake_case)]
43 pub fn #schema_fn_ident() -> rs_schema::TraitSchema {
44 #trait_tokens
45 }
46 };
47
48 output.into()
54}
55
56fn process_fn_arg_annotations(arg: &mut FnArg) -> rs_schema::FnArgAnnotations {
58 let mut info = rs_schema::FnArgAnnotations::new();
59 if let syn::FnArg::Typed(pat_type) = arg {
60 for attr in &pat_type.attrs {
61 if attr.path().is_ident("arg") {
62 let _ = attr.parse_nested_meta(|meta| {
64 if meta.path.is_ident("collection_as_item") {
65 info.collection_as_item = true;
66 return Ok(());
67 }
68 if meta.path.is_ident("assert_len") {
69 let v: LitInt = meta.value()?.parse()?;
70 info.assert_len = Some(v.base10_parse::<usize>()?);
71 return Ok(());
72 }
73 if meta.path.is_ident("cffi_type") {
74 let v: syn::LitStr = meta.value()?.parse()?;
75 info.cffi_type = Some(v.value());
76 return Ok(());
77 }
78 Ok(())
81 });
82 }
83 }
84 pat_type.attrs.retain(|a| !a.path().is_ident("arg"));
85 }
86
87 info
88}
89
90fn process_fn_annotations(func: &mut syn::TraitItemFn) -> rs_schema::FunctionAnnotations {
92 let mut info = rs_schema::FunctionAnnotations::new();
93 for attr in &func.attrs {
94 if attr.path().is_ident("func") {
95 let _ = attr.parse_nested_meta(|meta| {
97 if meta.path.is_ident("cffi_impl_no_op") {
98 info.cffi_impl_no_op = true;
99 return Ok(());
100 }
101 Ok(())
102 });
103 }
104 }
105 func.attrs.retain(|a| !a.path().is_ident("func"));
107 info
108}
109
110fn parse_generic_annotations_attr(
113 tokens: proc_macro2::TokenStream,
114) -> std::collections::HashMap<String, String> {
115 let mut result = std::collections::HashMap::new();
116 let mut iter = tokens.into_iter().peekable();
117 while iter.peek().is_some() {
118 let param_name = match iter.next() {
120 Some(proc_macro2::TokenTree::Ident(ident)) => ident.to_string(),
121 _ => break,
122 };
123 match iter.next() {
125 Some(proc_macro2::TokenTree::Punct(p)) if p.as_char() == '=' => {}
126 _ => break,
127 }
128 let cffi_type = match iter.next() {
130 Some(proc_macro2::TokenTree::Literal(lit)) => {
131 let lit_str = lit.to_string();
132 if lit_str.starts_with('"') && lit_str.ends_with('"') {
133 lit_str[1..lit_str.len() - 1].to_string()
134 } else {
135 break;
136 }
137 }
138 _ => break,
139 };
140 result.insert(param_name, cffi_type);
141 match iter.peek() {
143 Some(proc_macro2::TokenTree::Punct(p)) if p.as_char() == ',' => {
144 iter.next(); }
146 None => break,
147 _ => break,
148 }
149 }
150 result
151}
152
153fn build_trait_generics(
155 generics: &syn::Generics,
156 generic_annotations: &std::collections::HashMap<String, String>,
157) -> Vec<rs_schema::GenericParamSchema> {
158 let mut trait_generics: Vec<rs_schema::GenericParamSchema> = Vec::new();
159
160 for generic_param in &generics.params {
161 if let GenericParam::Type(type_param) = generic_param {
162 let param_name = type_param.ident.to_string();
163 let cffi_type = generic_annotations.get(¶m_name).cloned();
164 let annotations = if cffi_type.is_some() {
165 Some(rs_schema::GenericParamAnnotations { cffi_type })
166 } else {
167 None
168 };
169
170 trait_generics.push(rs_schema::GenericParamSchema {
171 name: param_name,
172 annotations,
173 });
174 }
175 }
176
177 trait_generics
178}
179
180fn extract_trait_functions(items: &mut Vec<TraitItem>) -> Vec<rs_schema::FunctionSchema> {
182 let mut trait_functions: Vec<rs_schema::FunctionSchema> = Vec::new();
183
184 for it in items.iter_mut() {
185 if let TraitItem::Fn(m) = it {
186 let fn_annotations = process_fn_annotations(m);
187 let sig = &mut m.sig;
188
189 let args: Vec<rs_schema::FunctionArgSchema> = sig
190 .inputs
191 .iter_mut()
192 .filter_map(|arg| {
193 if let FnArg::Typed(pat_type) = arg {
194 let arg_name = if let syn::Pat::Ident(pat_ident) = &*pat_type.pat {
195 format!("{}", quote! { #pat_ident })
196 } else {
197 "".to_string()
198 };
199
200 let arg_ty = &*pat_type.ty;
201 let arg_ty = type_schema_from_type(arg_ty);
202
203 let annotations = process_fn_arg_annotations(arg);
204
205 Some(rs_schema::FunctionArgSchema {
206 name: arg_name,
207 ty: Some(arg_ty),
208 annotations: Some(annotations),
209 })
210 } else if let FnArg::Receiver(Receiver { .. }) = arg {
211 Some(rs_schema::FunctionArgSchema {
212 name: "self".to_string(),
213 ty: None,
214 annotations: None,
215 })
216 } else {
217 None
218 }
219 })
220 .collect();
221
222 let return_type = match &sig.output {
223 ReturnType::Default => rs_schema::TypeSchema {
224 ty: "()".to_string(),
225 generic_ty_args: vec![],
226 },
227 ReturnType::Type(_, ty) => type_schema_from_type(ty),
228 };
229
230 trait_functions.push(rs_schema::FunctionSchema {
231 name: sig.ident.to_string(),
232 args,
233 return_type,
234 body: None,
235 extern_layout: None,
236 annotations: Some(fn_annotations),
237 });
238 }
239 }
240
241 trait_functions
242}
243
244fn extract_supertraits(
246 supertraits: &syn::punctuated::Punctuated<syn::TypeParamBound, syn::token::Plus>,
247) -> Vec<rs_schema::TypeSchema> {
248 supertraits
249 .iter()
250 .filter_map(|bound| {
251 if let syn::TypeParamBound::Trait(trait_bound) = bound {
252 Some(type_schema_from_path(&trait_bound.path))
253 } else {
254 None
255 }
256 })
257 .collect()
258}
259
260fn type_schema_from_type(ty: &Type) -> rs_schema::TypeSchema {
261 match ty {
262 Type::Path(type_path) => type_schema_from_path(&type_path.path),
263 _ => rs_schema::TypeSchema {
264 ty: format!("{}", quote! { #ty }),
265 generic_ty_args: vec![],
266 },
267 }
268}
269
270fn type_schema_from_path(path: &syn::Path) -> rs_schema::TypeSchema {
271 let mut ty = String::new();
272 if path.leading_colon.is_some() {
273 ty.push_str("::");
274 }
275 ty.push_str(
276 &path
277 .segments
278 .iter()
279 .map(|segment| segment.ident.to_string())
280 .collect::<Vec<_>>()
281 .join("::"),
282 );
283
284 let generic_ty_args = path
285 .segments
286 .last()
287 .and_then(|segment| match &segment.arguments {
288 syn::PathArguments::AngleBracketed(args) => Some(args),
289 _ => None,
290 })
291 .map(|args| {
292 args.args
293 .iter()
294 .map(|arg| match arg {
295 syn::GenericArgument::Type(ty) => type_schema_from_type(ty),
296 _ => rs_schema::TypeSchema {
297 ty: format!("{}", quote! { #arg }),
298 generic_ty_args: vec![],
299 },
300 })
301 .collect()
302 })
303 .unwrap_or_default();
304
305 rs_schema::TypeSchema {
306 ty,
307 generic_ty_args,
308 }
309}
310
311#[cfg(test)]
312mod tests {
313 use super::*;
314 use syn::parse_quote;
315
316 #[test]
317 fn test_process_fn_arg_annotations_no_annotations() {
318 let mut arg: FnArg = parse_quote!(arg1: String);
319 let annotations = process_fn_arg_annotations(&mut arg);
320
321 assert!(!annotations.collection_as_item);
322 assert!(annotations.assert_len.is_none());
323 }
324
325 #[test]
326 fn test_process_fn_arg_annotations_collection_as_item() {
327 let mut arg: FnArg = parse_quote!(#[arg(collection_as_item)] arg1: Vec<String>);
328 let annotations = process_fn_arg_annotations(&mut arg);
329
330 assert!(annotations.collection_as_item);
331 assert!(annotations.assert_len.is_none());
332 }
333
334 #[test]
335 fn test_process_fn_arg_annotations_assert_len() {
336 let mut arg: FnArg = parse_quote!(#[arg(assert_len = 5)] arg1: Vec<String>);
337 let annotations = process_fn_arg_annotations(&mut arg);
338
339 assert!(!annotations.collection_as_item);
340 assert_eq!(annotations.assert_len, Some(5));
341 }
342
343 #[test]
344 fn test_process_fn_arg_annotations_combined() {
345 let mut arg: FnArg =
346 parse_quote!(#[arg(collection_as_item, assert_len = 10)] arg1: Vec<String>);
347 let annotations = process_fn_arg_annotations(&mut arg);
348
349 assert!(annotations.collection_as_item);
350 assert_eq!(annotations.assert_len, Some(10));
351 }
352
353 #[test]
354 fn test_process_fn_arg_annotations_multiple_values() {
355 let mut arg: FnArg = parse_quote!(#[arg(assert_len = 42)] arg1: Vec<i32>);
356 let annotations = process_fn_arg_annotations(&mut arg);
357
358 assert_eq!(annotations.assert_len, Some(42));
359 }
360
361 #[test]
362 fn test_process_fn_arg_annotations_removes_arg_attribute() {
363 let mut arg: FnArg = parse_quote!(#[arg(collection_as_item)] arg1: Vec<String>);
364 process_fn_arg_annotations(&mut arg);
365
366 if let FnArg::Typed(pat_type) = &arg {
367 let has_arg_attr = pat_type
369 .attrs
370 .iter()
371 .any(|attr| attr.path().is_ident("arg"));
372 assert!(!has_arg_attr);
373 } else {
374 panic!("Expected FnArg::Typed");
375 }
376 }
377
378 #[test]
379 fn test_process_fn_arg_annotations_zero_assert_len() {
380 let mut arg: FnArg = parse_quote!(#[arg(assert_len = 0)] arg1: Vec<String>);
381 let annotations = process_fn_arg_annotations(&mut arg);
382
383 assert_eq!(annotations.assert_len, Some(0));
384 }
385
386 #[test]
387 fn test_process_fn_arg_annotations_large_assert_len() {
388 let mut arg: FnArg = parse_quote!(#[arg(assert_len = 999999)] arg1: Vec<String>);
389 let annotations = process_fn_arg_annotations(&mut arg);
390
391 assert_eq!(annotations.assert_len, Some(999999));
392 }
393
394 #[test]
395 fn test_fn_arg_annotations_new() {
396 let annotations = rs_schema::FnArgAnnotations::new();
397 assert!(!annotations.collection_as_item);
398 assert!(annotations.assert_len.is_none());
399 }
400
401 #[test]
402 fn test_fn_arg_annotations_creation_manual() {
403 let annotations = rs_schema::FnArgAnnotations {
404 collection_as_item: true,
405 assert_len: Some(25),
406 cffi_type: Some("opt_ptr<f32>".to_string()),
407 };
408
409 assert!(annotations.collection_as_item);
410 assert_eq!(annotations.assert_len, Some(25));
411 assert_eq!(annotations.cffi_type, Some("opt_ptr<f32>".to_string()));
412 }
413
414 #[test]
415 fn test_process_fn_arg_annotations_cffi_type() {
416 let mut arg: FnArg = parse_quote!(#[arg(cffi_type = "ptr<f64>")] values: Arc<f64>);
417 let annotations = process_fn_arg_annotations(&mut arg);
418
419 assert_eq!(annotations.cffi_type, Some("ptr<f64>".to_string()));
420 assert!(!annotations.collection_as_item);
421 assert!(annotations.assert_len.is_none());
422
423 if let FnArg::Typed(pat_type) = &arg {
425 let has_arg_attr = pat_type
426 .attrs
427 .iter()
428 .any(|attr| attr.path().is_ident("arg"));
429 assert!(!has_arg_attr);
430 } else {
431 panic!("Expected FnArg::Typed");
432 }
433 }
434
435 #[test]
436 fn test_parse_generic_annotations_attr_empty() {
437 let tokens = proc_macro2::TokenStream::new();
438 let result = parse_generic_annotations_attr(tokens);
439 assert!(result.is_empty());
440 }
441
442 #[test]
443 fn test_parse_generic_annotations_attr_single() {
444 let tokens = quote::quote!(T = "ptr<void>");
445 let result = parse_generic_annotations_attr(tokens);
446 assert_eq!(result.get("T"), Some(&"ptr<void>".to_string()));
447 }
448
449 #[test]
450 fn test_parse_generic_annotations_attr_multiple() {
451 let tokens = quote::quote!(T = "ptr<void>", U = "ptr<f32>");
452 let result = parse_generic_annotations_attr(tokens);
453 assert_eq!(result.get("T"), Some(&"ptr<void>".to_string()));
454 assert_eq!(result.get("U"), Some(&"ptr<f32>".to_string()));
455 }
456
457 #[test]
458 fn test_build_trait_generics_basic() {
459 let generics: syn::Generics = parse_quote!(<T, U>);
460 let mut annotations = std::collections::HashMap::new();
461 annotations.insert("T".to_string(), "ptr<void>".to_string());
462 let result = build_trait_generics(&generics, &annotations);
463 assert_eq!(result.len(), 2);
464 assert_eq!(result[0].name, "T");
465 assert_eq!(
466 result[0].annotations.as_ref().unwrap().cffi_type,
467 Some("ptr<void>".to_string())
468 );
469 assert_eq!(result[1].name, "U");
470 assert!(result[1].annotations.is_none());
471 }
472
473 #[test]
474 fn test_extract_trait_functions_basic() {
475 let mut items: Vec<TraitItem> = vec![
476 parse_quote! {
477 fn foo(&self, x: i32) -> i32;
478 },
479 parse_quote! {
480 fn bar(&mut self);
481 },
482 ];
483 let result = extract_trait_functions(&mut items);
484 assert_eq!(result.len(), 2);
485 assert_eq!(result[0].name, "foo");
486 assert_eq!(result[0].args[0].name, "self");
487 assert_eq!(result[0].args[1].name, "x");
488 assert_eq!(result[0].return_type.ty, "i32");
489 assert_eq!(result[1].name, "bar");
490 assert_eq!(result[1].args[0].name, "self");
491 assert_eq!(result[1].return_type.ty, "()");
492 }
493
494 #[test]
495 fn test_process_fn_annotations_no_attr() {
496 let mut func: syn::TraitItemFn = parse_quote!(
497 fn foo(&self);
498 );
499 let annotations = process_fn_annotations(&mut func);
500
501 assert!(!annotations.cffi_impl_no_op);
502 let has_func_attr = func.attrs.iter().any(|a| a.path().is_ident("func"));
504 assert!(!has_func_attr);
505 }
506
507 #[test]
508 fn test_process_fn_annotations_cffi_impl_no_op() {
509 let mut func: syn::TraitItemFn = parse_quote!(
510 #[func(cffi_impl_no_op)]
511 fn foo(&self);
512 );
513 let annotations = process_fn_annotations(&mut func);
514
515 assert!(annotations.cffi_impl_no_op);
516
517 let has_func_attr = func.attrs.iter().any(|a| a.path().is_ident("func"));
519 assert!(!has_func_attr);
520 }
521
522 #[test]
523 fn test_extract_supertraits_empty() {
524 let trait_def: syn::ItemTrait = parse_quote!(
525 trait MyTrait {}
526 );
527 let result = extract_supertraits(&trait_def.supertraits);
528 assert!(result.is_empty());
529 }
530
531 #[test]
532 fn test_extract_supertraits_single() {
533 let trait_def: syn::ItemTrait = parse_quote!(
534 trait MyTrait: Clone {}
535 );
536 let result = extract_supertraits(&trait_def.supertraits);
537 assert_eq!(result.len(), 1);
538 assert_eq!(result[0].ty, "Clone");
539 }
540
541 #[test]
542 fn test_extract_supertraits_multiple() {
543 let trait_def: syn::ItemTrait = parse_quote!(
544 trait MyTrait: Clone + Debug + Send {}
545 );
546 let result = extract_supertraits(&trait_def.supertraits);
547 assert_eq!(result.len(), 3);
548 assert_eq!(result[0].ty, "Clone");
549 assert_eq!(result[1].ty, "Debug");
550 assert_eq!(result[2].ty, "Send");
551 }
552
553 #[test]
554 fn test_extract_supertraits_with_path() {
555 let trait_def: syn::ItemTrait = parse_quote!(
556 trait MyTrait: std::fmt::Debug {}
557 );
558 let result = extract_supertraits(&trait_def.supertraits);
559 assert_eq!(result.len(), 1);
560 assert_eq!(result[0].ty, "std::fmt::Debug");
561 }
562
563 #[test]
564 fn test_extract_supertraits_generic_trait() {
565 let trait_def: syn::ItemTrait = parse_quote!(
566 trait MyTrait: IntoIterator<Item = String> {}
567 );
568 let result = extract_supertraits(&trait_def.supertraits);
569 assert_eq!(result.len(), 1);
570 assert_eq!(result[0].ty, "IntoIterator");
571 assert_eq!(result[0].generic_ty_args.len(), 1);
572 assert_eq!(result[0].generic_ty_args[0].ty, "Item = String");
573 }
574
575 #[test]
576 fn test_extract_supertraits_mixed_lifetimes_and_traits() {
577 let trait_def: syn::ItemTrait = parse_quote!(
578 trait MyTrait: 'static + Clone + Sync {}
579 );
580 let result = extract_supertraits(&trait_def.supertraits);
581 assert_eq!(result.len(), 2);
583 assert_eq!(result[0].ty, "Clone");
584 assert_eq!(result[1].ty, "Sync");
585 }
586
587 #[test]
588 fn test_extract_supertraits_complex() {
589 let trait_def: syn::ItemTrait = parse_quote!(
590 trait MyTrait: Send + Sync + std::fmt::Debug + Clone {}
591 );
592 let result = extract_supertraits(&trait_def.supertraits);
593 assert_eq!(result.len(), 4);
594 assert_eq!(result[0].ty, "Send");
595 assert_eq!(result[1].ty, "Sync");
596 assert_eq!(result[2].ty, "std::fmt::Debug");
597 assert_eq!(result[3].ty, "Clone");
598 }
599}