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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
use proc_macro::TokenStream;
use quote::{format_ident, quote, quote_spanned, spanned::Spanned};

/// Helper macro to bail out of the macro with a compile error.
macro_rules! throw {
    ($hasSpan:expr, $err:literal) => {
        let span = $hasSpan.__span();
        return quote_spanned!(span =>
            compile_error!($err);
        ).into();
    };
}

/// Returns whether or not the passed-in attribute is a simple attribute with no arguments with a
/// name that matches `name`.
fn is_simple_named_attr(attr: &venial::Attribute, name: &str) -> bool {
    attr.get_single_path_segment() == Some(&format_ident!("{name}"))
        && attr.get_value_tokens().is_empty()
}

/// Derive macro for deriving [`Deref`] on structs with one field.
#[proc_macro_derive(Deref, attributes(deref))]
pub fn derive_deref(input: TokenStream) -> TokenStream {
    let input = venial::parse_declaration(input.into()).unwrap();

    if let Some(s) = input.as_struct() {
        let name = &s.name;
        let params = &s.generic_params;

        match &s.fields {
            venial::StructFields::Tuple(tuple) => {
                if tuple.fields.len() != 1 {
                    throw!(tuple, "May only derive Deref for structs with one field.");
                }

                let deref_type = &tuple.fields[0].0.ty;

                quote! {
                    impl #params ::std::ops::Deref for #name #params {
                        type Target = #deref_type;

                        fn deref(&self) -> &Self::Target {
                            &self.0
                        }
                    }
                }
                .into()
            }
            venial::StructFields::Named(named) => {
                let (deref_type, field_name) = if named.fields.is_empty() {
                    throw!(named, "May not derive Deref for struct without fields");
                } else if named.fields.len() > 1 {
                    let mut info = None;
                    for (field, _) in named.fields.iter() {
                        for attr in &field.attributes {
                            if is_simple_named_attr(attr, "deref") {
                                if info.is_some() {
                                    throw!(attr, "Only one field may have the #[deref] attribute");
                                } else {
                                    info = Some((&field.ty, &field.name));
                                }
                            }
                        }
                    }

                    if let Some(info) = info {
                        info
                    } else {
                        throw!(
                            named,
                            "One field must be annotated with a #[deref] attribute"
                        );
                    }
                } else {
                    (&named.fields[0].0.ty, &named.fields[0].0.name)
                };

                quote! {
                    impl #params ::std::ops::Deref for #name #params {
                        type Target = #deref_type;

                        fn deref(&self) -> &Self::Target {
                            &self.#field_name
                        }
                    }
                }
                .into()
            }
            venial::StructFields::Unit => {
                throw!(s, "Cannot derive Deref on anything but structs.");
            }
        }
    } else {
        throw!(input, "Cannot derive Deref on anything but structs.");
    }
}

/// Derive macro for deriving [`DerefMut`] on structs with one field.
#[proc_macro_derive(DerefMut, attributes(deref))]
pub fn derive_deref_mut(input: TokenStream) -> TokenStream {
    let input = venial::parse_declaration(input.into()).unwrap();

    if let Some(s) = input.as_struct() {
        let name = &s.name;
        let params = &s.generic_params;

        match &s.fields {
            venial::StructFields::Tuple(tuple) => {
                if tuple.fields.len() != 1 {
                    throw!(
                        tuple,
                        "May only derive DerefMut for structs with one field."
                    );
                }

                quote! {
                    impl #params std::ops::DerefMut for #name #params {
                        fn deref_mut(&mut self) -> &mut Self::Target {
                            &mut self.0
                        }
                    }
                }
                .into()
            }
            venial::StructFields::Named(named) => {
                let field_name = if named.fields.is_empty() {
                    throw!(named, "May not derive Deref for struct without fields");
                } else if named.fields.len() > 1 {
                    let mut info = None;
                    for (field, _) in named.fields.iter() {
                        for attr in &field.attributes {
                            if is_simple_named_attr(attr, "deref") {
                                if info.is_some() {
                                    throw!(attr, "Only one field may have the #[deref] attribute");
                                } else {
                                    info = Some(&field.name);
                                }
                            }
                        }
                    }

                    if let Some(name) = info {
                        name
                    } else {
                        throw!(
                            named,
                            "One field must be annotated with a #[deref] attribute"
                        );
                    }
                } else {
                    &named.fields[0].0.name
                };

                quote! {
                    impl #params std::ops::DerefMut for #name #params {
                        fn deref_mut(&mut self) -> &mut Self::Target {
                            &mut self.#field_name
                        }
                    }
                }
                .into()
            }
            venial::StructFields::Unit => {
                throw!(s, "Cannot derive DerefMut on anything but structs.");
            }
        }
    } else {
        throw!(input, "Cannot derive DerefMut on anything but structs.");
    }
}