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
// Copyright (c) Facebook, Inc. and its affiliates.
//
// This source code is licensed under the MIT license found in the
// LICENSE file in the root directory of this source tree.

//! # Derive macros for opaque-ke

use proc_macro2::{Span, TokenStream};
use quote::{quote, quote_spanned};
use syn::{
    parse_quote, spanned::Spanned, Data, DeriveInput, Fields, GenericParam, Generics, Index,
};

//////////////////////////
// TryFromForSizedBytes //
//////////////////////////

/// Derive TryFrom<&[u8], Error = ErrorType> for any T: SizedBytes, assuming
/// ErrorType: Default. This proc-macro is here to work around the lack of
/// specialization, but there's nothing otherwise clever about it.
#[proc_macro_derive(TryFromForSizedBytes, attributes(ErrorType))]
pub fn try_from_for_sized_bytes(source: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let ast: DeriveInput = syn::parse(source).expect("Incorrect macro input");
    let name = &ast.ident;

    let error_type = get_type_from_attrs(&ast.attrs, "ErrorType").unwrap();

    let generics = add_basic_bound(ast.generics);
    let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();

    let gen = quote! {
        impl #impl_generics ::std::convert::TryFrom<&[u8]> for #name #ty_generics #where_clause {
            type Error = #error_type;

            fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
                let expected_len = <<Self as ::generic_bytes::SizedBytes>::Len as generic_array::typenum::Unsigned>::to_usize();
                if bytes.len() != expected_len {
                    return Err(#error_type::default());
                }
                let arr = GenericArray::from_slice(bytes);
                <Self as ::generic_bytes::SizedBytes>::from_arr(arr).map_err(|_| #error_type::default())
            }
        }
    };
    gen.into()
}

fn get_type_from_attrs(attrs: &[syn::Attribute], attr_name: &str) -> syn::Result<syn::Type> {
    attrs
        .iter()
        .find(|attr| attr.path.is_ident(attr_name))
        .map_or_else(
            || {
                Err(syn::Error::new(
                    proc_macro2::Span::call_site(),
                    format!("Could not find attribute {}", attr_name),
                ))
            },
            |attr| match attr.parse_meta()? {
                syn::Meta::NameValue(meta) => {
                    if let syn::Lit::Str(lit) = &meta.lit {
                        Ok(lit.clone())
                    } else {
                        Err(syn::Error::new_spanned(
                            meta,
                            &format!("Could not parse {} attribute", attr_name)[..],
                        ))
                    }
                }
                bad => Err(syn::Error::new_spanned(
                    bad,
                    &format!("Could not parse {} attribute", attr_name)[..],
                )),
            },
        )
        .and_then(|str| str.parse())
}

// add `T: SizedBytes` to each generic parameter
fn add_basic_bound(mut generics: Generics) -> Generics {
    for param in &mut generics.params {
        if let GenericParam::Type(ref mut type_param) = *param {
            type_param
                .bounds
                .push(parse_quote!(::generic_bytes::SizedBytes));
        }
    }
    generics
}

////////////////
// SizedBytes //
////////////////

// add where cause which reflects the bound propagation for generic SizedBytes clauses
fn add_trait_bounds(
    generics: &mut Generics,
    data: &syn::Data,
    bound: syn::Path,
) -> Result<(), syn::Error> {
    if generics.params.is_empty() {
        return Ok(());
    }

    let types = collect_types(&data)?;
    if !types.is_empty() {
        let where_clause = generics.make_where_clause();

        types
            .into_iter()
            .for_each(|ty| where_clause.predicates.push(parse_quote!(#ty : #bound)));
        bounds_sum(data, where_clause)?;
    }

    Ok(())
}

fn collect_types(data: &syn::Data) -> Result<Vec<syn::Type>, syn::Error> {
    use syn::*;

    let types = match *data {
        Data::Struct(ref data) => match &data.fields {
            Fields::Named(FieldsNamed { named: fields, .. })
            | Fields::Unnamed(FieldsUnnamed {
                unnamed: fields, ..
            }) => fields.iter().map(|f| f.ty.clone()).collect(),

            Fields::Unit => Vec::new(),
        },

        Data::Enum(ref data) => data
            .variants
            .iter()
            .flat_map(|variant| match &variant.fields {
                Fields::Named(FieldsNamed { named: fields, .. })
                | Fields::Unnamed(FieldsUnnamed {
                    unnamed: fields, ..
                }) => fields.iter().map(|f| f.ty.clone()).collect(),

                Fields::Unit => Vec::new(),
            })
            .collect(),

        Data::Union(_) => {
            return Err(Error::new(
                Span::call_site(),
                "Union types are not supported.",
            ))
        }
    };

    Ok(types)
}

fn extract_size_type_from_generic_array(ty: &syn::Type) -> Option<&syn::Type> {
    fn path_is_generic_array(path: &syn::Path) -> Option<&syn::GenericArgument> {
        path.segments.iter().find_map(|pt| {
            if pt.ident == "GenericArray" {
                // It should have only on angle-bracketed param ("<Foo, Bar>"):
                match &pt.arguments {
                    syn::PathArguments::AngleBracketed(params) if params.args.len() == 2 => {
                        params.args.last()
                    }
                    _ => None,
                }
            } else {
                None
            }
        })
    }

    match ty {
        syn::Type::Path(typepath)
            if typepath.qself.is_none()
                && typepath
                    .path
                    .segments
                    .iter()
                    .any(|pt| pt.ident == "GenericArray") =>
        {
            // Get the second parameter of the GenericArray
            let type_param = path_is_generic_array(&typepath.path);
            // This argument must be a type:
            if let Some(syn::GenericArgument::Type(ty)) = type_param {
                Some(ty)
            } else {
                None
            }
        }
        _ => None,
    }
}

fn bounds_sum(data: &Data, where_clause: &mut syn::WhereClause) -> Result<(), syn::Error> {
    match *data {
        Data::Struct(ref data) => {
            match data.fields {
                Fields::Named(ref fields) => {
                    let mut quote = None;
                    for f in fields.named.iter() {
                        let ty = &f.ty;
                        let res =
                            if let Some(unsigned_ty) = extract_size_type_from_generic_array(ty) {
                                quote_spanned! {f.span()=>
                                                #unsigned_ty
                                }
                            } else {
                                quote_spanned! {f.span()=>
                                                <#ty as ::generic_bytes::SizedBytes>::Len
                                }
                            };
                        if let Some(ih) = quote {
                            quote = Some(quote! {
                                ::generic_array::typenum::Sum<#ih, #res>
                            });
                            where_clause
                                .predicates
                                .push(parse_quote!(#ih: ::core::ops::Add<#res>));
                            where_clause
                                .predicates
                                .push(parse_quote!(::generic_array::typenum::Sum<#ih, #res> : ::generic_array::ArrayLength<u8> + ::core::ops::Sub<#ih, Output = #res>));
                            where_clause
                                .predicates
                                .push(parse_quote!(::generic_array::typenum::Diff<::generic_array::typenum::Sum<#ih, #res>, #ih> : ::generic_array::ArrayLength<u8>));
                        } else {
                            quote = Some(res);
                        }
                    }
                    Ok(())
                }
                Fields::Unnamed(ref fields) => {
                    let mut quote = None;
                    for f in fields.unnamed.iter() {
                        let ty = &f.ty;
                        let res =
                            if let Some(unsigned_ty) = extract_size_type_from_generic_array(ty) {
                                quote_spanned! {f.span()=>
                                                #unsigned_ty
                                }
                            } else {
                                quote_spanned! {f.span()=>
                                                <#ty as ::generic_bytes::SizedBytes>::Len
                                }
                            };
                        if let Some(ih) = quote {
                            quote = Some(quote! {
                                ::generic_array::typenum::Sum<#ih, #res>
                            });
                            where_clause
                                .predicates
                                .push(parse_quote!(#ih : ::core::ops::Add<#res>));
                            where_clause
                                .predicates
                                .push(parse_quote!(::generic_array::typenum::Sum<#ih, #res> : ::generic_array::ArrayLength<u8> + ::core::ops::Sub<#ih, Output = #res>));
                            where_clause
                                .predicates
                                .push(parse_quote!(::generic_array::typenum::Diff<::generic_array::typenum::Sum<#ih, #res>, #ih> : ::generic_array::ArrayLength<u8>));
                        } else {
                            quote = Some(res);
                        }
                    }
                    Ok(())
                }
                Fields::Unit => {
                    // Unit structs cannot own more than 0 bytes of heap memory.
                    unimplemented!()
                }
            }
        }
        Data::Enum(_) | Data::Union(_) => unimplemented!(),
    }
}

// create a type expression summing up the ::Len of each field
fn sum(data: &Data) -> TokenStream {
    match *data {
        Data::Struct(ref data) => {
            match data.fields {
                Fields::Named(ref fields) => {
                    let mut quote = None;
                    for f in fields.named.iter() {
                        let ty = &f.ty;
                        let res = quote_spanned! {f.span()=>
                            <#ty as ::generic_bytes::SizedBytes>::Len
                        };
                        if let Some(ih) = quote {
                            quote = Some(quote! {
                                ::generic_array::typenum::Sum<#ih, #res>
                            });
                        } else {
                            quote = Some(res);
                        }
                    }
                    quote! {
                        #quote
                    }
                }
                Fields::Unnamed(ref fields) => {
                    let mut quote = None;
                    for f in fields.unnamed.iter() {
                        let ty = &f.ty;
                        let res = quote_spanned! {f.span()=>
                            <#ty as ::generic_bytes::SizedBytes>::Len
                        };
                        if let Some(ih) = quote {
                            quote = Some(quote! {
                                ::generic_array::typenum::Sum<#ih, #res>
                            });
                        } else {
                            quote = Some(res);
                        }
                    }
                    quote! {
                        #quote
                    }
                }
                Fields::Unit => {
                    // Unit structs cannot own more than 0 bytes of heap memory.
                    unimplemented!()
                }
            }
        }
        Data::Enum(_) | Data::Union(_) => unimplemented!(),
    }
}

// Generate an expression to concatenate the to_arr of each field
fn byte_concatenation(data: &Data) -> TokenStream {
    match *data {
        Data::Struct(ref data) => {
            match data.fields {
                Fields::Named(ref fields) => {
                    let mut quote = None;
                    for f in fields.named.iter() {
                        let name = &f.ident;
                        let res = quote_spanned! {f.span()=>
                            ::generic_bytes::SizedBytes::to_arr(&self.#name)
                        };
                        if let Some(ih) = quote {
                            quote = Some(quote! {
                                ::generic_array::sequence::Concat::concat(#ih, #res)
                            });
                        } else {
                            quote = Some(res);
                        }
                    }
                    quote! {
                        #quote
                    }
                }
                Fields::Unnamed(ref fields) => {
                    let mut quote = None;
                    for (i, f) in fields.unnamed.iter().enumerate() {
                        let index = Index::from(i);
                        let res = quote_spanned! {f.span()=>
                            ::generic_bytes::SizedBytes::to_arr(&self.#index)
                        };
                        if let Some(ih) = quote {
                            quote = Some(quote! {
                                ::generic_array::sequence::Concat::concat(#ih, #res)
                            });
                        } else {
                            quote = Some(res);
                        }
                    }
                    quote! {
                        #quote
                    }
                }
                Fields::Unit => {
                    // Unit structs cannot own more than 0 bytes of heap memory.
                    quote!(0)
                }
            }
        }
        Data::Enum(_) | Data::Union(_) => unimplemented!(),
    }
}

// Generate an expression to concatenate the to_arr of each field
fn byte_splitting(constr: &proc_macro2::Ident, data: &Data) -> TokenStream {
    match *data {
        Data::Struct(ref data) => {
            match data.fields {
                Fields::Named(ref fields) => {
                    let l = fields.named.len();
                    let setup: TokenStream = fields
                        .named
                        .iter().enumerate()
                        .map(|(i, f)| {
                            let name = &f.ident;
                            let ty = &f.ty;

                            if i < (l-1) {
                                quote_spanned! {f.span()=>
                                    let (head, _tail): (&GenericArray<u8, <#ty as ::generic_bytes::SizedBytes>::Len>, &GenericArray<u8, _>) =
                                                generic_array::sequence::Split::split(_tail);
                                    let #name: #ty = ::generic_bytes::SizedBytes::from_arr(head)?;
                                }
                            } else {
                                quote_spanned!{f.span() =>
                                    let #name: #ty = ::generic_bytes::SizedBytes::from_arr(_tail)?;
                                }
                            }
                        })
                        .collect();

                    let conclude: TokenStream = fields
                        .named
                        .iter()
                        .map(|f| {
                            let name = &f.ident;
                            quote_spanned! {f.span()=>
                                #name,
                            }
                        })
                        .collect();
                    quote! {
                        let _tail = arr;
                        #setup
                        Ok(#constr {
                            #conclude
                        })
                    }
                }
                Fields::Unnamed(ref fields) => {
                    let l = fields.unnamed.len();
                    let setup: TokenStream = fields
                        .unnamed
                        .iter()
                        .enumerate()
                        .map(|(i, f)| {
                            let ty = &f.ty;
                            if i < (l-1) {
                                let field_name = format!("f_{}", i);
                                let fname = syn::Ident::new(&field_name, f.span());
                                quote_spanned! {f.span()=>
                                                let (head, _tail) = generic_array::sequence::Split::split(_tail);
                                                let #fname: #ty = ::generic_bytes::SizedBytes::from_arr(head)?;
                                }
                            } else {
                                let field_name = format!("f_{}", i);
                                let fname = syn::Ident::new(&field_name, f.span());
                                quote_spanned! {f.span()=>
                                                let #fname: #ty = ::generic_bytes::SizedBytes::from_arr(_tail)?;
                                }
                            }
                        })
                        .collect();

                    let conclude: TokenStream = fields
                        .unnamed
                        .iter()
                        .enumerate()
                        .map(|(i, f)| {
                            let field_name = format!("f_{}", i);
                            let fname = syn::Ident::new(&field_name, f.span());
                            quote_spanned! {f.span()=>
                                #fname,
                            }
                        })
                        .collect();
                    quote! (
                        let _tail = arr;
                        #setup
                        Ok(#constr (
                            #conclude
                        ))
                    )
                }
                Fields::Unit => {
                    // Unit structs cannot own more than 0 bytes of heap memory.
                    quote!(0)
                }
            }
        }
        Data::Enum(_) | Data::Union(_) => unimplemented!(),
    }
}

#[proc_macro_derive(SizedBytes)]
pub fn derive_sized_bytes(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let mut input: DeriveInput = match syn::parse(input) {
        Ok(input) => input,
        Err(e) => return e.to_compile_error().into(),
    };
    let name = &input.ident;

    // Add a bound `T::From : SizedBytes` to every type parameter occurrence `T::From`.
    if let Err(e) = add_trait_bounds(
        &mut input.generics,
        &input.data,
        parse_quote!(::generic_bytes::SizedBytes),
    ) {
        return e.to_compile_error().into();
    };

    let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();

    // Generate an expression to sum the type lengths of each field.
    let types_sum = sum(&input.data);

    // Generate an expression to concatenate each field.
    let to_arr_impl = byte_concatenation(&input.data);

    // Generate an expression to ingest each field.
    let from_arr_impl = byte_splitting(name, &input.data);

    let res = quote! (
        // The generated impl.
        impl #impl_generics ::generic_bytes::SizedBytes for #name #ty_generics #where_clause {

            type Len = #types_sum;

            fn to_arr(&self) -> GenericArray<u8, Self::Len> {
                #to_arr_impl
            }

            fn from_arr(arr: &GenericArray<u8, Self::Len>) -> Result<Self, ::generic_bytes::TryFromSizedBytesError> {
                #from_arr_impl
            }
        }
    );
    res.into()
}