diesel_derives/
diesel_public_if.rs

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
use quote::quote;
use syn::Token;
use syn::{punctuated::Punctuated, DeriveInput};

pub(crate) fn expand(cfg: CfgInput, item: EntryWithVisibility) -> proc_macro2::TokenStream {
    item.hide_for_cfg(cfg.cfg, cfg.field_list)
}

pub struct CfgInput {
    cfg: syn::Meta,
    field_list: Vec<syn::Ident>,
}

impl syn::parse::Parse for CfgInput {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        let mut cfg = Punctuated::<syn::Meta, Token![,]>::parse_terminated(input)?;
        if cfg.len() == 1 {
            Ok(Self {
                cfg: cfg
                    .pop()
                    .expect("There is exactly one element")
                    .into_value(),
                field_list: Vec::new(),
            })
        } else if cfg.len() == 2 {
            let value_1 = cfg
                .pop()
                .expect("There is exactly one element")
                .into_value();
            let value_2 = cfg
                .pop()
                .expect("There is exactly one element")
                .into_value();
            let (cfg, fields) = if matches!(&value_1, syn::Meta::List(v) if v.path.is_ident("public_fields"))
            {
                (value_2, value_1)
            } else if matches!(&value_2, syn::Meta::List(v) if v.path.is_ident("public_fields")) {
                (value_1, value_2)
            } else {
                panic!(
                    "Incompatible argument list detected. `__diesel_public_if` \
                     expects a cfg argument and a optional public_fields"
                )
            };
            let field_list = if let syn::Meta::List(v) = fields {
                use syn::parse::Parser;
                let parser =
                    syn::punctuated::Punctuated::<syn::Ident, syn::Token![,]>::parse_terminated;
                let idents = parser.parse2(v.tokens)?;
                idents.into_iter().collect()
            } else {
                unreachable!()
            };
            Ok(Self { cfg, field_list })
        } else {
            panic!(
                "Incompatible argument list detected. `__diesel_public_if` \
                 expects a cfg argument and an optional public_fields"
            )
        }
    }
}

#[derive(Clone)]
pub enum EntryWithVisibility {
    TraitFunction {
        meta: Vec<syn::Attribute>,
        tail: proc_macro2::TokenStream,
    },
    Item {
        meta: Vec<syn::Attribute>,
        vis: syn::Visibility,
        tail: proc_macro2::TokenStream,
    },
    Struct {
        meta: Vec<syn::Attribute>,
        vis: syn::Visibility,
        def: syn::DataStruct,
        ident: syn::Ident,
        generics: syn::Generics,
    },
}

impl syn::parse::Parse for EntryWithVisibility {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        let meta = syn::Attribute::parse_outer(input)?;
        if input.peek(Token![fn]) || input.peek(Token![type]) {
            let tail = input.parse()?;
            Ok(Self::TraitFunction { meta, tail })
        } else {
            let vis = input.parse()?;
            if input.peek(Token![struct]) {
                let s = DeriveInput::parse(input)?;
                if let syn::Data::Struct(def) = s.data {
                    Ok(Self::Struct {
                        meta,
                        vis,
                        def,
                        generics: s.generics,
                        ident: s.ident,
                    })
                } else {
                    unreachable!()
                }
            } else {
                let tail = input.parse()?;
                Ok(Self::Item { meta, vis, tail })
            }
        }
    }
}

impl EntryWithVisibility {
    fn hide_for_cfg(
        &self,
        cfg: syn::Meta,
        field_list: Vec<syn::Ident>,
    ) -> proc_macro2::TokenStream {
        match self {
            EntryWithVisibility::TraitFunction { meta, tail } if field_list.is_empty() => quote! {
                #(#meta)*
                #[cfg_attr(not(#cfg), doc(hidden))]
                #[cfg_attr(docsrs, doc(cfg(#cfg)))]
                #tail
            },
            EntryWithVisibility::Item { meta, vis, tail } if field_list.is_empty() => {
                quote! {
                    #(#meta)*
                    #[cfg(not(#cfg))]
                    #vis #tail

                    #(#meta)*
                    #[cfg(#cfg)]
                    pub #tail
                }
            }
            EntryWithVisibility::Struct {
                meta,
                vis,
                def,
                ident,
                generics,
            } => {
                let fields1 = def.fields.iter();
                let fields2 = def.fields.iter().map(|f| {
                    let mut ret = f.clone();
                    if ret
                        .ident
                        .as_ref()
                        .map(|i| field_list.contains(i))
                        .unwrap_or(false)
                    {
                        ret.vis = syn::Visibility::Public(Default::default());
                    }
                    ret
                });

                quote! {
                    #(#meta)*
                    #[cfg(not(#cfg))]
                    #vis struct #ident #generics {
                        #(#fields1,)*
                    }

                    #(#meta)*
                    #[cfg(#cfg)]
                    #[non_exhaustive]
                    pub struct #ident #generics {
                        #(#fields2,)*
                    }
                }
            }
            EntryWithVisibility::TraitFunction { .. } | EntryWithVisibility::Item { .. } => {
                panic!("Public field list is only supported for structs")
            }
        }
    }
}