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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
use darling::{FromAttributes, FromMeta};
use proc_macro::{Span, TokenStream};
use proc_macro2::{Delimiter, Group, Punct};
use quote::{quote, ToTokens, TokenStreamExt};
use syn::{
    parse_macro_input, punctuated::Punctuated, token::Comma, Attribute, DataEnum, DataStruct,
    DeriveInput, Expr, Field, Fields, Generics, Ident, Lifetime, LifetimeParam,
};

#[derive(Debug)]
struct DataTag([u8; 4]);

impl FromMeta for DataTag {
    fn from_string(value: &str) -> darling::Result<Self> {
        let mut out = [0u8; 4];

        let input = value.as_bytes();
        // Only copy the max of 4 bytes
        let len = input.len().min(4);
        out[0..len].copy_from_slice(input);

        Ok(Self(out))
    }
}

impl ToTokens for DataTag {
    fn to_tokens(&self, tokens: &mut proc_macro2::TokenStream) {
        tokens.append(Punct::new('&', proc_macro2::Spacing::Joint));
        let [a, b, c, d] = &self.0;
        let inner_stream = quote!(#a, #b, #c, #d);
        tokens.append(Group::new(Delimiter::Bracket, inner_stream));
    }
}

#[derive(Debug, FromAttributes)]
#[darling(attributes(tdf), forward_attrs(allow, doc, cfg))]
struct TdfFieldAttrs {
    tag: Option<DataTag>,
    #[darling(default)]
    into: Option<Expr>,
    #[darling(default)]
    skip: bool,
}

#[derive(Debug, FromAttributes)]
#[darling(attributes(tdf), forward_attrs(allow, doc, cfg))]
struct TdfStructAttr {
    #[darling(default)]
    group: bool,
    #[darling(default)]
    prefix_two: bool,
}

#[derive(Debug, FromAttributes)]
#[darling(attributes(tdf), forward_attrs(allow, doc, cfg))]
struct TdfEnumVariantAttr {
    #[darling(default)]
    default: bool,
}

#[derive(Debug, FromAttributes)]
#[darling(attributes(tdf), forward_attrs(allow, doc, cfg))]
struct TdfTaggedEnumVariantAttr {
    pub key: Option<Expr>,

    #[darling(default)]
    pub tag: Option<DataTag>,

    #[darling(default)]
    pub prefix_two: bool,

    #[darling(default)]
    pub default: bool,

    #[darling(default)]
    pub unset: bool,
}

#[proc_macro_derive(TdfSerialize, attributes(tdf))]
pub fn derive_tdf_serialize(input: TokenStream) -> TokenStream {
    let input: DeriveInput = parse_macro_input!(input);

    match &input.data {
        syn::Data::Struct(data) => impl_serialize_struct(&input, data),
        syn::Data::Enum(data) => {
            if is_enum_tagged(data) {
                impl_serialize_tagged_enum(&input, data)
            } else {
                impl_serialize_repr_enum(&input, data)
            }
        }
        syn::Data::Union(_) => panic!("TdfSerialize cannot be implemented on union types"),
    }
}

#[proc_macro_derive(TdfTyped, attributes(tdf))]
pub fn derive_tdf_typed(input: TokenStream) -> TokenStream {
    let input: DeriveInput = parse_macro_input!(input);

    match &input.data {
        syn::Data::Struct(data) => impl_type_struct(&input, data),
        syn::Data::Enum(data) => {
            if is_enum_tagged(data) {
                impl_type_tagged_enum(&input, data)
            } else {
                impl_type_repr_enum(&input, data)
            }
        }
        syn::Data::Union(_) => panic!("TdfTyped cannot be implemented on union types"),
    }
}

#[proc_macro_derive(TdfDeserialize, attributes(tdf))]
pub fn derive_tdf_deserialize(input: TokenStream) -> TokenStream {
    let input: DeriveInput = parse_macro_input!(input);
    match &input.data {
        syn::Data::Struct(data) => impl_deserialize_struct(&input, data),
        syn::Data::Enum(data) => {
            if is_enum_tagged(data) {
                impl_deserialize_tagged_enum(&input, data)
            } else {
                impl_deserialize_repr_enum(&input, data)
            }
        }

        syn::Data::Union(_) => panic!("TdfDeserialize cannot be implemented on union types"),
    }
}

fn get_repr_attribute(attrs: &[Attribute]) -> Option<Ident> {
    attrs
        .iter()
        .filter_map(|attr| attr.meta.require_list().ok())
        .find(|value| value.path.is_ident("repr"))
        .map(|attr| {
            let value: Ident = attr.parse_args().expect("Failed to parse repr type");
            value
        })
}

/// Determines whether an enum should be considered to be a Tagged Union
/// rather than a repr enum. Any enum types that have fields cannot be
/// repr types and thus must be Tagged Union's
fn is_enum_tagged(data: &DataEnum) -> bool {
    data.variants
        .iter()
        .any(|variant| !variant.fields.is_empty())
}

fn impl_type_struct(input: &DeriveInput, _data: &DataStruct) -> TokenStream {
    let attr =
        TdfStructAttr::from_attributes(&input.attrs).expect("Failed to parse tdf struct attrs");

    assert!(
        attr.group,
        "Cannot derive TdfTyped on non group struct, type is unknown"
    );

    let ident = &input.ident;
    let generics = &input.generics;
    let where_clause = generics.where_clause.as_ref();

    quote! {
        impl #generics tdf::TdfTyped for #ident #generics #where_clause {
            const TYPE: tdf::TdfType = tdf::TdfType::Group;
        }
    }
    .into()
}

fn impl_type_repr_enum(input: &DeriveInput, _data: &DataEnum) -> TokenStream {
    let ident = &input.ident;
    let repr = get_repr_attribute(&input.attrs)
        .expect("Non-tagged enums require #[repr({ty})] to be specified");

    quote! {
        impl tdf::TdfTyped for #ident {
            const TYPE: tdf::TdfType = <#repr as tdf::TdfTyped>::TYPE;
        }
    }
    .into()
}

fn impl_type_tagged_enum(input: &DeriveInput, _data: &DataEnum) -> TokenStream {
    let ident = &input.ident;

    let generics = &input.generics;
    let where_clause = generics.where_clause.as_ref();

    quote! {
        impl #generics tdf::TdfTyped for #ident #generics #where_clause {
            const TYPE: tdf::TdfType = tdf::TdfType::TaggedUnion;
        }
    }
    .into()
}

fn tag_field_serialize(
    field: &Field,
    into: Option<Expr>,
    tag: Option<DataTag>,
    is_struct: bool,
) -> proc_macro2::TokenStream {
    let tag = tag.expect("Fields that arent skipped must specify a tag");
    let ident = &field.ident;
    let ty = &field.ty;

    // TODO: Validate tag

    let value = if is_struct {
        quote!(&self.#ident)
    } else {
        quote!(#ident)
    };

    if let Some(into) = into {
        quote!( w.tag_owned::<#into>(#tag, <#ty as Into::<#into>>::into(*#value)); )
    } else {
        quote! ( w.tag_ref::<#ty>(#tag, #value); )
    }
}

fn impl_serialize_struct(input: &DeriveInput, data: &DataStruct) -> TokenStream {
    let attr =
        TdfStructAttr::from_attributes(&input.attrs).expect("Failed to parse tdf struct attrs");
    let ident = &input.ident;
    let generics = &input.generics;
    let where_clause = generics.where_clause.as_ref();

    let serialize_impls = data.fields.iter().filter_map(|field| {
        let attributes =
            TdfFieldAttrs::from_attributes(&field.attrs).expect("Failed to parse tdf field attrs");
        if attributes.skip {
            None
        } else {
            Some(tag_field_serialize(
                field,
                attributes.into,
                attributes.tag,
                true,
            ))
        }
    });

    let mut leading = None;
    let mut trailing = None;

    if attr.group {
        if attr.prefix_two {
            leading = Some(quote! { w.write_byte(2); });
        }

        trailing = Some(quote!( w.tag_group_end();));
    }

    quote! {
        impl #generics tdf::TdfSerialize for #ident #generics #where_clause {
            fn serialize<S: tdf::TdfSerializer>(&self, w: &mut S) {
                #leading
                #(#serialize_impls)*
                #trailing
            }
        }
    }
    .into()
}

fn impl_serialize_repr_enum(input: &DeriveInput, _data: &DataEnum) -> TokenStream {
    let ident = &input.ident;
    let repr = get_repr_attribute(&input.attrs)
        .expect("Non-tagged enums require #[repr({ty})] to be specified");

    quote! {
        impl tdf::TdfSerializeOwned for #ident {
            fn serialize_owned<S: tdf::TdfSerializer>(self, w: &mut S) {
                <#repr as tdf::TdfSerializeOwned>::serialize_owned(self as #repr, w);
            }
        }
    }
    .into()
}

fn impl_serialize_tagged_enum(input: &DeriveInput, data: &DataEnum) -> TokenStream {
    let ident = &input.ident;

    let field_impls: Vec<_> = data
        .variants
        .iter()
        .map(|variant| {
            let attr: TdfTaggedEnumVariantAttr =
                TdfTaggedEnumVariantAttr::from_attributes(&variant.attrs)
                    .expect("Failed to parse tdf field attrs");

            (variant, attr)
        })
        .map(|(variant, attr)| {
            let var_ident = &variant.ident;
            let value_tag = attr.tag;
            let is_unit = attr.unset || attr.default;

            // TODO: Ensure no duplicates & validate value tag matches

            if let Fields::Unit = &variant.fields {
                assert!(
                    is_unit,
                    "Only unset or default enum variants can have no content"
                );

                return quote! {
                    Self::#var_ident => {
                        w.write_byte(tdf::types::tagged_union::TAGGED_UNSET_KEY);
                    }
                };
            }

            assert!(
                !is_unit,
                "Enum variants with fields cannot be used as the default or unset variant"
            );

            let discriminant = attr.key.expect("Missing discriminant key");
            let value_tag = value_tag.expect("Missing value tag");

            match &variant.fields {
                // Variants with named fields are handled as groups
                Fields::Named(fields) => {
                    let (idents, impls): (Vec<_>, Vec<_>) = fields
                        .named
                        .iter()
                        .filter_map(|field| {
                            let attributes = TdfFieldAttrs::from_attributes(&field.attrs)
                                .expect("Failed to parse tdf field attrs");
                            if attributes.skip {
                                return None;
                            }

                            Some((field, attributes))
                        })
                        .map(|(field, attributes)| {
                            let ident = field.ident.as_ref().expect("Field missing ident");
                            let serialize = tag_field_serialize(field, attributes.into,attributes.tag, false);
                            (ident, serialize)
                        })
                        .unzip();

                    // Handle how field names are listed
                    let field_names: proc_macro2::TokenStream = if idents.is_empty() {
                        quote!(..)
                    } else if idents.len() != fields.named.len() {
                        quote!(#(#idents,)* ..)
                    } else {
                        quote!(#(#idents),*)
                    };

                    let mut leading = None;

                    if attr.prefix_two {
                        leading = Some(quote!( w.write_byte(2); ))
                    }

                    quote! {
                        Self::#var_ident { #field_names } => {
                            w.write_byte(#discriminant);
                            tdf::Tagged::serialize_raw(w, #value_tag, tdf::TdfType::Group);

                            #leading
                            #(#impls)*
                            w.tag_group_end();
                        }
                    }
                }

                // Variants with unnamed fields are treated as the type of the first field (Only one field is allowed)
                Fields::Unnamed(fields) => {
                    let fields = &fields.unnamed;
                    let field = fields.first().expect("Unnamed tagged enum missing field");

                    assert!(
                        fields.len() == 1,
                        "Tagged union cannot have more than one unnamed field"
                    );

                    let field_ty = &field.ty;

                    quote! {
                        Self::#var_ident(value) => {
                            w.write_byte(#discriminant);
                            tdf::Tagged::serialize_raw(w, #value_tag, <#field_ty as tdf::TdfTyped>::TYPE);

                            <#field_ty as tdf::TdfSerialize>::serialize(value, w);
                        }
                    }
                }
                Fields::Unit => unreachable!("Unit types should already be handled above"),
            }
        })
        .collect();
    let generics = &input.generics;
    let where_clause = generics.where_clause.as_ref();

    quote! {
        impl #generics tdf::TdfSerialize for #ident #generics #where_clause {
            fn serialize<S: tdf::TdfSerializer>(&self, w: &mut S) {
                match self {
                    #(#field_impls),*
                }
            }
        }
    }
    .into()
}

/// Obtains the lifetime that should be used by [tdf::TdfDeserializer] when
/// deserializing values. If the generic parameters specify a lifetime then
/// that lifetime is used otherwise the default lifetime '_ is used instead
///
/// Will panic if structure uses more than 1 lifetime as its not possible
/// to deserialize with more than one lifetime
fn get_deserialize_lifetime(generics: &Generics) -> LifetimeParam {
    let mut lifetimes = generics.lifetimes();

    let lifetime = lifetimes
        .next()
        .cloned()
        // Use a default '_ lifetime while deserializing when no lifetime is provided
        .unwrap_or_else(|| LifetimeParam::new(Lifetime::new("'_", Span::call_site().into())));

    assert!(
        lifetimes.next().is_none(),
        "Deserializable structs cannot have more than one lifetime"
    );

    lifetime
}

/// Creates a token stream for deserializing the provided `field`
/// loads the tag and whether
fn tag_field_deserialize(field: &Field) -> proc_macro2::TokenStream {
    let attributes =
        TdfFieldAttrs::from_attributes(&field.attrs).expect("Failed to parse tdf field attrs");

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

    if attributes.skip {
        quote!( let #ident = Default::default(); )
    } else {
        let tag = attributes
            .tag
            .expect("Fields that arent skipped must specify a tag");

        // TODO: Validate tag
        if let Some(into) = attributes.into {
            quote!( let #ident = <#ty as From<#into>>::from(r.tag::<#into>(#tag)?); )
        } else {
            quote!( let #ident = r.tag::<#ty>(#tag)?; )
        }
    }
}

fn impl_deserialize_struct(input: &DeriveInput, data: &DataStruct) -> TokenStream {
    let attributes =
        TdfStructAttr::from_attributes(&input.attrs).expect("Failed to parse tdf struct attrs");

    let ident = &input.ident;

    let generics = &input.generics;
    let lifetime = get_deserialize_lifetime(generics);
    let where_clause = generics.where_clause.as_ref();

    let idents = data.fields.iter().filter_map(|field| field.ident.as_ref());
    let impls = data.fields.iter().map(tag_field_deserialize);

    let mut leading = None;
    let mut trailing = None;

    // Groups need leading deserialization for possible prefixes and trailing
    // deserialization to read any unused tags and to read the group end byte
    if attributes.group {
        leading = Some(quote!( tdf::GroupSlice::deserialize_prefix_two(r)?; ));
        trailing = Some(quote!( tdf::GroupSlice::deserialize_content_skip(r)?; ));
    }

    quote! {
        impl #generics tdf::TdfDeserialize<#lifetime> for #ident #generics #where_clause {
            fn deserialize(r: &mut tdf::TdfDeserializer<#lifetime>) -> tdf::DecodeResult<Self> {
                #leading
                #(#impls)*
                #trailing
                Ok(Self {
                    #(#idents),*
                })
            }
        }
    }
    .into()
}

fn impl_deserialize_repr_enum(input: &DeriveInput, data: &DataEnum) -> TokenStream {
    let repr = get_repr_attribute(&input.attrs)
        .expect("Non-tagged enums require #[repr({ty})] to be specified");

    let mut default = None;

    let variant_cases: Vec<_> = data
        .variants
        .iter()
        .map(|variant| {
            let attr = TdfEnumVariantAttr::from_attributes(&variant.attrs)
                .expect("Failed to parse tdf enum variant attrs");
            (variant, attr)
        })
        .filter(|(variant, attr)| {
            if !attr.default {
                return true;
            }

            assert!(
                default.is_none(),
                "Cannot have more than one default variant"
            );

            let ident = &variant.ident;

            default = Some(quote!(_ => Self::#ident));

            false
        })
        .map(|(variant, _attr)| {
            let var_ident = &variant.ident;
            let (_, discriminant) = variant
                .discriminant
                .as_ref()
                .expect("Repr enum variants must include a descriminant for each value");

            quote! ( #discriminant => Self::#var_ident )
        })
        .collect();

    let ident = &input.ident;
    let default = default.unwrap_or_else(
        || quote!(_ => return Err(tdf::DecodeError::Other("Missing fallback enum variant"))),
    );

    quote! {
        impl tdf::TdfDeserialize<'_> for #ident {
            fn deserialize(r: &mut tdf::TdfDeserializer<'_>) -> tdf::DecodeResult<Self> {
                let value = <#repr>::deserialize(r)?;
                Ok(match value {
                    #(#variant_cases,)*
                    #default
                })
            }
        }
    }
    .into()
}

fn impl_deserialize_tagged_enum(input: &DeriveInput, data: &DataEnum) -> TokenStream {
    let generics = &input.generics;
    let lifetime = get_deserialize_lifetime(generics);
    let where_clause = generics.where_clause.as_ref();

    let mut has_unset = false;
    let mut has_default = false;

    let mut impls: Punctuated<proc_macro2::TokenStream, Comma> = data
        .variants
        .iter()
        .map(|variant| {
            let attr: TdfTaggedEnumVariantAttr =
                TdfTaggedEnumVariantAttr::from_attributes(&variant.attrs)
                    .expect("Failed to parse tdf field attrs");

            let var_ident = &variant.ident;
            let is_unit = attr.unset || attr.default;

            if let Fields::Unit = &variant.fields {
                assert!(
                    is_unit,
                    "Only unset or default enum variants can have no content"
                );

                assert!(
                    !(attr.default && attr.unset),
                    "Enum variant cannot be default and unset"
                );

                return if attr.default {
                    assert!(!has_default, "Default variant already defined");
                    has_default = true;

                    // TODO: Ensure no duplicates & validate value tag matches
                    quote! {
                        _  => {
                            let tag = tdf::Tagged::deserialize_owned(r)?;
                            tag.ty.skip(r)?;
                            Self::#var_ident
                        }
                    }
                } else {
                    assert!(!has_unset, "Unset variant already defined");
                    has_unset = true;
                    quote!( tdf::types::tagged_union::TAGGED_UNSET_KEY => Self::#var_ident )
                };
            }

            assert!(
                !is_unit,
                "Enum variants with fields cannot be used as the default or unset variant"
            );

            let discriminant = attr.key.expect("Missing discriminant key");
            let _value_tag = attr.tag.expect("Missing value tag");

            match &variant.fields {
                // Variants with named fields are handled as groups
                Fields::Named(fields) => {
                    let (idents, impls): (Vec<_>, Vec<_>) = fields
                        .named
                        .iter()
                        .map(|field| {
                            let ident = field.ident.as_ref().unwrap();
                            let value = tag_field_deserialize(field);
                            (ident, value)
                        })
                        .unzip();

                    // TODO: Ensure no duplicates & validate value tag matches
                    quote! {
                        #discriminant => {
                            let tag = tdf::Tagged::deserialize_owned(r)?;

                            tdf::GroupSlice::deserialize_prefix_two(r)?;
                            #(#impls)*
                            tdf::GroupSlice::deserialize_content_skip(r)?;

                            Self::#var_ident {
                                #(#idents),*
                            }
                        }
                    }
                }
                // Variants with unnamed fields are treated as the type of the first field (Only one field is allowed)
                Fields::Unnamed(fields) => {
                    let fields = &fields.unnamed;
                    let field = fields.first().expect("Unnamed tagged enum missing field");

                    assert!(
                        fields.len() == 1,
                        "Tagged union cannot have more than one unnamed field"
                    );

                    let field_ty = &field.ty;

                    // TODO: Ensure no duplicates & validate value tag matches
                    quote! {
                        #discriminant => {
                            let tag = tdf::Tagged::deserialize_owned(r)?;

                            let value = <#field_ty as tdf::TdfDeserialize<'_>>::deserialize(r)?;
                            Self::#var_ident(value)
                        }
                    }
                }

                Fields::Unit => unreachable!("Unit types should already be handled above"),
            }
        })
        .collect();

    if !has_unset {
        // If an unset variant is not specified its handling is replaced with a runtime error
        impls.push(quote!(
            tdf::types::tagged_union::TAGGED_UNSET_KEY => return Err(tdf::DecodeError::Other("Missing unset enum variant"))
        ));
    }

    if !has_default {
        // If a default variant is not specified its handling is replaced with a runtime error
        impls.push(quote!(
            _ => return Err(tdf::DecodeError::Other("Missing default enum variant"))
        ));
    }

    let ident = &input.ident;

    quote! {
        impl #generics tdf::TdfDeserialize<#lifetime> for #ident #generics #where_clause {
            fn deserialize(r: &mut tdf::TdfDeserializer<#lifetime>) -> tdf::DecodeResult<Self> {
                let discriminant = <u8 as tdf::TdfDeserialize<#lifetime>>::deserialize(r)?;

                Ok(match discriminant {
                    #impls
                })
            }
        }
    }
    .into()
}