rngpui_craby_macro/
lib.rs1use proc_macro::TokenStream;
2use quote::quote;
3use syn::{parse_macro_input, parse_quote, ImplItem, ItemImpl};
4
5#[proc_macro_attribute]
6pub fn craby_module(_attr: TokenStream, item: TokenStream) -> TokenStream {
7 let mut input = parse_macro_input!(item as ItemImpl);
8
9 let has_new = input
10 .items
11 .iter()
12 .any(|item| matches!(item, ImplItem::Fn(method) if method.sig.ident == "new"));
13
14 let has_id = input
15 .items
16 .iter()
17 .any(|item| matches!(item, ImplItem::Fn(method) if method.sig.ident == "id"));
18
19 if !has_new {
20 let new_method: ImplItem = parse_quote! {
21 fn new(ctx: Context) -> Self {
22 Self { ctx }
23 }
24 };
25 input.items.push(new_method);
26 }
27
28 if !has_id {
29 let id_method: ImplItem = parse_quote! {
30 fn id(&self) -> usize {
31 self.ctx.id
32 }
33 };
34 input.items.push(id_method);
35 }
36
37 TokenStream::from(quote! { #input })
38}