rs-schema-derive-impl 0.1.0

Implementation of procedural macros for `rs-schema-derive`.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
use proc_macro::TokenStream;
use quote::{format_ident, quote};
use syn::{
    parse_macro_input, FnArg, GenericParam, ItemTrait, LitInt, Receiver, ReturnType, TraitItem,
    Type,
};

use rs_schema;

#[proc_macro_attribute]
/// Attribute macro that captures trait metadata and emits a schema function.
pub fn trait_schema(attr: TokenStream, item: TokenStream) -> TokenStream {
    let mut input = parse_macro_input!(item as ItemTrait);
    let trait_ident = input.ident.clone();
    // Generated schema function name
    let schema_fn_ident = format_ident!("{}_schema", trait_ident);

    // Parse generic parameter annotations from trait-level attribute
    // Format: #[trait_schema] or #[trait_schema(T = "cffi_type", U = "other_cffi_type")]
    let generic_annotations = parse_generic_annotations_attr(proc_macro2::TokenStream::from(attr));

    // Build generics and functions using helper routines
    let trait_generics = build_trait_generics(&input.generics, &generic_annotations);

    let trait_functions = extract_trait_functions(&mut input.items);

    let trait_supertraits = extract_supertraits(&input.supertraits);

    let trait_name_string = trait_ident.to_string();
    let trait_schema = rs_schema::TraitSchema {
        name: trait_name_string,
        functions: trait_functions,
        generics: trait_generics,
        supertraits: trait_supertraits,
    };

    let trait_tokens: proc_macro2::TokenStream = trait_schema.into();

    let output = quote! {
        #input

        #[allow(non_snake_case)]
        pub fn #schema_fn_ident() -> rs_schema::TraitSchema {
            #trait_tokens
        }
    };

    // Debug formatting output:
    // eprintln!("{:#?}", output);
    // Raw text output:
    // println!("{}", output);

    output.into()
}

/// Parse argument-level annotations (#[arg(...)]) and strip the attribute from the input.
fn process_fn_arg_annotations(arg: &mut FnArg) -> rs_schema::FnArgAnnotations {
    let mut info = rs_schema::FnArgAnnotations::new();
    if let syn::FnArg::Typed(pat_type) = arg {
        for attr in &pat_type.attrs {
            if attr.path().is_ident("arg") {
                // Parse meta inside #[arg(...)]
                let _ = attr.parse_nested_meta(|meta| {
                    if meta.path.is_ident("collection_as_item") {
                        info.collection_as_item = true;
                        return Ok(());
                    }
                    if meta.path.is_ident("assert_len") {
                        let v: LitInt = meta.value()?.parse()?;
                        info.assert_len = Some(v.base10_parse::<usize>()?);
                        return Ok(());
                    }
                    if meta.path.is_ident("cffi_type") {
                        let v: syn::LitStr = meta.value()?.parse()?;
                        info.cffi_type = Some(v.value());
                        return Ok(());
                    }
                    // Unknown key -> ignore or error:
                    // return Err(meta.error("unknown arg attribute"));
                    Ok(())
                });
            }
        }
        pat_type.attrs.retain(|a| !a.path().is_ident("arg"));
    }

    info
}

/// Parse function-level annotations on trait methods (#[func(...)]).
fn process_fn_annotations(func: &mut syn::TraitItemFn) -> rs_schema::FunctionAnnotations {
    let mut info = rs_schema::FunctionAnnotations::new();
    for attr in &func.attrs {
        if attr.path().is_ident("func") {
            // Parse nested meta inside #[func(...)]
            let _ = attr.parse_nested_meta(|meta| {
                if meta.path.is_ident("cffi_impl_no_op") {
                    info.cffi_impl_no_op = true;
                    return Ok(());
                }
                Ok(())
            });
        }
    }
    // remove the parsed attribute so downstream consumers don't see it
    func.attrs.retain(|a| !a.path().is_ident("func"));
    info
}

/// Parse generic parameter annotations from trait attribute
/// Format: #[trait_schema] or #[trait_schema(T = "ptr<void>", U = "ptr<f32>")]
fn parse_generic_annotations_attr(
    tokens: proc_macro2::TokenStream,
) -> std::collections::HashMap<String, String> {
    let mut result = std::collections::HashMap::new();
    let mut iter = tokens.into_iter().peekable();
    while iter.peek().is_some() {
        // Expect: identifier
        let param_name = match iter.next() {
            Some(proc_macro2::TokenTree::Ident(ident)) => ident.to_string(),
            _ => break,
        };
        // Expect: =
        match iter.next() {
            Some(proc_macro2::TokenTree::Punct(p)) if p.as_char() == '=' => {}
            _ => break,
        }
        // Expect: string literal
        let cffi_type = match iter.next() {
            Some(proc_macro2::TokenTree::Literal(lit)) => {
                let lit_str = lit.to_string();
                if lit_str.starts_with('"') && lit_str.ends_with('"') {
                    lit_str[1..lit_str.len() - 1].to_string()
                } else {
                    break;
                }
            }
            _ => break,
        };
        result.insert(param_name, cffi_type);
        // Expect optional: comma
        match iter.peek() {
            Some(proc_macro2::TokenTree::Punct(p)) if p.as_char() == ',' => {
                iter.next(); // consume comma
            }
            None => break,
            _ => break,
        }
    }
    result
}

/// Build a vector of `GenericParamSchema` from `syn::Generics` and parsed annotations.
fn build_trait_generics(
    generics: &syn::Generics,
    generic_annotations: &std::collections::HashMap<String, String>,
) -> Vec<rs_schema::GenericParamSchema> {
    let mut trait_generics: Vec<rs_schema::GenericParamSchema> = Vec::new();

    for generic_param in &generics.params {
        if let GenericParam::Type(type_param) = generic_param {
            let param_name = type_param.ident.to_string();
            let cffi_type = generic_annotations.get(&param_name).cloned();
            let annotations = if cffi_type.is_some() {
                Some(rs_schema::GenericParamAnnotations { cffi_type })
            } else {
                None
            };

            trait_generics.push(rs_schema::GenericParamSchema {
                name: param_name,
                annotations,
            });
        }
    }

    trait_generics
}

/// Extract function schemas from the trait items, parsing argument annotations.
fn extract_trait_functions(items: &mut Vec<TraitItem>) -> Vec<rs_schema::FunctionSchema> {
    let mut trait_functions: Vec<rs_schema::FunctionSchema> = Vec::new();

    for it in items.iter_mut() {
        if let TraitItem::Fn(m) = it {
            let fn_annotations = process_fn_annotations(m);
            let sig = &mut m.sig;

            let args: Vec<rs_schema::FunctionArgSchema> = sig
                .inputs
                .iter_mut()
                .filter_map(|arg| {
                    if let FnArg::Typed(pat_type) = arg {
                        let arg_name = if let syn::Pat::Ident(pat_ident) = &*pat_type.pat {
                            format!("{}", quote! { #pat_ident })
                        } else {
                            "".to_string()
                        };

                        let arg_ty = &*pat_type.ty;
                        let arg_ty = type_schema_from_type(arg_ty);

                        let annotations = process_fn_arg_annotations(arg);

                        Some(rs_schema::FunctionArgSchema {
                            name: arg_name,
                            ty: Some(arg_ty),
                            annotations: Some(annotations),
                        })
                    } else if let FnArg::Receiver(Receiver { .. }) = arg {
                        Some(rs_schema::FunctionArgSchema {
                            name: "self".to_string(),
                            ty: None,
                            annotations: None,
                        })
                    } else {
                        None
                    }
                })
                .collect();

            let return_type = match &sig.output {
                ReturnType::Default => rs_schema::TypeSchema {
                    ty: "()".to_string(),
                    generic_ty_args: vec![],
                },
                ReturnType::Type(_, ty) => type_schema_from_type(ty),
            };

            trait_functions.push(rs_schema::FunctionSchema {
                name: sig.ident.to_string(),
                args,
                return_type,
                body: None,
                extern_layout: None,
                annotations: Some(fn_annotations),
            });
        }
    }

    trait_functions
}

/// Extract supertraits from the trait bounds
fn extract_supertraits(
    supertraits: &syn::punctuated::Punctuated<syn::TypeParamBound, syn::token::Plus>,
) -> Vec<rs_schema::TypeSchema> {
    supertraits
        .iter()
        .filter_map(|bound| {
            if let syn::TypeParamBound::Trait(trait_bound) = bound {
                Some(type_schema_from_path(&trait_bound.path))
            } else {
                None
            }
        })
        .collect()
}

fn type_schema_from_type(ty: &Type) -> rs_schema::TypeSchema {
    match ty {
        Type::Path(type_path) => type_schema_from_path(&type_path.path),
        _ => rs_schema::TypeSchema {
            ty: format!("{}", quote! { #ty }),
            generic_ty_args: vec![],
        },
    }
}

fn type_schema_from_path(path: &syn::Path) -> rs_schema::TypeSchema {
    let mut ty = String::new();
    if path.leading_colon.is_some() {
        ty.push_str("::");
    }
    ty.push_str(
        &path
            .segments
            .iter()
            .map(|segment| segment.ident.to_string())
            .collect::<Vec<_>>()
            .join("::"),
    );

    let generic_ty_args = path
        .segments
        .last()
        .and_then(|segment| match &segment.arguments {
            syn::PathArguments::AngleBracketed(args) => Some(args),
            _ => None,
        })
        .map(|args| {
            args.args
                .iter()
                .map(|arg| match arg {
                    syn::GenericArgument::Type(ty) => type_schema_from_type(ty),
                    _ => rs_schema::TypeSchema {
                        ty: format!("{}", quote! { #arg }),
                        generic_ty_args: vec![],
                    },
                })
                .collect()
        })
        .unwrap_or_default();

    rs_schema::TypeSchema {
        ty,
        generic_ty_args,
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use syn::parse_quote;

    #[test]
    fn test_process_fn_arg_annotations_no_annotations() {
        let mut arg: FnArg = parse_quote!(arg1: String);
        let annotations = process_fn_arg_annotations(&mut arg);

        assert!(!annotations.collection_as_item);
        assert!(annotations.assert_len.is_none());
    }

    #[test]
    fn test_process_fn_arg_annotations_collection_as_item() {
        let mut arg: FnArg = parse_quote!(#[arg(collection_as_item)] arg1: Vec<String>);
        let annotations = process_fn_arg_annotations(&mut arg);

        assert!(annotations.collection_as_item);
        assert!(annotations.assert_len.is_none());
    }

    #[test]
    fn test_process_fn_arg_annotations_assert_len() {
        let mut arg: FnArg = parse_quote!(#[arg(assert_len = 5)] arg1: Vec<String>);
        let annotations = process_fn_arg_annotations(&mut arg);

        assert!(!annotations.collection_as_item);
        assert_eq!(annotations.assert_len, Some(5));
    }

    #[test]
    fn test_process_fn_arg_annotations_combined() {
        let mut arg: FnArg =
            parse_quote!(#[arg(collection_as_item, assert_len = 10)] arg1: Vec<String>);
        let annotations = process_fn_arg_annotations(&mut arg);

        assert!(annotations.collection_as_item);
        assert_eq!(annotations.assert_len, Some(10));
    }

    #[test]
    fn test_process_fn_arg_annotations_multiple_values() {
        let mut arg: FnArg = parse_quote!(#[arg(assert_len = 42)] arg1: Vec<i32>);
        let annotations = process_fn_arg_annotations(&mut arg);

        assert_eq!(annotations.assert_len, Some(42));
    }

    #[test]
    fn test_process_fn_arg_annotations_removes_arg_attribute() {
        let mut arg: FnArg = parse_quote!(#[arg(collection_as_item)] arg1: Vec<String>);
        process_fn_arg_annotations(&mut arg);

        if let FnArg::Typed(pat_type) = &arg {
            // The #[arg(...)] attribute should be removed
            let has_arg_attr = pat_type
                .attrs
                .iter()
                .any(|attr| attr.path().is_ident("arg"));
            assert!(!has_arg_attr);
        } else {
            panic!("Expected FnArg::Typed");
        }
    }

    #[test]
    fn test_process_fn_arg_annotations_zero_assert_len() {
        let mut arg: FnArg = parse_quote!(#[arg(assert_len = 0)] arg1: Vec<String>);
        let annotations = process_fn_arg_annotations(&mut arg);

        assert_eq!(annotations.assert_len, Some(0));
    }

    #[test]
    fn test_process_fn_arg_annotations_large_assert_len() {
        let mut arg: FnArg = parse_quote!(#[arg(assert_len = 999999)] arg1: Vec<String>);
        let annotations = process_fn_arg_annotations(&mut arg);

        assert_eq!(annotations.assert_len, Some(999999));
    }

    #[test]
    fn test_fn_arg_annotations_new() {
        let annotations = rs_schema::FnArgAnnotations::new();
        assert!(!annotations.collection_as_item);
        assert!(annotations.assert_len.is_none());
    }

    #[test]
    fn test_fn_arg_annotations_creation_manual() {
        let annotations = rs_schema::FnArgAnnotations {
            collection_as_item: true,
            assert_len: Some(25),
            cffi_type: Some("opt_ptr<f32>".to_string()),
        };

        assert!(annotations.collection_as_item);
        assert_eq!(annotations.assert_len, Some(25));
        assert_eq!(annotations.cffi_type, Some("opt_ptr<f32>".to_string()));
    }

    #[test]
    fn test_process_fn_arg_annotations_cffi_type() {
        let mut arg: FnArg = parse_quote!(#[arg(cffi_type = "ptr<f64>")] values: Arc<f64>);
        let annotations = process_fn_arg_annotations(&mut arg);

        assert_eq!(annotations.cffi_type, Some("ptr<f64>".to_string()));
        assert!(!annotations.collection_as_item);
        assert!(annotations.assert_len.is_none());

        // Ensure the attribute was removed from the typed arg
        if let FnArg::Typed(pat_type) = &arg {
            let has_arg_attr = pat_type
                .attrs
                .iter()
                .any(|attr| attr.path().is_ident("arg"));
            assert!(!has_arg_attr);
        } else {
            panic!("Expected FnArg::Typed");
        }
    }

    #[test]
    fn test_parse_generic_annotations_attr_empty() {
        let tokens = proc_macro2::TokenStream::new();
        let result = parse_generic_annotations_attr(tokens);
        assert!(result.is_empty());
    }

    #[test]
    fn test_parse_generic_annotations_attr_single() {
        let tokens = quote::quote!(T = "ptr<void>");
        let result = parse_generic_annotations_attr(tokens);
        assert_eq!(result.get("T"), Some(&"ptr<void>".to_string()));
    }

    #[test]
    fn test_parse_generic_annotations_attr_multiple() {
        let tokens = quote::quote!(T = "ptr<void>", U = "ptr<f32>");
        let result = parse_generic_annotations_attr(tokens);
        assert_eq!(result.get("T"), Some(&"ptr<void>".to_string()));
        assert_eq!(result.get("U"), Some(&"ptr<f32>".to_string()));
    }

    #[test]
    fn test_build_trait_generics_basic() {
        let generics: syn::Generics = parse_quote!(<T, U>);
        let mut annotations = std::collections::HashMap::new();
        annotations.insert("T".to_string(), "ptr<void>".to_string());
        let result = build_trait_generics(&generics, &annotations);
        assert_eq!(result.len(), 2);
        assert_eq!(result[0].name, "T");
        assert_eq!(
            result[0].annotations.as_ref().unwrap().cffi_type,
            Some("ptr<void>".to_string())
        );
        assert_eq!(result[1].name, "U");
        assert!(result[1].annotations.is_none());
    }

    #[test]
    fn test_extract_trait_functions_basic() {
        let mut items: Vec<TraitItem> = vec![
            parse_quote! {
                fn foo(&self, x: i32) -> i32;
            },
            parse_quote! {
                fn bar(&mut self);
            },
        ];
        let result = extract_trait_functions(&mut items);
        assert_eq!(result.len(), 2);
        assert_eq!(result[0].name, "foo");
        assert_eq!(result[0].args[0].name, "self");
        assert_eq!(result[0].args[1].name, "x");
        assert_eq!(result[0].return_type.ty, "i32");
        assert_eq!(result[1].name, "bar");
        assert_eq!(result[1].args[0].name, "self");
        assert_eq!(result[1].return_type.ty, "()");
    }

    #[test]
    fn test_process_fn_annotations_no_attr() {
        let mut func: syn::TraitItemFn = parse_quote!(
            fn foo(&self);
        );
        let annotations = process_fn_annotations(&mut func);

        assert!(!annotations.cffi_impl_no_op);
        // ensure attribute wasn't present (and thus none removed)
        let has_func_attr = func.attrs.iter().any(|a| a.path().is_ident("func"));
        assert!(!has_func_attr);
    }

    #[test]
    fn test_process_fn_annotations_cffi_impl_no_op() {
        let mut func: syn::TraitItemFn = parse_quote!(
            #[func(cffi_impl_no_op)]
            fn foo(&self);
        );
        let annotations = process_fn_annotations(&mut func);

        assert!(annotations.cffi_impl_no_op);

        // The #[func(...)] attribute should be removed from the function
        let has_func_attr = func.attrs.iter().any(|a| a.path().is_ident("func"));
        assert!(!has_func_attr);
    }

    #[test]
    fn test_extract_supertraits_empty() {
        let trait_def: syn::ItemTrait = parse_quote!(
            trait MyTrait {}
        );
        let result = extract_supertraits(&trait_def.supertraits);
        assert!(result.is_empty());
    }

    #[test]
    fn test_extract_supertraits_single() {
        let trait_def: syn::ItemTrait = parse_quote!(
            trait MyTrait: Clone {}
        );
        let result = extract_supertraits(&trait_def.supertraits);
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].ty, "Clone");
    }

    #[test]
    fn test_extract_supertraits_multiple() {
        let trait_def: syn::ItemTrait = parse_quote!(
            trait MyTrait: Clone + Debug + Send {}
        );
        let result = extract_supertraits(&trait_def.supertraits);
        assert_eq!(result.len(), 3);
        assert_eq!(result[0].ty, "Clone");
        assert_eq!(result[1].ty, "Debug");
        assert_eq!(result[2].ty, "Send");
    }

    #[test]
    fn test_extract_supertraits_with_path() {
        let trait_def: syn::ItemTrait = parse_quote!(
            trait MyTrait: std::fmt::Debug {}
        );
        let result = extract_supertraits(&trait_def.supertraits);
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].ty, "std::fmt::Debug");
    }

    #[test]
    fn test_extract_supertraits_generic_trait() {
        let trait_def: syn::ItemTrait = parse_quote!(
            trait MyTrait: IntoIterator<Item = String> {}
        );
        let result = extract_supertraits(&trait_def.supertraits);
        assert_eq!(result.len(), 1);
        assert_eq!(result[0].ty, "IntoIterator");
        assert_eq!(result[0].generic_ty_args.len(), 1);
        assert_eq!(result[0].generic_ty_args[0].ty, "Item = String");
    }

    #[test]
    fn test_extract_supertraits_mixed_lifetimes_and_traits() {
        let trait_def: syn::ItemTrait = parse_quote!(
            trait MyTrait: 'static + Clone + Sync {}
        );
        let result = extract_supertraits(&trait_def.supertraits);
        // 'static is a lifetime bound, not a trait, so it should be filtered out
        assert_eq!(result.len(), 2);
        assert_eq!(result[0].ty, "Clone");
        assert_eq!(result[1].ty, "Sync");
    }

    #[test]
    fn test_extract_supertraits_complex() {
        let trait_def: syn::ItemTrait = parse_quote!(
            trait MyTrait: Send + Sync + std::fmt::Debug + Clone {}
        );
        let result = extract_supertraits(&trait_def.supertraits);
        assert_eq!(result.len(), 4);
        assert_eq!(result[0].ty, "Send");
        assert_eq!(result[1].ty, "Sync");
        assert_eq!(result[2].ty, "std::fmt::Debug");
        assert_eq!(result[3].ty, "Clone");
    }
}