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
//! # Derive macros for traits in `tls_codec`
//!
//! ## Warning
//! The derive macros support deriving the `tls_codec` traits for enumerations and the resulting
//! serialized format complies with [the "variants" section of the TLS RFC](https://datatracker.ietf.org/doc/html/rfc8446#section-3.8).
//! However support is limited to enumerations that are serialized with their discriminant
//! immediately followed by the variant data. If this is not appropriate (e.g. the format requires
//! other fields between the discriminant and variant data), the `tls_codec` traits can be
//! implemented manually.
//!
//! ## Available attributes
//! ### `with`
//!
//! ```text
//! #[tls_codec(with = "prefix")]
//! ```
//! This attribute may be applied to a struct field. It indicates that deriving any of the
//! `tls_codec` traits for the containing struct calls the following functions:
//! - `prefix::tls_deserialize` when deriving `Deserialize`
//! - `prefix::tls_serialize` when deriving `Serialize`
//! - `prefix::tls_serialized_len` when deriving `Size`
//!
//! `prefix` can be a path to a module, type or trait where the functions are defined.
//!
//! Their expected signatures match the corresponding methods in the traits.
//!
//! ```
//! use tls_codec_derive::{TlsSerialize, TlsSize};
//!
//! #[derive(TlsSerialize, TlsSize)]
//! struct Bytes {
//!     #[tls_codec(with = "bytes")]
//!     values: Vec<u8>,
//! }
//!
//! mod bytes {
//!     use std::io::Write;
//!     use tls_codec::{Serialize, Size, TlsByteSliceU32};
//!
//!     pub fn tls_serialized_len(v: &[u8]) -> usize {
//!         TlsByteSliceU32(v).tls_serialized_len()
//!     }
//!
//!     pub fn tls_serialize<W: Write>(v: &[u8], writer: &mut W) -> Result<usize, tls_codec::Error> {
//!         TlsByteSliceU32(v).tls_serialize(writer)
//!     }
//! }
//! ```
//!
//! ### `discriminant`
//!
//! ```text
//! #[tls_codec(discriminant = 123)]
//! ```
//! This attribute may be applied to an enum variant to specify the discriminant to use when
//! serializing it. If all variants are units (e.g. they do not have any data), this attribute
//! must not be used and the desired discriminants should be assigned to the variants using
//! standard Rust syntax (`Variant = Discriminant`).
//!
//! For enumerations with non-unit variants, if no variant has this attribute, the serialization
//! discriminants will start from zero. If this attribute is used on a variant and the following
//! variant does not have it, its discriminant will be equal to the previous variant discriminant
//! plus 1.
//!
//! ```
//! use tls_codec_derive::{TlsSerialize, TlsSize};
//!
//! #[derive(TlsSerialize, TlsSize)]
//! #[repr(u8)]
//! enum Token {
//!     #[tls_codec(discriminant = 5)]
//!     Int(u32),
//!     Bytes([u8; 16]),
//! }

extern crate proc_macro;
extern crate proc_macro2;

use proc_macro::TokenStream;
use proc_macro2::{Span, TokenStream as TokenStream2};
use quote::quote;
use syn::{
    self, parenthesized,
    parse::{ParseStream, Parser, Result},
    parse_macro_input,
    punctuated::Punctuated,
    token::Comma,
    Attribute, Data, DeriveInput, ExprPath, Field, Generics, Ident, Lit, Member, Meta, NestedMeta,
    Type,
};

/// Attribute name to identify attributes to be processed by derive-macros in this crate.
const ATTR_IDENT: &str = "tls_codec";

/// Prefix to add to `tls_codec` functions
///
/// This is either `<Type as Trait>` or a custom module containing the functions.
#[derive(Clone)]
enum Prefix {
    Type(Type),
    Custom(ExprPath),
}

impl Prefix {
    /// Returns the path prefix to use for functions from the given trait.
    fn for_trait(&self, trait_name: &str) -> TokenStream2 {
        let trait_name = Ident::new(trait_name, Span::call_site());
        match self {
            Prefix::Type(ty) => quote! { <#ty as tls_codec::#trait_name> },
            Prefix::Custom(p) => quote! { #p },
        }
    }
}

#[derive(Clone)]
struct Struct {
    call_site: Span,
    ident: Ident,
    generics: Generics,
    members: Vec<Member>,
    member_prefixes: Vec<Prefix>,
}

#[derive(Clone)]
struct Enum {
    call_site: Span,
    ident: Ident,
    generics: Generics,
    repr: Ident,
    variants: Vec<Variant>,
    discriminant_constants: TokenStream2,
}

#[derive(Clone)]
struct Variant {
    ident: Ident,
    members: Vec<Member>,
    member_prefixes: Vec<Prefix>,
}

#[derive(Clone)]
enum TlsStruct {
    Struct(Struct),
    Enum(Enum),
}

/// Attributes supported by derive-macros in this crate
#[derive(Clone)]
enum TlsAttr {
    /// Prefix for custom serialization functions
    With(ExprPath),
    /// Custom discriminant for an enum variant
    Discriminant(u32),
}

impl TlsAttr {
    fn name(&self) -> &'static str {
        match self {
            TlsAttr::With(_) => "with",
            TlsAttr::Discriminant(_) => "discriminant",
        }
    }

    /// Parses attributes of the form:
    /// ```text
    /// #[tls_codec(with = "module")]
    /// ```
    fn parse(attr: &Attribute) -> Result<Vec<TlsAttr>> {
        if attr.path.get_ident().map_or(true, |id| id != ATTR_IDENT) {
            return Ok(Vec::new());
        }
        let meta = match attr.parse_meta()? {
            Meta::List(list) => Ok(list),
            _ => Err(syn::Error::new_spanned(attr, "Invalid attribute syntax")),
        }?;
        meta.nested
            .iter()
            .map(|item| match item {
                NestedMeta::Meta(Meta::NameValue(kv)) => kv
                    .path
                    .get_ident()
                    .map(|ident| {
                        let ident_str = ident.to_string();
                        match &*ident_str {
                            "discriminant" => match &kv.lit {
                                Lit::Int(i) => i.base10_parse::<u32>().map(TlsAttr::Discriminant),
                                _ => Err(syn::Error::new_spanned(
                                    &kv.lit,
                                    "Expected integer literal",
                                )),
                            },
                            "with" => match &kv.lit {
                                Lit::Str(s) => s.parse::<ExprPath>().map(TlsAttr::With),
                                _ => {
                                    Err(syn::Error::new_spanned(&kv.lit, "Expected string literal"))
                                }
                            },
                            _ => Err(syn::Error::new_spanned(
                                ident,
                                format!("Unexpected identifier {}", ident),
                            )),
                        }
                    })
                    .unwrap_or_else(|| {
                        Err(syn::Error::new_spanned(&kv.path, "Expected identifier"))
                    }),
                _ => Err(syn::Error::new_spanned(item, "Invalid attribute syntax")),
            })
            .collect()
    }

    /// Parses attributes of the form:
    /// ```text
    /// #[tls_codec(with = "module", ...)]
    /// ```
    fn parse_multi(attrs: &[Attribute]) -> Result<Vec<TlsAttr>> {
        attrs.iter().try_fold(Vec::new(), |mut acc, attr| {
            acc.extend(TlsAttr::parse(attr)?);
            Ok(acc)
        })
    }
}

/// Gets the [`Prefix`] for a field, i.e. the type itself or a path to prepend to the `tls_codec`
/// functions (e.g. a module or type).
fn function_prefix(field: &Field) -> Result<Prefix> {
    let prefix = TlsAttr::parse_multi(&field.attrs)?
        .into_iter()
        .try_fold(None, |path, attr| match (path, attr) {
            (None, TlsAttr::With(p)) => Ok(Some(p)),
            (Some(_), TlsAttr::With(p)) => Err(syn::Error::new_spanned(
                p,
                "Attribute `with` specified more than once",
            )),
            (_, attr) => Err(syn::Error::new(
                Span::call_site(),
                format!("Unrecognized field attribute `{}`", attr.name()),
            )),
        })?
        .map(Prefix::Custom)
        .unwrap_or_else(|| Prefix::Type(field.ty.clone()));
    Ok(prefix)
}

/// Gets the serialization discriminant if specified.
fn discriminant_value(attrs: &[Attribute]) -> Result<Option<u32>> {
    TlsAttr::parse_multi(attrs)?
        .into_iter()
        .try_fold(None, |discriminant, attr| match (discriminant, attr) {
            (None, TlsAttr::Discriminant(d)) => Ok(Some(d)),
            (Some(_), TlsAttr::Discriminant(_)) => Err(syn::Error::new(
                Span::call_site(),
                "Attribute `discriminant` specified more than once",
            )),
            (_, attr) => Err(syn::Error::new(
                Span::call_site(),
                format!("Unrecognized variant attribute `{}`", attr.name()),
            )),
        })
}

fn fields_to_members(fields: &syn::Fields) -> Vec<Member> {
    fields
        .iter()
        .enumerate()
        .map(|(i, field)| {
            field
                .ident
                .clone()
                .map_or_else(|| Member::Unnamed(syn::Index::from(i)), Member::Named)
        })
        .collect()
}

/// Gets the [`Prefix`]es for all fields, i.e. the types themselves or paths to prepend to the
/// `tls_codec` functions (e.g. a module or type).
fn fields_to_member_prefixes(fields: &syn::Fields) -> Result<Vec<Prefix>> {
    fields.iter().map(function_prefix).collect()
}

fn parse_ast(ast: DeriveInput) -> Result<TlsStruct> {
    let call_site = Span::call_site();
    let ident = ast.ident.clone();
    let generics = ast.generics.clone();
    match ast.data {
        Data::Struct(st) => {
            let members = fields_to_members(&st.fields);
            let member_prefixes = fields_to_member_prefixes(&st.fields)?;
            Ok(TlsStruct::Struct(Struct {
                call_site,
                ident,
                generics,
                members,
                member_prefixes,
            }))
        }
        // Enums.
        // Note that they require a repr attribute.
        Data::Enum(syn::DataEnum { variants, .. }) => {
            let mut repr = None;
            for attr in ast.attrs {
                if attr.path.is_ident("repr") {
                    fn repr_arg(input: ParseStream) -> Result<Ident> {
                        let content;
                        parenthesized!(content in input);
                        content.parse()
                    }
                    let ty = repr_arg.parse2(attr.tokens)?;
                    repr = Some(ty);
                    break;
                }
            }
            let repr =
                repr.ok_or_else(|| syn::Error::new(call_site, "missing #[repr(...)] attribute"))?;
            let discriminant_constants = define_discriminant_constants(&ident, &repr, &variants)?;
            let variants = variants
                .into_iter()
                .map(|variant| {
                    Ok(Variant {
                        ident: variant.ident,
                        members: fields_to_members(&variant.fields),
                        member_prefixes: fields_to_member_prefixes(&variant.fields)?,
                    })
                })
                .collect::<Result<Vec<_>>>()?;

            Ok(TlsStruct::Enum(Enum {
                call_site,
                ident,
                generics,
                repr,
                variants,
                discriminant_constants,
            }))
        }
        Data::Union(_) => unimplemented!(),
    }
}

#[proc_macro_derive(TlsSize, attributes(tls_codec))]
pub fn size_macro_derive(input: TokenStream) -> TokenStream {
    let ast = parse_macro_input!(input as DeriveInput);
    let parsed_ast = parse_ast(ast).unwrap();
    impl_tls_size(parsed_ast).into()
}

#[proc_macro_derive(TlsSerialize, attributes(tls_codec))]
pub fn serialize_macro_derive(input: TokenStream) -> TokenStream {
    let ast = parse_macro_input!(input as DeriveInput);
    let parsed_ast = parse_ast(ast).unwrap();
    impl_serialize(parsed_ast).into()
}

#[proc_macro_derive(TlsDeserialize, attributes(tls_codec))]
pub fn deserialize_macro_derive(input: TokenStream) -> TokenStream {
    let ast = parse_macro_input!(input as DeriveInput);
    let parsed_ast = parse_ast(ast).unwrap();
    impl_deserialize(parsed_ast).into()
}

/// Returns identifiers to use as bindings in generated code
fn make_n_ids(n: usize) -> Vec<Ident> {
    (0..n)
        .map(|i| Ident::new(&format!("__arg{}", i), Span::call_site()))
        .collect()
}

/// Returns identifier to define a constant equal to the discriminant of a variant
fn discriminant_id(variant: &Ident) -> Ident {
    Ident::new(&format!("__TLS_CODEC_{}", variant), Span::call_site())
}

/// Returns definitions of constants equal to the discriminants of each variant
fn define_discriminant_constants(
    enum_ident: &Ident,
    repr: &Ident,
    variants: &Punctuated<syn::Variant, Comma>,
) -> Result<TokenStream2> {
    let all_variants_are_unit = variants
        .iter()
        .all(|variant| matches!(variant.fields, syn::Fields::Unit));
    let discriminant_constants = if all_variants_are_unit {
        variants
            .iter()
            .map(|variant| {
                let variant_id = &variant.ident;
                let constant_id = discriminant_id(variant_id);
                if discriminant_value(&variant.attrs)?.is_some() {
                    Err(syn::Error::new(
                        Span::call_site(),
                        "The tls_codec discriminant attribute must only be used in enumerations \
                        with at least one non-unit variant. When all variants are units, \
                        discriminants can be assigned to variants directly.",
                    ))
                } else {
                    Ok(quote! {
                        const #constant_id: #repr = #enum_ident::#variant_id as #repr;
                    })
                }
            })
            .collect::<Result<Vec<_>>>()?
    } else {
        variants
            .iter()
            .try_fold((0, Vec::new()), |(next, mut acc), variant| {
                let constant_id = discriminant_id(&variant.ident);
                let value = discriminant_value(&variant.attrs)?.unwrap_or(next);
                acc.push(quote! {
                    const #constant_id: #repr = #value as #repr;
                });
                Ok::<_, syn::Error>((value + 1, acc))
            })?
            .1
    };
    Ok(quote! { #(#discriminant_constants)* })
}

#[allow(unused_variables)]
fn impl_tls_size(parsed_ast: TlsStruct) -> TokenStream2 {
    match parsed_ast {
        TlsStruct::Struct(Struct {
            call_site,
            ident,
            generics,
            members,
            member_prefixes,
        }) => {
            let prefixes = member_prefixes
                .iter()
                .map(|p| p.for_trait("Size"))
                .collect::<Vec<_>>();
            quote! {
                impl #generics tls_codec::Size for #ident #generics {
                    #[inline]
                    fn tls_serialized_len(&self) -> usize {
                        #(#prefixes::tls_serialized_len(&self.#members) + )*
                        0
                    }
                }

                impl #generics tls_codec::Size for &#ident #generics {
                    #[inline]
                    fn tls_serialized_len(&self) -> usize {
                        tls_codec::Size::tls_serialized_len(*self)
                    }
                }
            }
        }
        TlsStruct::Enum(Enum {
            call_site,
            ident,
            generics,
            repr,
            variants,
            ..
        }) => {
            let field_arms = variants
                .iter()
                .map(|variant| {
                    let variant_id = &variant.ident;
                    let members = &variant.members;
                    let bindings = make_n_ids(members.len());
                    let prefixes = variant.member_prefixes.iter().map(|p| p.for_trait("Size")).collect::<Vec<_>>();
                    quote! {
                        #ident::#variant_id { #(#members: #bindings,)* } => 0 #(+ #prefixes::tls_serialized_len(#bindings))*,
                    }
                })
                .collect::<Vec<_>>();
            quote! {
                impl #generics tls_codec::Size for #ident #generics {
                    #[inline]
                    fn tls_serialized_len(&self) -> usize {
                        let field_len = match self {
                            #(#field_arms)*
                        };
                        std::mem::size_of::<#repr>() + field_len
                    }
                }

                impl #generics tls_codec::Size for &#ident #generics {
                    #[inline]
                    fn tls_serialized_len(&self) -> usize {
                        tls_codec::Size::tls_serialized_len(*self)
                    }
                }
            }
        }
    }
}

#[allow(unused_variables)]
fn impl_serialize(parsed_ast: TlsStruct) -> TokenStream2 {
    match parsed_ast {
        TlsStruct::Struct(Struct {
            call_site,
            ident,
            generics,
            members,
            member_prefixes,
        }) => {
            let prefixes = member_prefixes
                .iter()
                .map(|p| p.for_trait("Serialize"))
                .collect::<Vec<_>>();
            quote! {
                impl #generics tls_codec::Serialize for #ident #generics {
                    fn tls_serialize<W: std::io::Write>(&self, writer: &mut W) -> core::result::Result<usize, tls_codec::Error> {
                        let mut written = 0usize;
                        #(
                            written += #prefixes::tls_serialize(&self.#members, writer)?;
                        )*
                        if cfg!(debug_assertions) {
                            let expected_written = tls_codec::Size::tls_serialized_len(&self);
                            debug_assert_eq!(written, expected_written, "Expected to serialize {} bytes but only {} were generated.", expected_written, written);
                            if written != expected_written {
                                Err(tls_codec::Error::EncodingError(format!("Expected to serialize {} bytes but only {} were generated.", expected_written, written)))
                            } else {
                                Ok(written)
                            }
                        } else {
                            Ok(written)
                        }
                    }
                }

                impl #generics tls_codec::Serialize for &#ident #generics {
                    fn tls_serialize<W: std::io::Write>(&self, writer: &mut W) -> core::result::Result<usize, tls_codec::Error> {
                        tls_codec::Serialize::tls_serialize(*self, writer)
                    }
                }
            }
        }
        TlsStruct::Enum(Enum {
            call_site,
            ident,
            generics,
            repr,
            variants,
            discriminant_constants,
        }) => {
            let arms = variants
                .iter()
                .map(|variant| {
                    let variant_id = &variant.ident;
                    let discriminant = discriminant_id(variant_id);
                    let members = &variant.members;
                    let bindings = make_n_ids(members.len());
                    let prefixes = variant
                        .member_prefixes
                        .iter()
                        .map(|p| p.for_trait("Serialize"))
                        .collect::<Vec<_>>();
                    quote! {
                        #ident::#variant_id { #(#members: #bindings,)* } => Ok(
                            tls_codec::Serialize::tls_serialize(&#discriminant, writer)?
                            #(+ #prefixes::tls_serialize(#bindings, writer)?)*
                        ),
                    }
                })
                .collect::<Vec<_>>();
            quote! {
                impl #generics tls_codec::Serialize for #ident #generics {
                    fn tls_serialize<W: std::io::Write>(&self, writer: &mut W) -> core::result::Result<usize, tls_codec::Error> {
                        #discriminant_constants
                        match self {
                            #(#arms)*
                        }
                    }
                }

                impl #generics tls_codec::Serialize for &#ident #generics {
                    fn tls_serialize<W: std::io::Write>(&self, writer: &mut W) -> core::result::Result<usize, tls_codec::Error> {
                        tls_codec::Serialize::tls_serialize(*self, writer)
                    }
                }
            }
        }
    }
}

#[allow(unused_variables)]
fn impl_deserialize(parsed_ast: TlsStruct) -> TokenStream2 {
    match parsed_ast {
        TlsStruct::Struct(Struct {
            call_site,
            ident,
            generics,
            members,
            member_prefixes,
        }) => {
            let prefixes = member_prefixes
                .iter()
                .map(|p| p.for_trait("Deserialize"))
                .collect::<Vec<_>>();
            quote! {
                impl tls_codec::Deserialize for #ident {
                    fn tls_deserialize<R: std::io::Read>(bytes: &mut R) -> core::result::Result<Self, tls_codec::Error> {
                        Ok(Self {
                            #(#members: #prefixes::tls_deserialize(bytes)?,)*
                        })
                    }
                }
            }
        }
        TlsStruct::Enum(Enum {
            call_site,
            ident,
            generics,
            repr,
            variants,
            discriminant_constants,
        }) => {
            let arms = variants
                .iter()
                .map(|variant| {
                    let variant_id = &variant.ident;
                    let discriminant = discriminant_id(variant_id);
                    let members = &variant.members;
                    let prefixes = variant
                        .member_prefixes
                        .iter()
                        .map(|p| p.for_trait("Deserialize"))
                        .collect::<Vec<_>>();
                    quote! {
                        #discriminant => Ok(#ident::#variant_id {
                            #(#members: #prefixes::tls_deserialize(bytes)?,)*
                        }),
                    }
                })
                .collect::<Vec<_>>();
            quote! {
                impl tls_codec::Deserialize for #ident {
                    #[allow(non_upper_case_globals)]
                    fn tls_deserialize<R: std::io::Read>(bytes: &mut R) -> core::result::Result<Self, tls_codec::Error> {
                        #discriminant_constants
                        let discriminant = <#repr as tls_codec::Deserialize>::tls_deserialize(bytes)?;
                        match discriminant {
                            #(#arms)*
                            _ => {
                                Err(tls_codec::Error::DecodingError(format!("Unmatched discriminant {:?} in tls_deserialize", discriminant)))
                            },
                        }
                    }
                }
            }
        }
    }
}