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
use syn::DeriveInput;
#[cfg(feature="debug_parameters")]
use syn::Meta;
#[cfg(feature="debug_parameters")]
use proc_macro2::Span;

#[cfg(feature="debug_parameters")]
fn debug_as_string(ast: &DeriveInput) -> bool{
    ast.attrs.iter()
        .find(|attr| attr.parse_meta().ok().map(|meta| match meta {
            Meta::Path(ref path) if path.is_ident("debug_as_string") => true,
            _ => false,
        }).unwrap_or(false)).is_some()
}

#[cfg(feature="debug_parameters")]
fn debug_custom(ast: &DeriveInput) -> bool{
    ast.attrs.iter()
        .find(|attr| attr.parse_meta().ok().map(|meta| match meta {
            Meta::Path(ref path) if path.is_ident("debug_custom") => true,
            _ => false,
        }).unwrap_or(false)).is_some()
}

#[cfg(feature="debug_parameters")]
pub fn impl_debug_parameter(ast: &DeriveInput) -> proc_macro2::TokenStream {
    let name = &ast.ident;
    let (_, ty_generics, where_clause) = ast.generics.split_for_impl();
    let mut generics_params = ast.generics.clone();
    generics_params.params.push(syn::GenericParam::Lifetime(syn::LifetimeDef::new(syn::Lifetime::new("'a", Span::call_site()))));
    let (impl_generics_params, _, _) = generics_params.split_for_impl();
    let crate_name = match super::rinecs_crate_name(){
        Ok(crate_name) => crate_name,
        Err(err) => return err.to_compile_error(),
    };

    if debug_as_string(&ast) {
        quote! {
            impl #impl_generics_params #crate_name::DebugParameter for #name #ty_generics #where_clause {
                fn debug<S: serde::Serializer>(&self, serializer: S) -> std::result::Result<<S as serde::Serializer>::Ok, <S as serde::Serializer>::Error>{
                    use serde::Serialize;
                    format!("{:#?}", self).serialize(serializer)
                }
            }
        }
    }else if !debug_custom(&ast){
        quote! {
            impl #impl_generics_params #crate_name::DebugParameter for #name #ty_generics #where_clause {
                fn debug<S: serde::Serializer>(&self, serializer: S) -> std::result::Result<<S as serde::Serializer>::Ok, <S as serde::Serializer>::Error>{
                    use serde::Serialize;
                    self.serialize(serializer)
                }
            }
        }
    }else{
        quote!{}
    }
}

#[cfg(not(feature="debug_parameters"))]
pub fn impl_debug_parameter(_: &DeriveInput) -> proc_macro2::TokenStream {
    quote!{}
}