deref_derives/lib.rs
1use proc_macro::TokenStream;
2use syn::parse_macro_input;
3
4mod deref;
5
6/// Derive macro to implement the Deref trait
7///
8/// Use the `#[auto_ref]` attribute to mark the field to implement Deref for
9///
10/// # Examples
11/// ```rust
12/// use deref_derives::Deref;
13///
14/// #[derive(Deref)]
15/// struct Hello<T> {
16/// #[auto_ref]
17/// inner: T,
18/// }
19/// ```
20#[proc_macro_derive(Deref, attributes(auto_ref))]
21pub fn derive_deref(input: TokenStream) -> TokenStream {
22 let input = parse_macro_input!(input as syn::DeriveInput);
23
24 match deref::impl_deref_trait(&input, false) {
25 Ok(tokens) => tokens.into(),
26 Err(err) => err.to_compile_error().into(),
27 }
28}
29
30/// Derive macro to implement the DerefMut trait
31///
32/// Use the `#[auto_ref]` attribute to mark the field to implement DerefMut for
33///
34/// Note: This macro automatically implements both Deref and DerefMut traits.
35/// You don't need to separately derive Deref when using DerefMut.
36///
37/// # Examples
38/// ```rust
39/// use deref_derives::DerefMut;
40///
41/// #[derive(DerefMut)]
42/// struct HelloMut<T> {
43/// #[auto_ref]
44/// inner: T,
45/// }
46/// // The above automatically implements both Deref and DerefMut
47/// ```
48#[proc_macro_derive(DerefMut, attributes(auto_ref))]
49pub fn derive_deref_mut(input: TokenStream) -> TokenStream {
50 let input = parse_macro_input!(input as syn::DeriveInput);
51
52 match deref::impl_deref_trait(&input, true) {
53 Ok(tokens) => tokens.into(),
54 Err(err) => err.to_compile_error().into(),
55 }
56}