karyon_eventemitter_macro/lib.rs
1use proc_macro::TokenStream;
2use quote::quote;
3use syn::{parse_macro_input, DeriveInput};
4
5/// Derive macro for the AsEventValue trait
6///
7/// This macro implements AsEventValue for structs and enums,
8/// using either the type name as the event_id or by passing a custom event_id.
9///
10/// # Example
11///
12/// ```compile_fail;
13///
14/// #[derive(EventValue)]
15/// struct MyEvent {
16/// data: String,
17/// }
18///
19/// // impl AsEventValue for MyEvent {
20/// // fn event_id() -> &'static str {
21/// // "MyEvent"
22/// // }
23/// // }
24///
25/// #[derive(EventValue)]
26/// #[event_id("custom_event_name")]
27/// struct MyEvent2 {
28/// data: String,
29/// }
30///
31/// // impl AsEventValue for MyEvent2 {
32/// // fn event_id() -> &'static str {
33/// // "custom_event_name"
34/// // }
35/// // }
36///
37/// ```
38#[proc_macro_derive(EventValue, attributes(event_id))]
39pub fn derive_event_value(input: TokenStream) -> TokenStream {
40 let input = parse_macro_input!(input as DeriveInput);
41
42 let name = &input.ident;
43
44 let event_id = input
45 .attrs
46 .iter()
47 .find(|attr| attr.path().is_ident("event_id"))
48 .and_then(|attr| attr.parse_args::<syn::LitStr>().ok().map(|lit| lit.value()))
49 .unwrap_or_else(|| name.to_string());
50
51 let expanded = quote! {
52 impl karyon_eventemitter::AsEventValue for #name {
53 fn event_id() -> &'static str {
54 #event_id
55 }
56 }
57 };
58
59 TokenStream::from(expanded)
60}