summaryrefslogtreecommitdiffstats
path: root/third_party/rust/derive_more/src/deref.rs
blob: c7a8008cbd9d77ebc28b04a92ffbe4f5f007220f (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
use crate::utils::{SingleFieldData, State};
use proc_macro2::TokenStream;
use quote::quote;
use syn::{parse::Result, DeriveInput};

/// Provides the hook to expand `#[derive(Deref)]` into an implementation of `Deref`
pub fn expand(input: &DeriveInput, trait_name: &'static str) -> Result<TokenStream> {
    let state = State::with_field_ignore_and_forward(
        input,
        trait_name,
        quote!(::core::ops),
        trait_name.to_lowercase(),
    )?;
    let SingleFieldData {
        input_type,
        field_type,
        trait_path,
        casted_trait,
        impl_generics,
        ty_generics,
        where_clause,
        member,
        info,
        ..
    } = state.assert_single_enabled_field();

    let (target, body) = if info.forward {
        (
            quote!(#casted_trait::Target),
            quote!(#casted_trait::deref(&#member)),
        )
    } else {
        (quote!(#field_type), quote!(&#member))
    };

    Ok(quote! {
        impl#impl_generics #trait_path for #input_type#ty_generics #where_clause
        {
            type Target = #target;
            #[inline]
            fn deref(&self) -> &Self::Target {
                #body
            }
        }
    })
}