From fbb5847fa3e6370c5fe4ff2bde33d60b6772b85f Mon Sep 17 00:00:00 2001 From: Jonathan Irhodia Date: Tue, 3 Sep 2024 04:37:44 +0100 Subject: [PATCH] feat: app state derive macro (#180) --- crates/macros/src/common/mod.rs | 1 + crates/macros/src/common/state.rs | 19 +++++++++++++++++++ crates/macros/src/lib.rs | 14 ++++++++++++++ 3 files changed, 34 insertions(+) create mode 100644 crates/macros/src/common/state.rs diff --git a/crates/macros/src/common/mod.rs b/crates/macros/src/common/mod.rs index 480db3ff..122ec233 100644 --- a/crates/macros/src/common/mod.rs +++ b/crates/macros/src/common/mod.rs @@ -5,3 +5,4 @@ pub mod inject; pub mod injectable; pub mod route; pub mod routes; +pub mod state; diff --git a/crates/macros/src/common/state.rs b/crates/macros/src/common/state.rs new file mode 100644 index 00000000..b9fc26c9 --- /dev/null +++ b/crates/macros/src/common/state.rs @@ -0,0 +1,19 @@ +use proc_macro::TokenStream; + +pub(crate) fn derive_app_state_macro(input: TokenStream) -> TokenStream { + let input = syn::parse_macro_input!(input as syn::ItemStruct); + let name = &input.ident; + let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); + + let expanded = quote::quote! { + impl shared::server::context::AppState for #name #impl_generics #ty_generics #where_clause { + fn as_any(&self) -> &dyn std::any::Any { + self + } + fn as_any_mut(&mut self) -> &mut dyn std::any::Any { + self + } + } + }; + TokenStream::from(expanded) +} diff --git a/crates/macros/src/lib.rs b/crates/macros/src/lib.rs index f22dee9a..52c79bb6 100644 --- a/crates/macros/src/lib.rs +++ b/crates/macros/src/lib.rs @@ -387,3 +387,17 @@ pub fn query_derive_macro(input: TokenStream) -> TokenStream { pub fn param_derive_macro(input: TokenStream) -> TokenStream { param_macro(input) } + +#[proc_macro_derive(AppState)] +/// The `AppState` derive macro is used to derive a struct that can be used as a state in a server. +/// +/// ### Example +/// ```rust ignore +/// #[derive(AppState)] +/// struct MyState { +/// // fields +/// } +/// ``` +pub fn app_state_derive_macro(input: TokenStream) -> TokenStream { + common::state::derive_app_state_macro(input) +}