rustantic_macros/lib.rs
1#[allow(unused_imports)]
2use proc_macro::TokenStream;
3use quote::quote;
4use syn::{parse_macro_input, Item};
5
6#[proc_macro_attribute]
7pub fn pydantic(_attr: TokenStream, item: TokenStream) -> TokenStream {
8 let input = parse_macro_input!(item as Item);
9 let output = match input {
10 // If the input is a struct, add #[pyclass] and do any modifications you need.
11 Item::Struct(item_struct) => {
12 // Optionally check if #[pyclass] is already present and add it if not.
13 // For simplicity, we just inject #[pyclass] before the struct.
14 quote! {
15 #[pyclass]
16 #item_struct
17 }
18 }
19 // If the input is an enum, process it accordingly.
20 Item::Enum(item_enum) => {
21 // For enums, you might not need #[pyclass] (depending on your design),
22 // but you could also register it for code-generation purposes.
23 // Here we simply return the enum unmodified.
24 quote! {
25 #[pyclass]
26 #[derive(PartialEq)]
27 #item_enum
28 }
29 }
30 // For any other item types, produce a compile error.
31 _ => {
32 return syn::Error::new_spanned(
33 input,
34 "The #[my_pydantic] attribute can only be used on structs or enums.",
35 )
36 .to_compile_error()
37 .into();
38 }
39 };
40
41 output.into()
42}