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
use proc_macro2::{Span, TokenStream};
use quote::{format_ident, quote};
use std::ops::Not;
use syn::{
    parse_macro_input, parse_quote_spanned, Attribute, Data, DeriveInput, Error, Fields, Generics,
    Index, Lit, Meta, NestedMeta, Path, Result, Type, Variant, WherePredicate,
};

/// Derives the `SizeOf` trait for the given item
///
/// Works on structs and enums, `SizeOf` must be implemented manually for unions
/// unless the `#[size_of(skip_all)]` top-level attribute is used
///
/// Accepted attributes:
/// - `#[size_of(crate = "<crate_path>")]` allows setting the path to the
///   `size_of` crate, this is only allowed at the top level
/// - `#[size_of(skip_all)]` allows skipping all fields or variants of the item,
///   this is only allowed at the top level
/// - `#[size_of(skip)]` skips the current variant or field
/// - `#[size_of(skip_bounds)]` skips emitting trait bounds for the current
///   variant/field, allows compiling things like `struct Foo { bar: Box<Self>
///   }`
///
/// # Examples
///
/// Normal derive usage
///
/// ```rust,ignore
/// #[derive(SizeOf)]
/// struct Foo {
///     bar: Vec<u8>,
///     baz: String,
/// }
/// ```
///
/// Skips collecting the sizes of all children
///
/// ```rust,ignore
/// #[derive(SizeOf)]
/// #[size_of(skip_all)]
/// struct Foo {
///     bar: Vec<u8>,
///     baz: String,
/// }
/// ```
///
/// Skip collecting the size of a specific field/variant
///
/// ```rust,ignore
/// #[derive(SizeOf)]
/// struct Foo {
///     bar: Vec<u8>,
///     #[size_of(skip)]
///     baz: String,
/// }
///
/// #[derive(SizeOf)]
/// enum Bar {
///     #[size_of(skip)]
///     Baz,
///     #[size_of(skip)]
///     Bing(u8),
///     Bong {
///         #[size_of(skip)]
///         boo: String,
///     },
/// }
/// ```
///
/// Skip the bounds of a specific field/variant. The size of the field and all
/// of its children will still be collected, however a `FieldType: SizeOf` bound
/// will not be emitted. This will cause compile errors if `FieldType` doesn't
/// implement `SizeOf`, but it's necessary for recursive types.
///
/// ```rust,ignore
/// #[derive(SizeOf)]
/// struct Foo {
///     #[size_of(skip_bounds)]
///     baz: Vec<Self>,
/// }
/// ```
#[proc_macro_derive(SizeOf, attributes(size_of))]
pub fn size_of_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
    let input = parse_macro_input!(input as DeriveInput);

    size_of_derive_inner(input)
        .unwrap_or_else(Error::into_compile_error)
        .into()
}

// TODO: Emit an error on unrecognized or invalid `#[size_of]` attributes
// TODO: Add `#[size_of(size = <expr>, excess = <expr>, shared = <expr>,
// allocations = <expr>)]`
fn size_of_derive_inner(input: DeriveInput) -> Result<TokenStream> {
    // If the user specified a crate name to replace the default of `::size_of`,
    // use it and otherwise just fall back to `::size_of`
    let crate_path = find_crate_name(&input.attrs)?
        .unwrap_or_else(|| parse_quote_spanned!(Span::mixed_site() => ::size_of));

    // We allow skipping the entire struct for any type (structs, enums and unions)
    if has_skip_all(&input.attrs) {
        let type_name = &input.ident;
        let (intro_generics, fwd_generics, where_clause) = input.generics.split_for_impl();

        return Ok(quote! {
            #[automatically_derived]
            impl #intro_generics #crate_path::SizeOf for #type_name #fwd_generics
                #where_clause
            {
                #[inline]
                fn size_of_children(&self, context: &mut #crate_path::Context) {}
            }
        });

    // `#[size_of(skip)]` isn't accepted at the top level
    } else if let Some(attr) = find_skip(&input.attrs) {
        return Err(Error::new_spanned(
            attr,
            "#[size_of(skip)] is not supported on top-level items, use `#[size_of(skip_all)] instead",
        ));

    // `#[size_of(skip_bounds)]` isn't currently supported at the top level
    // FIXME: Implement this
    } else if let Some(attr) = find_skip_bounds(&input.attrs) {
        return Err(Error::new_spanned(
            attr,
            "#[size_of(skip_bounds)] is not currently supported on top-level items",
        ));
    }

    match &input.data {
        Data::Struct(structure) => {
            let struct_name = &input.ident;

            // Collect info for the fields
            let (field_types, field_sizes) = collect_field_info(&crate_path, &structure.fields);

            // Build the generic bounds for the impl
            let generics = make_generic_bounds(&input, &crate_path, &field_types);
            let (intro_generics, fwd_generics, where_clause) = generics.split_for_impl();

            // Inline empty bodies
            let attr = if field_sizes.is_empty() {
                quote! { #[inline] }
            } else {
                TokenStream::new()
            };

            Ok(quote! {
                #[automatically_derived]
                impl #intro_generics #crate_path::SizeOf for #struct_name #fwd_generics
                    #where_clause
                {
                    #attr
                    fn size_of_children(&self, context: &mut #crate_path::Context) {
                        #(#field_sizes;)*
                    }
                }
            })
        }

        Data::Enum(enumeration) => {
            // Flatten and dedup all types used within all unskipped variants
            let mut variant_types: Vec<_> = enumeration
                .variants
                .iter()
                .flat_map(|variant| {
                    // Do nothing for skipped variants
                    if has_skip(&variant.attrs) {
                        Vec::new()
                    } else {
                        collect_field_info(&crate_path, &variant.fields).0
                    }
                })
                .collect();
            dedup_types(&mut variant_types);

            let match_arms = enumeration.variants.iter().map(|variant| {
                let variant_name = &variant.ident;

                match &variant.fields {
                    Fields::Named(named) => {
                        let mut needs_ellipses = false;
                        let idents: Vec<_> = named
                            .named
                            .iter()
                            .filter_map(|field| {
                                if has_skip(&field.attrs) {
                                    needs_ellipses = true;
                                    None
                                } else {
                                    Some(field.ident.as_ref().unwrap())
                                }
                            })
                            .collect();
                        let ellipses = needs_ellipses.then(|| quote!(..));

                        let body = named.named.iter().map(|field| {
                            if has_skip(&field.attrs) {
                                TokenStream::new()
                            } else {
                                let ident = &field.ident;
                                let ty = &field.ty;
                                quote! {
                                    <#ty as #crate_path::SizeOf>::size_of_children(#ident, context);
                                }
                            }
                        });

                        quote! {
                            Self::#variant_name { #(#idents,)* #ellipses } => {
                                #(#body)*
                            }
                        }
                    }

                    Fields::Unnamed(unnamed) => {
                        let idents = unnamed.unnamed.iter().enumerate().map(|(idx, field)| {
                            if has_skip(&field.attrs) {
                                quote! { _ }
                            } else {
                                let idx = format_ident!("_{idx}");
                                quote! { #idx }
                            }
                        });

                        let body = unnamed.unnamed.iter().enumerate().map(|(idx, field)| {
                            if has_skip(&field.attrs) {
                                TokenStream::new()
                            } else {
                                let ident = format_ident!("_{idx}");
                                let ty = &field.ty;
                                quote! {
                                    <#ty as #crate_path::SizeOf>::size_of_children(#ident, context);
                                }
                            }
                        });

                        quote! {
                            Self::#variant_name(#(#idents),*) => {
                                #(#body)*
                            }
                        }
                    }

                    // Do nothing for unit variants
                    Fields::Unit => quote! { Self::#variant_name => {} },
                }
            });

            // Build the generic bounds for the impl
            let generics = make_generic_bounds(&input, &crate_path, &variant_types);
            let (intro_generics, fwd_generics, where_clause) = generics.split_for_impl();
            let tuple_name = &input.ident;

            // Special casing uninhabited enums, references are always considered inhabited
            // so we just dereference the value and match on that
            let body = if enumeration.variants.is_empty() {
                quote! {
                    match *self {}
                }

            // If all variants are empty, skipped or have no unskipped fields
            // then we can emit nothing as the body
            } else if all_variants_empty(enumeration.variants.iter()) {
                TokenStream::new()

            // For inhabited enums we still match on the referenced value
            } else {
                quote! {
                    match self {
                        #(#match_arms)*
                    }
                }
            };

            Ok(quote! {
                #[automatically_derived]
                impl #intro_generics #crate_path::SizeOf for #tuple_name #fwd_generics
                    #where_clause
                {
                    fn size_of_children(&self, context: &mut #crate_path::Context) {
                        #body
                    }
                }
            })
        }

        // We can't automatically derive for unions
        Data::Union(_) => Err(Error::new_spanned(
            input,
            "cannot derive TotalSize on unions, try manually implementing it",
        )),
    }
}

/// Returns `true` if the number of given variants that:
/// - Are not skipped
/// - Have at least one unskipped field
/// Is greater than zero
fn all_variants_empty<'a, I>(mut variants: I) -> bool
where
    I: Iterator<Item = &'a Variant> + 'a,
{
    variants.all(|variant| {
        has_skip(&variant.attrs)
            || variant
                .fields
                .iter()
                .filter(|field| !has_skip(&field.attrs))
                .count()
                == 0
    })
}

fn make_generic_bounds(input: &DeriveInput, crate_path: &Path, field_types: &[&Type]) -> Generics {
    let mut generics = input.generics.clone();

    // Add SizeOf bounds to all all unskipped fields of the type
    generics
        .make_where_clause()
        .predicates
        .extend(field_types.iter().map(|field_ty| -> WherePredicate {
            parse_quote_spanned!(Span::mixed_site() => #field_ty: #crate_path::SizeOf)
        }));

    generics
}

fn collect_field_info<'a>(
    crate_path: &Path,
    fields: &'a Fields,
) -> (Vec<&'a Type>, Vec<TokenStream>) {
    let (mut field_types, field_sizes): (Vec<_>, Vec<_>) = match fields {
        // Collect all field types that aren't annotated with a skip attribute
        Fields::Named(fields) => {
            fields
                .named
                .iter()
                .flat_map(|field| {
                    if has_skip(&field.attrs) || has_skip_bounds(&field.attrs) {
                        None
                    } else {
                        let field_type = &field.ty;
                        let field_ident = &field.ident;
                        let field_size = quote! {
                            <#field_type as #crate_path::SizeOf>::size_of_children(&self.#field_ident, context)
                        };

                        Some((field_type, field_size))
                    }
                })
                .unzip()
        }

        // We need field indices for tuple structs
        Fields::Unnamed(fields) => {
            fields
                .unnamed
                .iter()
                .enumerate()
                .flat_map(|(idx, field)| has_skip(&field.attrs).not().then(|| {
                    let field_type = &field.ty;
                    let idx = Index::from(idx);
                    let field_size = quote! {
                        <#field_type as #crate_path::SizeOf>::size_of_children(&self.#idx, context)
                    };

                    (field_type, field_size)
                }))
                .unzip()
        }

        // We give no (extra) bounds on unit structs
        Fields::Unit => (Vec::new(), Vec::new()),
    };

    // Deduplicate the types we add bounds to so that we reduce the amount of code
    // we generate
    dedup_types(&mut field_types);

    (field_types, field_sizes)
}

/// Deduplicate all types within the given vec
fn dedup_types(field_types: &mut Vec<&Type>) {
    let mut idx = 0;
    while idx < field_types.len() {
        let current = field_types[idx];

        let mut field_idx = 0;
        field_types.retain(|&ty| {
            let should_retain = if field_idx <= idx {
                true
            } else {
                ty != current
            };
            field_idx += 1;

            should_retain
        });

        idx += 1;
    }
}

/// Returns the path set in the top-level `#[size_of(crate_path = "<path>")]`
/// attribute (if present)
fn find_crate_name(attrs: &[Attribute]) -> Result<Option<Path>> {
    for attr in attrs {
        if let Ok(Meta::List(meta)) = attr.parse_meta() {
            if meta.path.is_ident("size_of") {
                for nested in &meta.nested {
                    if let NestedMeta::Meta(Meta::NameValue(pair)) = nested {
                        if pair.path.is_ident("crate") {
                            if let Lit::Str(path) = &pair.lit {
                                return path.parse().map(Some);
                            }
                        }
                    }
                }
            }
        }
    }

    Ok(None)
}

/// Returns `true` if any of the given attributes has an `ident` meta, e.g.
/// `#[size_of(<ident>)]`
fn has_ident_attr(ident: &str, attrs: &[Attribute]) -> bool {
    for attr in attrs {
        if let Ok(Meta::List(meta)) = attr.parse_meta() {
            if meta.path.is_ident("size_of") {
                for nested in &meta.nested {
                    if matches!(nested, NestedMeta::Meta(Meta::Path(path)) if path.is_ident(ident))
                    {
                        return true;
                    }
                }
            }
        }
    }

    false
}

fn find_ident_attr(ident: &str, attrs: &[Attribute]) -> Option<NestedMeta> {
    for attr in attrs {
        if let Ok(Meta::List(meta)) = attr.parse_meta() {
            if meta.path.is_ident("size_of") {
                for nested in &meta.nested {
                    if matches!(nested, NestedMeta::Meta(Meta::Path(path)) if path.is_ident(ident))
                    {
                        return Some(nested.clone());
                    }
                }
            }
        }
    }

    None
}

/// Returns `true` if any of the given attributes is `#[size_of(skip)]`
fn has_skip_all(attrs: &[Attribute]) -> bool {
    has_ident_attr("skip_all", attrs)
}

/// Returns `true` if any of the given attributes is `#[size_of(skip)]`
fn has_skip(attrs: &[Attribute]) -> bool {
    has_ident_attr("skip", attrs)
}

/// Returns the `#[size_of(skip)]` meta if it exists
fn find_skip(attrs: &[Attribute]) -> Option<NestedMeta> {
    find_ident_attr("skip", attrs)
}

/// Returns `true` if any of the given attributes is `#[size_of(skip_bounds)]`
fn has_skip_bounds(attrs: &[Attribute]) -> bool {
    has_ident_attr("skip_bounds", attrs)
}

/// Returns the `#[size_of(skip_bounds)]` meta if it exists
fn find_skip_bounds(attrs: &[Attribute]) -> Option<NestedMeta> {
    find_ident_attr("skip_bounds", attrs)
}