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
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
//! `#[derive(ParseAttrs)]` proc macro implementation.

use std::{collections::HashSet, convert::TryFrom, iter};

use proc_macro2::{Span, TokenStream};
use quote::{quote, ToTokens, TokenStreamExt as _};
use syn::{
    parse::{Parse, ParseStream},
    token,
};

use crate::{
    ext::{Data as _, Ident as _},
    parse::{
        attrs::{
            dedup,
            field::TryMerge as _,
            kind,
            validate::{rule, Validate as _},
        },
        err,
        ext::ParseBuffer as _,
    },
    ParseAttrs, Required, Spanning,
};

/// Name of the derived trait.
const TRAIT_NAME: &str = "ParseAttrs";

/// Name of the helper attribute of this `proc_macro_derive`.
const ATTR_NAME: &str = "parse";

/// Expands `#[derive(ParseAttrs)]` proc macro.
///
/// # Errors
///
/// - If the proc macro isn't applied to a struct.
/// - If parsing `#[parse]` helper attribute fails.
pub fn derive(input: syn::DeriveInput) -> syn::Result<TokenStream> {
    if !matches!(&input.data, syn::Data::Struct(_)) {
        return Err(syn::Error::new_spanned(
            input,
            format!("only structs can derive {}", TRAIT_NAME),
        ));
    }

    let out = Definition {
        ty: input.ident,
        generics: input.generics,
        fields: input
            .data
            .named_fields()?
            .into_iter()
            .map(Field::try_from)
            .collect::<syn::Result<Vec<_>>>()?,
    };

    let impl_syn_parse = out.impl_syn_parse();
    let impl_parse_attrs = out.impl_parse_attrs();
    Ok(quote! {
        #impl_syn_parse
        #impl_parse_attrs
    })
}

/// Representation of a struct implementing [`ParseAttrs`], used for code
/// generation.
#[derive(Debug)]
struct Definition {
    /// [`syn::Ident`] of this structure's type.
    ty: syn::Ident,

    /// [`syn::Generics`] of this structure's type.
    generics: syn::Generics,

    /// [`Fields`] of this structure to generate code for.
    fields: Vec<Field>,
}

impl Definition {
    /// Generates implementation of [`syn::parse::Parse`] trait for this struct.
    #[must_use]
    fn impl_syn_parse(&self) -> TokenStream {
        let ty = &self.ty;
        let (impl_generics, ty_generics, where_clause) =
            self.generics.split_for_impl();

        let parse_arms = self.fields.iter().map(|f| {
            let field = &f.ident;
            let ty = &f.ty;
            let kind = f.kind;
            let dedup = f.dedup;
            let arg_lits = &f.names;

            let val_ty = quote! {
                <#ty as ::synthez::field::Container<_>>::Value
            };

            let code = match kind {
                Kind::Ident => quote! {
                    <#ty as ::synthez::parse::attrs::field::TryApply<
                        _, #kind, #dedup,
                    >>::try_apply(&mut out.#field, input.parse::<#val_ty>()?)?;
                },
                Kind::Nested => quote! {
                    ::synthez::ParseBufferExt::skip_any_ident(input)?;
                    let inner;
                    let _ = ::synthez::syn::parenthesized!(inner in input);
                    <#ty as ::synthez::parse::attrs::field::TryApply<
                        _, #kind, #dedup,
                    >>::try_apply(
                        &mut out.#field,
                        ::synthez::Spanning::new(inner.parse()?, &ident),
                    )?;
                },
                Kind::Value(spaced) => {
                    let method = syn::Ident::new_on_call_site(if spaced {
                        "parse_maybe_wrapped_and_punctuated"
                    } else {
                        "parse_eq_or_wrapped_and_punctuated"
                    });

                    quote! {
                        ::synthez::ParseBufferExt::skip_any_ident(input)?;
                        for v in ::synthez::ParseBufferExt::#method::<
                            #val_ty,
                            ::synthez::syn::token::Paren,
                            ::synthez::syn::token::Comma,
                        >(input)? {
                            <#ty as ::synthez::parse::attrs::field::TryApply<
                                _, #kind, #dedup,
                            >>::try_apply(&mut out.#field, v)?;
                        }
                    }
                }
                Kind::Map => quote! {
                    ::synthez::ParseBufferExt::skip_any_ident(input)?;
                    let k = input.parse()?;
                    input.parse::<::synthez::syn::token::Eq>()?;
                    let v = input.parse()?;
                    <#ty as ::synthez::parse::attrs::field::TryApply<
                        (_, _), #kind, #dedup,
                    >>::try_apply(&mut out.#field, (k, v))?;
                },
            };

            quote! {
                #( #arg_lits )|* => { #code },
            }
        });

        quote! {
            #[automatically_derived]
            impl#impl_generics ::synthez::syn::parse::Parse for #ty#ty_generics
                #where_clause
            {
                fn parse(
                    input: ::synthez::syn::parse::ParseStream<'_>,
                ) -> ::synthez::syn::Result<Self> {
                    let mut out = <#ty#ty_generics as Default>::default();
                    while !input.is_empty() {
                        let ident =
                            ::synthez::ParseBufferExt::parse_any_ident(
                                &input.fork(),
                            )?;
                        match ident.to_string().as_str() {
                            #( #parse_arms )*
                            name => {
                                return Err(::synthez::parse::err::
                                    unknown_attr_arg(&ident, name));
                            },
                        }
                        if ::synthez::ParseBufferExt::try_parse::<
                            ::synthez::syn::token::Comma,
                        >(input)?.is_none() && !input.is_empty() {
                            return Err(::synthez::parse::err::
                                expected_followed_by_comma(&ident));
                        }
                    }
                    Ok(out)
                }
            }
        }
    }

    /// Generates implementation of [`ParseAttrs`] trait for this struct.
    #[must_use]
    fn impl_parse_attrs(&self) -> TokenStream {
        let ty = &self.ty;
        let (impl_generics, ty_generics, where_clause) =
            self.generics.split_for_impl();

        let try_merge_fields = self.fields.iter().map(Field::gen_merge);

        let validate_provided_fields =
            self.fields.iter().map(Field::gen_validate_provided);
        let validate_nested_fields =
            self.fields.iter().filter_map(Field::gen_validate_nested);
        let validate_custom_fields = self.fields.iter().flat_map(|f| {
            let field = &f.ident;
            f.validators.iter().map(move |validator| {
                quote! {
                    #validator(&self.#field)?;
                }
            })
        });

        let fallback_nested_fields =
            self.fields.iter().filter_map(Field::gen_fallback_nested);
        let fallback_custom_fields = self.fields.iter().flat_map(|f| {
            let field = &f.ident;
            f.fallbacks.iter().map(move |fallback| {
                quote! {
                    #fallback(&mut self.#field, attrs)?;
                }
            })
        });

        quote! {
            #[automatically_derived]
            impl#impl_generics ::synthez::parse::Attrs for #ty#ty_generics
                #where_clause
            {
                fn try_merge(
                    mut self,
                    another: Self,
                ) -> ::synthez::syn::Result<Self> {
                    #( #try_merge_fields )*
                    Ok(self)
                }

                fn validate(
                    &self,
                    attr_name: &str,
                    item_span: ::synthez::proc_macro2::Span,
                ) -> ::synthez::syn::Result<()> {
                    #( #validate_provided_fields )*
                    #( #validate_nested_fields )*
                    #( #validate_custom_fields )*
                    Ok(())
                }

                fn fallback(
                    &mut self,
                    attrs: &[::synthez::syn::Attribute],
                ) -> ::synthez::syn::Result<()> {
                    #( #fallback_nested_fields )*
                    #( #fallback_custom_fields )*
                    Ok(())
                }
            }
        }
    }
}

/// Representation of a [`ParseAttrs`]'s field, used for code generation.
#[derive(Debug)]
struct Field {
    /// [`syn::Ident`] of this [`Field`] in the original code.
    ident: syn::Ident,

    /// [`syn::Type`] of this [`Field`] (with [`field::Container`]).
    ///
    /// [`field::Container`]: crate::field::Container
    ty: syn::Type,

    /// Parsing [`kind`] to use for this [`Field`] in the generated code.
    kind: Kind,

    /// [`dedup`]lication strategy to use for this [`Field`] in the generated
    /// code.
    dedup: Dedup,

    /// Names [`syn::Attribute`]'s arguments to parse this [`Field`] from in the
    /// generated code.
    names: Vec<String>,

    /// Additional custom validators to apply to this [`Field`] in the generated
    /// code.
    validators: Vec<syn::Expr>,

    /// Additional custom fallback functions to apply to this [`Field`] in the
    /// generated code.
    fallbacks: Vec<syn::Expr>,
}

impl TryFrom<syn::Field> for Field {
    type Error = syn::Error;

    fn try_from(field: syn::Field) -> syn::Result<Self> {
        let attrs = FieldAttrs::parse_attrs(ATTR_NAME, &field)?;
        let ident = field.ident.unwrap();

        let mut names = if attrs.args.is_empty() {
            iter::once(ident.clone()).collect()
        } else {
            attrs.args
        };
        names.try_merge_self::<kind::Value, dedup::Unique>(attrs.aliases)?;

        Ok(Self {
            ident,
            ty: field.ty,
            kind: **attrs.kind,
            dedup: attrs.dedup.as_deref().copied().unwrap_or_default(),
            names: names.into_iter().map(|n| n.to_string()).collect(),
            validators: attrs.validators,
            fallbacks: attrs.fallbacks,
        })
    }
}

impl Field {
    /// Generates code of merging this [`Field`] with another one.
    #[must_use]
    fn gen_merge(&self) -> TokenStream {
        let field = &self.ident;
        let ty = &self.ty;
        let kind = self.kind;
        let dedup = self.dedup;

        quote! {
            <#ty as ::synthez::parse::attrs::field::TryApplySelf<
                _, #kind, #dedup,
            >>::try_apply_self(&mut self.#field, another.#field)?;
        }
    }

    /// Generates code of [`rule::Provided`] validation for this [`Field`].
    #[must_use]
    fn gen_validate_provided(&self) -> TokenStream {
        let field = &self.ident;
        let ty = &self.ty;

        let arg_names = if self.names.len() > 1 {
            format!(
                "either `{}` or `{}`",
                &self.names[..(self.names.len() - 1)].join("`, `"),
                self.names.last().unwrap(),
            )
        } else {
            format!("`{}`", self.names.first().unwrap())
        };
        let err_msg =
            format!("{} argument of `#[{{}}]` attribute {{}}", arg_names);

        quote! {
            if let Err(e) = <#ty as ::synthez::parse::attrs::Validation<
                ::synthez::parse::attrs::validate::rule::Provided,
            >>::validation(&self.#field) {
                return Err(::synthez::syn::Error::new(
                    item_span,
                    format!(#err_msg, attr_name, e),
                ));
            }
        }
    }

    /// Generates code of [`kind::Nested`] validation for this [`Field`], if it
    /// represents the one.
    #[must_use]
    fn gen_validate_nested(&self) -> Option<TokenStream> {
        if self.kind != Kind::Nested {
            return None;
        }

        let field = &self.ident;
        let attr_fmt = format!("{{}}({})", self.names.first().unwrap());

        Some(quote! {
            for v in &self.#field {
                ::synthez::parse::Attrs::validate(
                    &**v,
                    &format!(#attr_fmt, attr_name),
                    ::synthez::syn::spanned::Spanned::span(v),
                )?;
            }
        })
    }

    /// Generates code of [`kind::Nested`] fallback for this [`Field`], if it
    /// represents the one.
    #[must_use]
    fn gen_fallback_nested(&self) -> Option<TokenStream> {
        if self.kind != Kind::Nested {
            return None;
        }

        let field = &self.ident;
        let ty = &self.ty;

        Some(quote! {
            if !<#ty as ::synthez::field::Container<_>>::is_empty(
                &self.#field,
            ) {
                for v in &mut self.#field {
                    ::synthez::parse::Attrs::fallback(&mut **v, attrs)?;
                }
            }
        })
    }
}

/// Representation of a `#[parse]` attribute used along with a
/// `#[derive(ParseAttrs)]` proc macro and placed on struct fields.
#[derive(Debug, Default)]
struct FieldAttrs {
    /// [`kind`] of the [`ParseAttrs`]'s field parsing.
    // #[parse(ident, args(ident, nested, value, map))]
    kind: Required<Spanning<Kind>>,

    /// Names of [`syn::Attribute`]'s arguments to use for parsing __instead
    /// of__ the [`ParseAttrs`]'s field's [`syn::Ident`].
    // #[parse(value, alias = arg)]
    args: HashSet<syn::Ident>,

    /// Names of [`syn::Attribute`]'s arguments to use for parsing __along
    /// with__ the [`ParseAttrs`]'s field's [`syn::Ident`].
    // #[parse(value, alias = alias)]
    aliases: HashSet<syn::Ident>,

    /// [`dedup`]lication strategy of how multiple values of the
    /// [`ParseAttrs`]'s field should be merged.
    ///
    /// Default is [`Dedup::Unique`].
    // #[parse(value)]
    dedup: Option<Spanning<Dedup>>,

    /// Additional custom validators to use for the [`ParseAttrs`]'s field.
    // #[parse(value, arg = validate)]
    validators: Vec<syn::Expr>,

    /// Additional custom fallback functions to use for the [`ParseAttrs`]'s
    /// field.
    // #[parse(value, alias = fallback)]
    fallbacks: Vec<syn::Expr>,
}

impl Parse for FieldAttrs {
    fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
        let mut out = Self::default();
        while !input.is_empty() {
            let ident = input.fork().parse_any_ident()?;
            match ident.to_string().as_str() {
                "ident" | "nested" | "value" | "map" => {
                    out.kind.try_merge::<kind::Ident, dedup::Unique>(
                        input.parse::<Spanning<Kind>>()?,
                    )?;
                }
                "arg" | "args" => {
                    input.skip_any_ident()?;
                    for val in input.parse_eq_or_wrapped_and_punctuated::<
                        syn::Ident, token::Paren, token::Comma,
                    >()? {
                        out.args.try_merge::<kind::Value, dedup::Unique>(val)?;
                    }
                }
                "alias" | "aliases" => {
                    input.skip_any_ident()?;
                    for v in input.parse_eq_or_wrapped_and_punctuated::<
                        syn::Ident, token::Paren, token::Comma,
                    >()? {
                        out.aliases.try_merge::<kind::Value, dedup::Unique>(v)?;
                    }
                }
                "dedup" => {
                    input.skip_any_ident()?;
                    for val in input.parse_eq_or_wrapped_and_punctuated::<
                        Spanning<Dedup>, token::Paren, token::Comma,
                    >()? {
                        out.dedup.try_merge::<kind::Value, dedup::Unique>(val)?;
                    }
                }
                "validate" => {
                    input.skip_any_ident()?;
                    for v in input.parse_eq_or_wrapped_and_punctuated::<
                        syn::Expr, token::Paren, token::Comma,
                    >()? {
                        out.validators.try_merge::<
                            kind::Value, dedup::Unique,
                        >(v)?;
                    }
                }
                "fallbacks" | "fallback" => {
                    input.skip_any_ident()?;
                    for v in input.parse_eq_or_wrapped_and_punctuated::<
                        syn::Expr, token::Paren, token::Comma,
                    >()? {
                        out.fallbacks.try_merge::<
                            kind::Value, dedup::Unique,
                        >(v)?;
                    }
                }
                name => {
                    return Err(err::unknown_attr_arg(&ident, name));
                }
            }
            if input.try_parse::<token::Comma>()?.is_none() && !input.is_empty()
            {
                return Err(err::expected_followed_by_comma(&ident));
            }
        }
        Ok(out)
    }
}

impl ParseAttrs for FieldAttrs {
    fn try_merge(mut self, another: Self) -> syn::Result<Self> {
        self.kind.try_merge_self::<kind::Value, dedup::Unique>(another.kind)?;
        self.args.try_merge_self::<kind::Value, dedup::Unique>(another.args)?;
        self.aliases
            .try_merge_self::<kind::Value, dedup::Unique>(another.aliases)?;
        self.dedup
            .try_merge_self::<kind::Value, dedup::Unique>(another.dedup)?;
        self.validators
            .try_merge_self::<kind::Value, dedup::Unique>(another.validators)?;
        self.fallbacks
            .try_merge_self::<kind::Value, dedup::Unique>(another.fallbacks)?;
        Ok(self)
    }

    fn validate(&self, attr_name: &str, item_span: Span) -> syn::Result<()> {
        if self.kind.validate::<rule::Provided>().is_err() {
            return Err(syn::Error::new(
                item_span,
                format!(
                    "either `ident`, `value` or `map` argument of `#[{}]` \
                     attribute is expected",
                    attr_name,
                ),
            ));
        }
        Ok(())
    }
}

/// Field [`kind`] of parsing it from [`syn::Attribute`]s.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Kind {
    /// Field is parsed as a simple [`syn::Ident`].
    Ident,

    /// Field is parsed as a nested structure implementing [`ParseAttrs`].
    Nested,

    /// Field is parsed as values behind a [`syn::Ident`].
    ///
    /// Boolean refers to whether the value and the [`syn::Ident`] are separated
    /// with spaces only.
    Value(bool),

    /// Field is parsed as as key-value pairs behind a [`syn::Ident`].
    Map,
}

impl Parse for Spanning<Kind> {
    fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
        let ident = input.parse::<syn::Ident>()?;
        Ok(Self::new(
            match ident.to_string().as_str() {
                "ident" => Kind::Ident,
                "nested" => Kind::Nested,
                "value" => {
                    if input.is_next::<token::Paren>() {
                        let inner;
                        let _ = syn::parenthesized!(inner in input);
                        let inner = inner.parse::<syn::Ident>()?;
                        let val = inner.to_string();
                        if val != "spaced" {
                            return Err(syn::Error::new_spanned(
                                inner,
                                format!("invalid value setting: {} ", val),
                            ));
                        }
                        Kind::Value(true)
                    } else {
                        Kind::Value(false)
                    }
                }
                "map" => Kind::Map,
                val => {
                    return Err(syn::Error::new_spanned(
                        ident,
                        format!("invalid kind value: {} ", val),
                    ))
                }
            },
            &ident,
        ))
    }
}

impl ToTokens for Kind {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let variant = syn::Ident::new_on_call_site(match self {
            Self::Ident => "Ident",
            Self::Nested => "Nested",
            Self::Value(_) => "Value",
            Self::Map => "Map",
        });
        tokens.append_all(&[quote! {
            ::synthez::parse::attrs::kind::#variant
        }])
    }
}

/// Field [`dedup`]lication strategy parsed from [`syn::Attribute`]s.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
enum Dedup {
    /// Only a single value of the field is allowed to appear.
    Unique,

    /// Only the first parsed value of the field is picked.
    First,

    /// Only the last parsed value of the field is picked.
    Last,
}

impl Default for Dedup {
    #[inline]
    fn default() -> Self {
        Self::Unique
    }
}

impl Parse for Spanning<Dedup> {
    fn parse(input: ParseStream<'_>) -> syn::Result<Self> {
        let ident = input.parse::<syn::Ident>()?;
        Ok(Self::new(
            match ident.to_string().as_str() {
                "unique" => Dedup::Unique,
                "first" => Dedup::First,
                "last" => Dedup::Last,
                val => {
                    return Err(syn::Error::new_spanned(
                        ident,
                        format!("invalid dedup value: {} ", val),
                    ))
                }
            },
            &ident,
        ))
    }
}

impl ToTokens for Dedup {
    fn to_tokens(&self, tokens: &mut TokenStream) {
        let variant = syn::Ident::new_on_call_site(match self {
            Self::Unique => "Unique",
            Self::First => "First",
            Self::Last => "Last",
        });
        tokens.append_all(&[quote! {
            ::synthez::parse::attrs::dedup::#variant
        }])
    }
}