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
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
use proc_macro::TokenStream;
use proc_macro2::Span;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use std::iter::FromIterator;
use syn::{parse_macro_input, parse_quote, Data, DeriveInput, Fields, GenericParam, Ident, Type};

#[proc_macro_derive(Value)]
pub fn value_derive(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let ident = input.ident;
    if let Data::Struct(r#struct) = input.data {
        let fields = r#struct.fields;
        if matches!(&fields, Fields::Named(_)) {
            if matches!(&fields, Fields::Named(_)) {
                let builder_set_fields = map_value_fields(&fields, |(ident, sets, ty)| {
                    if ident == "nacos" {
                        return quote!();
                    }
                    if let Some(to) = get_optional_inner_type(ty) {
                        quote!(
                            pub fn #sets(&mut self, value: &#to) {
                                self.#ident = Some(value.clone());
                            }

                            pub fn #ident(&self) -> #ty {
                                self.#ident.clone()
                            }
                        )
                    } else {
                        quote!(
                            pub fn #sets(&mut self, value: &#ty) {
                                self.#ident = value.clone();
                            }

                            pub fn #ident(&self) -> #ty {
                                self.#ident.clone()
                            }
                        )
                    }
                });
                let result = quote!(
                impl #ident {
                    #builder_set_fields
                }
                )
                .into();
                return result;
            }
        }
    }
    quote!().into()
}

#[proc_macro_derive(Builder)]
pub fn derive(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let ident = input.ident;
    let ident_builder = Ident::new(&format!("{}Builder", ident), ident.span());
    if let Data::Struct(r#struct) = input.data {
        let fields = r#struct.fields;
        if matches!(&fields, Fields::Named(_)) {
            let builder_fields = map_fields(&fields, |(ident, ty)| {
                if let Some(_) = get_optional_inner_type(ty) {
                    quote!(#ident: #ty, )
                } else {
                    quote!(#ident: Option<#ty>, )
                }
            });
            let builder_set_fields = map_fields(&fields, |(ident, ty)| {
                if let Some(to) = get_optional_inner_type(ty) {
                    quote!(pub fn #ident(mut self, value: #to) -> Self {
                        self.#ident = Some(value);
                        self
                    })
                } else {
                    quote!(pub fn #ident(mut self, value: #ty) -> Self {
                        self.#ident = Some(value);
                        self
                    })
                }
            });
            let builder_token_stream = map_fields(&fields, |(ident, ty)| {
                if let Some(_) = get_optional_inner_type(ty) {
                    quote!(
                        let #ident = self.#ident;
                    )
                } else {
                    quote!(
                        let #ident = self.#ident.ok_or(
                            format!("field \"{}\" required, but not set yet.",stringify!(#ident))
                            )?;
                    )
                }
            });
            let build_values = map_fields(&fields, |(ident, _)| quote!(#ident,));
            let result = quote!(
                impl #ident {
                    pub fn builder() -> #ident_builder {
                        #ident_builder::default()
                    }
                }

                #[derive(Default)]
                pub struct #ident_builder {
                    #builder_fields
                }

                impl #ident_builder {
                    #builder_set_fields

                    pub fn build(self) -> Result<#ident, String> {
                        #builder_token_stream

                        Ok(#ident { #build_values })
                    }
                }
            ).into();
            return result;
        }
    }
    quote!().into()
}
#[proc_macro_derive(Nacos)]
pub fn nacos_derive(item: TokenStream) -> TokenStream {
    let input = parse_macro_input!(item as DeriveInput);
    let name = input.ident;

    let mut generics = input.generics.clone();
    for param in &mut generics.params {
        if let GenericParam::Type(ref mut type_param) = *param {
            type_param.bounds.push(parse_quote!(Get));
        }
    }

    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();

    quote! (
        impl #impl_generics Nacos for #name #ty_generics #where_clause {
            fn get_token(&self) -> String {
                match self.nacos.clone() {
                    Some(n) => n.read().unwrap().clone().token.unwrap_or("".to_string()),
                    None => "".to_string(),
                }
            }
            fn get_nacos(&self) -> NacosClient {
                self.nacos.clone().unwrap().read().unwrap().clone()
            }
            fn clone_nacos(&self) -> Arc<RwLock<NacosClient>> {
                self.nacos.clone().unwrap()
            }
            fn set_nacos(&mut self, nacos: &Arc<RwLock<NacosClient>>) {
                self.nacos = Some(nacos.clone());
            }
        }
    )
    .into()
}

#[proc_macro_derive(Get)]
pub fn get_derive(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let name = input.ident;

    let mut generics = input.generics.clone();
    for param in &mut generics.params {
        if let GenericParam::Type(ref mut type_param) = *param {
            type_param.bounds.push(parse_quote!(Get));
        }
    }

    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();

    let uri = Ident::new(
        &format!("{}_URI", name.to_string().to_uppercase()),
        Span::call_site(),
    );
    quote! (
        impl #impl_generics Get for #name #ty_generics #where_clause {
            const URI: &'static str = #uri;
        }
    )
    .into()
}

#[proc_macro_derive(Post)]
pub fn post_derive(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let name = input.ident;

    let mut generics = input.generics.clone();
    for param in &mut generics.params {
        if let GenericParam::Type(ref mut type_param) = *param {
            type_param.bounds.push(parse_quote!(Post));
        }
    }

    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();

    let uri = Ident::new(
        &format!("{}_URI", name.to_string().to_uppercase()),
        Span::call_site(),
    );
    quote! (
        impl #impl_generics Post for #name #ty_generics #where_clause {
            const URI: &'static str = #uri;
        }
    )
    .into()
}

#[proc_macro_derive(Put)]
pub fn put_derive(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let name = input.ident;

    let mut generics = input.generics.clone();
    for param in &mut generics.params {
        if let GenericParam::Type(ref mut type_param) = *param {
            type_param.bounds.push(parse_quote!(Put));
        }
    }

    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();

    let uri = Ident::new(
        &format!("{}_URI", name.to_string().to_uppercase()),
        Span::call_site(),
    );
    quote! (
        impl #impl_generics Put for #name #ty_generics #where_clause {
            const URI: &'static str = #uri;
        }
    )
    .into()
}

#[proc_macro_derive(Delete)]
pub fn delete_derive(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);
    let name = input.ident;

    let mut generics = input.generics.clone();
    for param in &mut generics.params {
        if let GenericParam::Type(ref mut type_param) = *param {
            type_param.bounds.push(parse_quote!(Delete));
        }
    }

    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();

    let uri = Ident::new(
        &format!("{}_URI", name.to_string().to_uppercase()),
        Span::call_site(),
    );
    quote! (
        impl #impl_generics Delete for #name #ty_generics #where_clause {
            const URI: &'static str = #uri;
        }
    )
    .into()
}

fn map_fields<F>(fields: &Fields, mapper: F) -> TokenStream2
where
    F: FnMut((&Ident, &Type)) -> TokenStream2,
{
    TokenStream2::from_iter(
        fields
            .iter()
            .map(|field| (field.ident.as_ref().unwrap(), &field.ty))
            .map(mapper),
    )
}

fn map_value_fields<F>(fields: &Fields, mapper: F) -> TokenStream2
where
    F: FnMut((&Ident, Ident, &Type)) -> TokenStream2,
{
    TokenStream2::from_iter(
        fields
            .iter()
            .map(|field| {
                (
                    field.ident.as_ref().unwrap(),
                    Ident::new(
                        &format!("set_{}", field.ident.as_ref().unwrap().to_string()),
                        Span::call_site(),
                    ),
                    &field.ty,
                )
            })
            .map(mapper),
    )
}

fn get_optional_inner_type(ty: &syn::Type) -> Option<&syn::Type> {
    if let syn::Type::Path(syn::TypePath { ref path, .. }) = ty {
        // 这里我们取segments的最后一节来判断是不是`Option<T>`,这样如果用户写的是`std:option:Option<T>`我们也能识别出最后的`Option<T>`
        if let Some(seg) = path.segments.last() {
            if seg.ident == "Option" {
                if let syn::PathArguments::AngleBracketed(syn::AngleBracketedGenericArguments {
                    ref args,
                    ..
                }) = seg.arguments
                {
                    if let Some(syn::GenericArgument::Type(inner_ty)) = args.first() {
                        return Some(inner_ty);
                    }
                }
            }
        }
    }
    None
}