Skip to main content

studiole_di_macros/
lib.rs

1//! Derive macros for `studiole-di`.
2mod generate;
3mod parse;
4
5use proc_macro::TokenStream;
6use syn::parse_macro_input;
7
8/// Derive [`FromServices`] for a struct with `Arc<T>` fields.
9///
10/// Generates a sync implementation that resolves each field
11/// from the [`ServiceProvider`].
12///
13/// # Example
14///
15/// ```ignore
16/// #[derive(FromServices)]
17/// pub struct Database {
18///     config: Arc<Config>,
19/// }
20/// ```
21#[proc_macro_derive(FromServices, attributes(di))]
22pub fn derive_from_services(input: TokenStream) -> TokenStream {
23    let input = parse_macro_input!(input as syn::DeriveInput);
24    match parse::parse_struct(&input) {
25        Ok(parsed) => generate::generate_sync(&parsed).into(),
26        Err(err) => err.to_compile_error().into(),
27    }
28}
29
30/// Derive [`FromServicesAsync`] for a struct with `Arc<T>` fields.
31///
32/// Generates an async implementation that resolves each field
33/// from the [`ServiceProvider`].
34///
35/// # Example
36///
37/// ```ignore
38/// #[derive(FromServicesAsync)]
39/// pub struct AsyncDatabase {
40///     config: Arc<Config>,
41/// }
42/// ```
43#[proc_macro_derive(FromServicesAsync, attributes(di))]
44pub fn derive_from_services_async(input: TokenStream) -> TokenStream {
45    let input = parse_macro_input!(input as syn::DeriveInput);
46    match parse::parse_struct(&input) {
47        Ok(parsed) => generate::generate_async(&parsed).into(),
48        Err(err) => err.to_compile_error().into(),
49    }
50}
51
52#[cfg(test)]
53mod tests;