eventually_macros/lib.rs
1//! `eventually-macros` contains useful macros that provides
2//! different implementations of traits and functionalities from [eventually].
3
4#![deny(unsafe_code, unused_qualifications, trivial_casts, missing_docs)]
5#![deny(clippy::all, clippy::pedantic, clippy::cargo)]
6
7use proc_macro::TokenStream;
8use quote::quote;
9use syn::punctuated::Punctuated;
10use syn::{parse_macro_input, Fields, ItemStruct, Token, Type};
11
12/// Implements a newtype to use the [`eventually::aggregate::Root`] instance with
13/// user-defined [`eventually::aggregate::Aggregate`] types.
14///
15/// # Context
16///
17/// The eventually API uses [`aggregate::Root`][eventually::aggregate::Root]
18/// to manage the versioning and list of events to commit for an `Aggregate` instance.
19/// Domain commands are to be implemented on the `aggregate::Root<T>` instance, as it gives
20/// access to use `Root<T>.record_that` or `Root<T>.record_new` to record Domain Events.
21///
22/// However, it's not possible to use `impl aggregate::Root<MyAggregateType>` (`MyAggregateType`
23/// being an example of user-defined `Aggregate` type) outside the `eventually` crate (E0116).
24/// Therefore, a newtype that uses `aggregate::Root<T>` is required.
25///
26/// This attribute macro makes the implementation of a newtype easy, as it implements
27/// conversion traits from and to `aggregate::Root<T>` and implements automatic deref
28/// through [`std::ops::Deref`] and [`std::ops::DerefMut`].
29///
30/// # Panics
31///
32/// This method will panic if the Aggregate Root type is not provided as a macro parameter.
33#[proc_macro_attribute]
34pub fn aggregate_root(args: TokenStream, item: TokenStream) -> TokenStream {
35 let mut item = parse_macro_input!(item as ItemStruct);
36 let item_ident = item.ident.clone();
37
38 let aggregate_type: Type =
39 parse_macro_input!(args with Punctuated::<Type, Token![,]>::parse_terminated)
40 .into_iter()
41 .next()
42 .expect("the aggregate root type must be provided as macro parameter");
43
44 item.fields = Fields::Unnamed(
45 syn::parse2(quote! { (eventually::aggregate::Root<#aggregate_type>) }).unwrap(),
46 );
47
48 let result = quote! {
49 #item
50
51 impl std::ops::Deref for #item_ident {
52 type Target = eventually::aggregate::Root<#aggregate_type>;
53
54 fn deref(&self) -> &Self::Target {
55 &self.0
56 }
57 }
58
59 impl std::ops::DerefMut for #item_ident {
60 fn deref_mut(&mut self) -> &mut Self::Target {
61 &mut self.0
62 }
63 }
64
65 impl From<eventually::aggregate::Root<#aggregate_type>> for #item_ident {
66 fn from(root: eventually::aggregate::Root<#aggregate_type>) -> Self {
67 Self(root)
68 }
69 }
70
71 impl From<#item_ident> for eventually::aggregate::Root<#aggregate_type> {
72 fn from(value: #item_ident) -> Self {
73 value.0
74 }
75 }
76 };
77
78 result.into()
79}