custom_attrs 1.5.3

A library that allows you to configure values specific to each variants of an enum.
Documentation
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
use std::collections::HashMap;

use proc_macro2::Ident;
use proc_macro_error::{abort, abort_if_dirty, emit_error};
use quote::{format_ident, quote, ToTokens};
use syn::{
    parenthesized,
    parse::Parse,
    punctuated::Punctuated,
    token::{self, Comma},
    DataEnum, DeriveInput, Expr, Token, Type, Variant, Visibility, LitStr,
};

use crate::{
    config::{Config, ConfigDeclarationList},
    opt::{extract_type_from_option, is_option_wrapped},
    value::{IdentValueAssignment, ValueAssignment},
};

macro_rules! error_duplicate {
    ($span1: expr, $error1: expr $(, $error1fragments: expr)*;
     $span2: expr, $error2: expr $(, $error2fragments: expr)*) => {
        cfg_if::cfg_if! {
            if #[cfg(help_span)] {
                emit_error!(
                    $span1, $error1 $(, $error1fragments)*;
                    help = $span2 => $error2 $(, $error2fragments)*
                );
            } else {
                emit_error!($span1, $error1 $(, $error1fragments)*);
                emit_error!($span2, $error2 $(, $error2fragments)*);
            }
        }
    };
}

pub(crate) use error_duplicate;

macro_rules! unwrap_opt_or_continue {
    ($expr: expr) => {{
        let res = $expr;
        if res.is_none() {
            continue;
        }
        res.unwrap()
    }};
}

struct ParenList<T> {
    _paren: token::Paren,
    elements: Punctuated<T, Comma>,
}

impl<T: Parse> Parse for ParenList<T> {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        let content;

        Ok(Self {
            _paren: parenthesized!(content in input),
            elements: content.parse_terminated(T::parse)?,
        })
    }
}

struct AttributeDeclaration {
    attributes: Vec<ConfigDeclarationList>,
    vis: Visibility,
    ident: Ident,
    _colon: Token!(:),
    type_: Type,
    default_value: Option<ValueAssignment>,
}

impl Parse for AttributeDeclaration {
    fn parse(input: syn::parse::ParseStream) -> syn::Result<Self> {
        Ok(Self {
            attributes: input.call(ConfigDeclarationList::parse_all)?,
            vis: input.parse()?,
            ident: input.parse()?,
            _colon: input.parse()?,
            type_: {
                let res = input.parse();
                if let Err(e) = res {
                    let err = syn::Error::new(e.span(), "Expected a type.");
                    return Err(err);
                }
                res.unwrap()
            },
            default_value: input.parse()?,
        })
    }
}

struct AttributeValue<'f> {
    variant: &'f Variant,
    value: Option<Expr>,
    type_state: TypeState,
}

impl<'f> AttributeValue<'f> {
    pub fn new(field_ident: &'f Variant, type_state: TypeState) -> Self {
        Self {
            variant: field_ident,
            value: None,
            type_state,
        }
    }
}

impl<'f> ToTokens for AttributeValue<'f> {
    fn to_tokens(&self, tokens2: &mut proc_macro2::TokenStream) {
        if self.value.is_none() {
            return proc_macro2::TokenStream::new().to_tokens(tokens2);
        }

        let ident = &self.variant.ident;
        let fields = match self.variant.fields {
            syn::Fields::Named(ref named) => {
                let new_named = named.named.iter()
                    .map(|n| n.ident.as_ref().unwrap());

                quote!({#(#new_named: _),*})
            },
            syn::Fields::Unnamed(ref unnamed) => {
                let new_named = unnamed.unnamed.iter()
                    .enumerate()
                    .map(|(i, _)| {
                        Some(format_ident!("_{}", i))
                    });

                quote!((#(#new_named),*))
            },
            syn::Fields::Unit => quote!(),
        };

        let value = self.value.as_ref().unwrap();

        let value = match self.type_state {
            TypeState::Required(_) => quote!(#value),
            TypeState::Optional(_) => {
                if is_option_wrapped(value) {
                    quote!(#value)
                } else {
                    quote!(Some(#value))
                }
            }
        };

        let tokens = quote! {
            if let Self::#ident #fields = self {
                return #value
            }
        };

        tokens.to_tokens(tokens2)
    }
}

#[derive(Clone)]
enum TypeState {
    Required(Type),
    Optional(Type),
}

struct Attribute<'f> {
    vis: Visibility,
    ident: Ident,
    type_: TypeState,
    values: Vec<AttributeValue<'f>>,
    default: Option<Expr>,
    config: Config,
}

impl<'f> Attribute<'f> {
    fn new(declaration: AttributeDeclaration, variants: &'f Punctuated<Variant, Comma>) -> Self {
        let type_ = declaration.type_;
        let type_state = match extract_type_from_option(&type_) {
            Some(type_) => TypeState::Optional(type_.to_owned()),
            None => TypeState::Required(type_),
        };

        let values = variants
            .iter()
            .map(|f| AttributeValue::new(&f, type_state.to_owned()))
            .collect();

        let config = Config::new(declaration.attributes);

        Self {
            vis: declaration.vis,
            ident: declaration.ident,
            type_: type_state,
            values,
            default: declaration
                .default_value
                .map(|default| default.value().to_owned()),
            config,
        }
    }

    fn set(&mut self, ident: &Ident, value: IdentValueAssignment) {
        let attr_value = self
            .values
            .iter_mut()
            .find(|p| &p.variant.ident == ident)
            .expect("tried to set a value for a variant that doesn't exists.");

        match attr_value.value {
            None => attr_value.value = Some(value.value().to_owned()),
            Some(ref value2) => {
                error_duplicate!(
                    value, "The value is already set for this attribute.";
                    value2, "First value of `{}` is set here.", self.ident
                );
            }
        }
    }

    fn check(&self) {
        if self.default.is_some() {
            return;
        }
        if let TypeState::Optional(_) = self.type_ {
            return;
        }

        for value in &self.values {
            if value.value.is_none() {
                emit_error!(
                    value.variant.ident,
                    format!("Value not set for `{}`.", self.ident)
                );
            }
        }
    }
}

impl<'f> ToTokens for Attribute<'f> {
    fn to_tokens(&self, tokens2: &mut proc_macro2::TokenStream) {
        let function_name = self.config.function_name().unwrap_or(format_ident!("get_{}", self.ident));

        let vis = &self.vis;
        let type_ = match &self.type_ {
            TypeState::Required(type_) => quote!(#type_),
            TypeState::Optional(type_) => quote!(Option<#type_>),
        };
        let values = &self.values;

        let default = match &self.default {
            Some(value) => {
                let mut tokens = quote!(#value);
                if let TypeState::Optional(_) = self.type_ {
                    if !is_option_wrapped(value) {
                        tokens = quote!(Some(#value))
                    }
                }
                tokens
            }
            None => {
                if let TypeState::Optional(_) = self.type_ {
                    quote!(None)
                } else {
                    quote!(unreachable!())
                }
            }
        };

        let comment = self.config.comment();

        let tokens = quote! {
            #[doc = #comment]
            #vis fn #function_name(&self) -> #type_ {
                #(#values)*

                #default
            }
        };

        tokens.to_tokens(tokens2)
    }
}

fn parse_enum_attributes<'f>(
    attrs: &[syn::Attribute],
    data_enum: &'f DataEnum,
) -> Vec<Attribute<'f>> {
    let mut attribute_declarations = Vec::<AttributeDeclaration>::new();

    for attr in attrs.iter() {
        let attr_ident = unwrap_opt_or_continue!(attr.path.get_ident());

        match attr_ident.to_string().as_str() {
            "attr" => {
                let res = syn::parse2(attr.tokens.to_owned());
                if let Err(e) = res {
                    emit_error!(e.span(), e);
                    continue;
                }

                let declaration_list: ParenList<AttributeDeclaration> = res.unwrap();

                for declaration in declaration_list.elements {
                    let match_ = attribute_declarations
                        .iter()
                        .find(|attr2| declaration.ident == attr2.ident);

                    if let Some(declaration2) = match_ {
                        error_duplicate!(
                            declaration.ident, "This attribute is already declared.";
                            declaration2.ident, "`{}` is already declared here.", declaration2.ident
                        );

                        continue;
                    }

                    attribute_declarations.push(declaration);
                }
            }

            _ => continue,
        }
    }

    attribute_declarations
        .into_iter()
        .map(|decl| Attribute::new(decl, &data_enum.variants))
        .collect()
}

fn parse_variant_attributes(variant: &Variant) -> Vec<IdentValueAssignment> {
    let mut variant_attrs = Vec::new();

    for attr in &variant.attrs {
        let attr_ident = unwrap_opt_or_continue!(attr.path.get_ident());

        match attr_ident.to_string().as_str() {
            "attr" => {
                let res = syn::parse2(attr.tokens.to_owned());
                if let Err(e) = res {
                    emit_error!(e.span(), e);
                    continue;
                }

                let list: ParenList<IdentValueAssignment> = res.unwrap();

                variant_attrs.extend(list.elements.into_iter());
            }
            _ => continue,
        }
    }

    variant_attrs
}

fn check_for_conflicts(attrs: &[Attribute]) {
    let mut before = HashMap::<&LitStr, &Attribute>::new();
    for attr in attrs.iter().filter(|a| a.config.function_name_lit().is_some()) {
        let lit = attr.config.function_name_lit().unwrap();
        
        if let Some((lit2, attr2)) = before.get_key_value(lit) {
            error_duplicate!(
                lit, "The attribute `{}` already use this function name.", attr2.ident;
                lit2, "First use of `{}` here.", lit.value()
            );

            continue;
        }

        before.insert(lit, attr);
    }
}

pub fn derive_custom_attrs(input: DeriveInput) -> proc_macro2::TokenStream {
    let data_enum = match input.data {
        syn::Data::Struct(struct_) => abort!(struct_.struct_token, "Not implemented for structs."),
        syn::Data::Union(union_) => abort!(union_.union_token, "Not implemented for unions."),

        syn::Data::Enum(ref data_enum) => data_enum,
    };

    let mut attributes = parse_enum_attributes(&input.attrs, data_enum);

    abort_if_dirty();

    for variant in &data_enum.variants {
        let variant_attrs = parse_variant_attributes(variant);

        for attr in variant_attrs {
            let opt = attributes
                .iter_mut()
                .find(|attr2| &attr2.ident == attr.ident());

            if opt.is_none() {
                emit_error!(attr.ident(), "Unknown attribute.");
                continue;
            }

            opt.unwrap().set(&variant.ident, attr)
        }
    }

    for attr in attributes.iter() {
        attr.check();
    }

    abort_if_dirty();

    check_for_conflicts(&attributes);

    abort_if_dirty();

    let ident = &input.ident;
    let (impl_generics, generics, generic_where) = input.generics.split_for_impl();

    quote! {
        impl #impl_generics #ident #generics #generic_where {
            #(#attributes)*
        }
    }
}