Skip to main content

size_of_derive/
lib.rs

1use proc_macro2::{Span, TokenStream};
2use quote::{format_ident, quote};
3use std::{mem::replace, ops::Not};
4use syn::{
5    parse_macro_input, parse_quote_spanned, Attribute, Data, DeriveInput, Error, Fields, Generics,
6    Index, Lit, Meta, NestedMeta, Path, Result, ReturnType, Type, TypeArray, TypeBareFn, TypePtr,
7    TypeReference, TypeSlice, TypeTuple, Variant, WherePredicate,
8};
9
10/// Derives the `SizeOf` trait for the given item
11///
12/// Works on structs and enums, `SizeOf` must be implemented manually for unions
13/// unless the `#[size_of(skip_all)]` top-level attribute is used
14///
15/// Accepted attributes:
16/// - `#[size_of(crate = "<crate_path>")]` allows setting the path to the
17///   `size_of` crate, this is only allowed at the top level
18/// - `#[size_of(skip_all)]` allows skipping all fields or variants of the item,
19///   this is only allowed at the top level
20/// - `#[size_of(skip)]` skips the current variant or field
21/// - `#[size_of(skip_bounds)]` skips emitting trait bounds for the current
22///   variant/field, allows compiling things like `struct Foo { bar: Box<Self>
23///   }`
24///
25/// # Examples
26///
27/// Normal derive usage
28///
29/// ```rust,ignore
30/// #[derive(SizeOf)]
31/// struct Foo {
32///     bar: Vec<u8>,
33///     baz: String,
34/// }
35/// ```
36///
37/// Skips collecting the sizes of all children
38///
39/// ```rust,ignore
40/// #[derive(SizeOf)]
41/// #[size_of(skip_all)]
42/// struct Foo {
43///     bar: Vec<u8>,
44///     baz: String,
45/// }
46/// ```
47///
48/// Skip collecting the size of a specific field/variant
49///
50/// ```rust,ignore
51/// #[derive(SizeOf)]
52/// struct Foo {
53///     bar: Vec<u8>,
54///     #[size_of(skip)]
55///     baz: String,
56/// }
57///
58/// #[derive(SizeOf)]
59/// enum Bar {
60///     #[size_of(skip)]
61///     Baz,
62///     #[size_of(skip)]
63///     Bing(u8),
64///     Bong {
65///         #[size_of(skip)]
66///         boo: String,
67///     },
68/// }
69/// ```
70///
71/// Skip the bounds of a specific field/variant. The size of the field and all
72/// of its children will still be collected, however a `FieldType: SizeOf` bound
73/// will not be emitted. This will cause compile errors if `FieldType` doesn't
74/// implement `SizeOf`, but it's necessary for recursive types.
75///
76/// ```rust,ignore
77/// #[derive(SizeOf)]
78/// struct Foo {
79///     #[size_of(skip_bounds)]
80///     baz: Vec<Self>,
81/// }
82/// ```
83#[proc_macro_derive(SizeOf, attributes(size_of))]
84pub fn size_of_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
85    let input = parse_macro_input!(input as DeriveInput);
86
87    size_of_derive_inner(input)
88        .unwrap_or_else(Error::into_compile_error)
89        .into()
90}
91
92// TODO: Emit an error on unrecognized or invalid `#[size_of]` attributes
93// TODO: Add `#[size_of(size = <expr>, excess = <expr>, shared = <expr>,
94// allocations = <expr>)]`
95fn size_of_derive_inner(input: DeriveInput) -> Result<TokenStream> {
96    // If the user specified a crate name to replace the default of `::size_of`,
97    // use it and otherwise just fall back to `::size_of`
98    let crate_path = find_crate_name(&input.attrs)?
99        .unwrap_or_else(|| parse_quote_spanned!(Span::mixed_site() => ::size_of));
100
101    // We allow skipping the entire struct for any type (structs, enums and unions)
102    if has_skip_all(&input.attrs) {
103        let type_name = &input.ident;
104        let (intro_generics, fwd_generics, where_clause) = input.generics.split_for_impl();
105
106        return Ok(quote! {
107            #[automatically_derived]
108            impl #intro_generics #crate_path::SizeOf for #type_name #fwd_generics
109                #where_clause
110            {
111                #[inline]
112                fn size_of_children(&self, context: &mut #crate_path::Context) {}
113            }
114        });
115
116    // `#[size_of(skip)]` isn't accepted at the top level
117    } else if let Some(attr) = find_skip(&input.attrs) {
118        return Err(Error::new_spanned(
119            attr,
120            "#[size_of(skip)] is not supported on top-level items, use `#[size_of(skip_all)] instead",
121        ));
122
123    // `#[size_of(skip_bounds)]` isn't currently supported at the top level
124    // FIXME: Implement this
125    } else if let Some(attr) = find_skip_bounds(&input.attrs) {
126        return Err(Error::new_spanned(
127            attr,
128            "#[size_of(skip_bounds)] is not currently supported on top-level items",
129        ));
130    }
131
132    match &input.data {
133        Data::Struct(structure) => {
134            let struct_name = &input.ident;
135
136            // Collect info for the fields
137            let (field_types, field_sizes) = collect_field_info(&crate_path, &structure.fields);
138
139            // Build the generic bounds for the impl
140            let generics = make_generic_bounds(&input, &crate_path, &field_types);
141            let (intro_generics, fwd_generics, where_clause) = generics.split_for_impl();
142
143            // Inline empty bodies
144            let attr = if field_sizes.is_empty() {
145                quote! { #[inline] }
146            } else {
147                TokenStream::new()
148            };
149
150            Ok(quote! {
151                #[automatically_derived]
152                impl #intro_generics #crate_path::SizeOf for #struct_name #fwd_generics
153                    #where_clause
154                {
155                    #attr
156                    fn size_of_children(&self, context: &mut #crate_path::Context) {
157                        #(#field_sizes;)*
158                    }
159                }
160            })
161        }
162
163        Data::Enum(enumeration) => {
164            // Flatten and dedup all types used within all unskipped variants
165            let mut variant_types: Vec<_> = enumeration
166                .variants
167                .iter()
168                .flat_map(|variant| {
169                    // Do nothing for skipped variants
170                    if has_skip(&variant.attrs) {
171                        Vec::new()
172                    } else {
173                        collect_field_info(&crate_path, &variant.fields).0
174                    }
175                })
176                .collect();
177            dedup_types(&mut variant_types);
178
179            let match_arms = enumeration.variants.iter().map(|variant| {
180                let variant_name = &variant.ident;
181
182                match &variant.fields {
183                    Fields::Named(named) => {
184                        let mut needs_ellipses = false;
185                        let idents: Vec<_> = named
186                            .named
187                            .iter()
188                            .filter_map(|field| {
189                                if has_skip(&field.attrs) {
190                                    needs_ellipses = true;
191                                    None
192                                } else {
193                                    Some(field.ident.as_ref().unwrap())
194                                }
195                            })
196                            .collect();
197                        let ellipses = needs_ellipses.then(|| quote!(..));
198
199                        let body = named.named.iter().map(|field| {
200                            if has_skip(&field.attrs) {
201                                TokenStream::new()
202                            } else {
203                                let ident = &field.ident;
204                                let ty = normalize_type(field.ty.clone());
205                                quote! {
206                                    <#ty as #crate_path::SizeOf>::size_of_children(#ident, context);
207                                }
208                            }
209                        });
210
211                        quote! {
212                            Self::#variant_name { #(#idents,)* #ellipses } => {
213                                #(#body)*
214                            }
215                        }
216                    }
217
218                    Fields::Unnamed(unnamed) => {
219                        let idents = unnamed.unnamed.iter().enumerate().map(|(idx, field)| {
220                            if has_skip(&field.attrs) {
221                                quote! { _ }
222                            } else {
223                                let idx = format_ident!("_{idx}");
224                                quote! { #idx }
225                            }
226                        });
227
228                        let body = unnamed.unnamed.iter().enumerate().map(|(idx, field)| {
229                            if has_skip(&field.attrs) {
230                                TokenStream::new()
231                            } else {
232                                let ident = format_ident!("_{idx}");
233                                let ty = normalize_type(field.ty.clone());
234                                quote! {
235                                    <#ty as #crate_path::SizeOf>::size_of_children(#ident, context);
236                                }
237                            }
238                        });
239
240                        quote! {
241                            Self::#variant_name(#(#idents),*) => {
242                                #(#body)*
243                            }
244                        }
245                    }
246
247                    // Do nothing for unit variants
248                    Fields::Unit => quote! { Self::#variant_name => {} },
249                }
250            });
251
252            // Build the generic bounds for the impl
253            let generics = make_generic_bounds(&input, &crate_path, &variant_types);
254            let (intro_generics, fwd_generics, where_clause) = generics.split_for_impl();
255            let tuple_name = &input.ident;
256
257            // Special casing uninhabited enums, references are always considered inhabited
258            // so we just dereference the value and match on that
259            let body = if enumeration.variants.is_empty() {
260                quote! {
261                    match *self {}
262                }
263
264            // If all variants are empty, skipped or have no unskipped fields
265            // then we can emit nothing as the body
266            } else if all_variants_empty(enumeration.variants.iter()) {
267                TokenStream::new()
268
269            // For inhabited enums we still match on the referenced value
270            } else {
271                quote! {
272                    match self {
273                        #(#match_arms)*
274                    }
275                }
276            };
277
278            Ok(quote! {
279                #[automatically_derived]
280                impl #intro_generics #crate_path::SizeOf for #tuple_name #fwd_generics
281                    #where_clause
282                {
283                    fn size_of_children(&self, context: &mut #crate_path::Context) {
284                        #body
285                    }
286                }
287            })
288        }
289
290        // We can't automatically derive for unions
291        Data::Union(_) => Err(Error::new_spanned(
292            input,
293            "cannot derive TotalSize on unions, try manually implementing it",
294        )),
295    }
296}
297
298/// Returns `true` if the number of given variants that:
299/// - Are not skipped
300/// - Have at least one unskipped field
301/// Is greater than zero
302fn all_variants_empty<'a, I>(mut variants: I) -> bool
303where
304    I: Iterator<Item = &'a Variant> + 'a,
305{
306    variants.all(|variant| {
307        has_skip(&variant.attrs)
308            || variant
309                .fields
310                .iter()
311                .filter(|field| !has_skip(&field.attrs))
312                .count()
313                == 0
314    })
315}
316
317fn make_generic_bounds(input: &DeriveInput, crate_path: &Path, field_types: &[Type]) -> Generics {
318    let mut generics = input.generics.clone();
319
320    // Add SizeOf bounds to all all unskipped fields of the type
321    generics
322        .make_where_clause()
323        .predicates
324        .extend(field_types.iter().map(|field_ty| -> WherePredicate {
325            parse_quote_spanned!(Span::mixed_site() => #field_ty: #crate_path::SizeOf)
326        }));
327
328    generics
329}
330
331fn collect_field_info(crate_path: &Path, fields: &Fields) -> (Vec<Type>, Vec<TokenStream>) {
332    let (mut field_types, field_sizes): (Vec<_>, Vec<_>) = match fields {
333        // Collect all field types that aren't annotated with a skip attribute
334        Fields::Named(fields) => {
335            fields
336                .named
337                .iter()
338                .filter_map(|field| {
339                    let field_type = normalize_type(field.ty.clone());
340
341                    if has_skip(&field.attrs) || has_skip_bounds(&field.attrs) || is_trivial_bound(&field_type) {
342                        None
343                    } else {
344                        let field_ident = &field.ident;
345                        let field_size = quote! {
346                            <#field_type as #crate_path::SizeOf>::size_of_children(&self.#field_ident, context)
347                        };
348
349                        Some((field_type, field_size))
350                    }
351                })
352                .unzip()
353        }
354
355        // We need field indices for tuple structs
356        Fields::Unnamed(fields) => {
357            fields
358                .unnamed
359                .iter()
360                .enumerate()
361                .flat_map(|(idx, field)| has_skip(&field.attrs).not().then(|| {
362                    let field_type = normalize_type(field.ty.clone());
363                    let idx = Index::from(idx);
364                    let field_size = quote! {
365                        <#field_type as #crate_path::SizeOf>::size_of_children(&self.#idx, context)
366                    };
367
368                    (field_type, field_size)
369                }))
370                .unzip()
371        }
372
373        // We give no (extra) bounds on unit structs
374        Fields::Unit => (Vec::new(), Vec::new()),
375    };
376
377    // Deduplicate the types we add bounds to so that we reduce the amount of code
378    // we generate
379    dedup_types(&mut field_types);
380
381    (field_types, field_sizes)
382}
383
384/// Returns `true` if the type is trivial elidible
385///
386/// Currently returns `true` for the following types:
387/// - `fn` types, e.g. `fn()`
388/// - Raw pointers, e.g. `*const T`
389///
390// TODO: Can probably extend this to break down nested types like `&T`,
391// `&mut T`, `[T; N]` and `[T]` into just `T`, we know that arrays and
392// slices implement `SizeOf` when the inner type does. We can probably
393// also decompose tuples into their constituent element types
394fn is_trivial_bound(ty: &Type) -> bool {
395    matches!(ty, Type::BareFn(_) | Type::Ptr(_))
396}
397
398/// Normalizes a type
399///
400/// Currently just removes all parenthesis from around the type
401fn normalize_type(mut ty: Type) -> Type {
402    normalize_type_mut(&mut ty);
403    ty
404}
405
406/// Normalizes a type
407///
408/// Currently just removes all parenthesis from around the type
409fn normalize_type_mut(ty: &mut Type) {
410    // Unwrap any parenthesises around the type
411    while let Type::Paren(inner) = ty {
412        *ty = replace(&mut *inner.elem, Type::Verbatim(TokenStream::new()));
413    }
414
415    match ty {
416        Type::Array(TypeArray { elem, .. })
417        | Type::Slice(TypeSlice { elem, .. })
418        | Type::Ptr(TypePtr { elem, .. })
419        | Type::Reference(TypeReference { elem, .. }) => {
420            normalize_type_mut(elem);
421        }
422
423        Type::BareFn(TypeBareFn { inputs, output, .. }) => {
424            for input in inputs {
425                normalize_type_mut(&mut input.ty);
426            }
427
428            if let ReturnType::Type(_, ret) = output {
429                normalize_type_mut(ret);
430            }
431        }
432
433        Type::Tuple(TypeTuple { elems, .. }) => {
434            for elem in elems {
435                normalize_type_mut(elem);
436            }
437        }
438
439        _ => {}
440    }
441}
442
443/// Deduplicate all types within the given vec
444fn dedup_types(field_types: &mut Vec<Type>) {
445    // Ensure that all types are normalized before we start messing with them
446    for ty in &mut *field_types {
447        normalize_type_mut(ty);
448    }
449
450    let mut idx = 0;
451    while idx < field_types.len() {
452        let current = field_types[idx].clone();
453
454        let mut field_idx = 0;
455        field_types.retain(|ty| {
456            let should_retain = if field_idx <= idx {
457                true
458            } else {
459                ty != &current
460            };
461            field_idx += 1;
462
463            should_retain
464        });
465
466        idx += 1;
467    }
468}
469
470/// Returns the path set in the top-level `#[size_of(crate_path = "<path>")]`
471/// attribute (if present)
472fn find_crate_name(attrs: &[Attribute]) -> Result<Option<Path>> {
473    for attr in attrs {
474        if let Ok(Meta::List(meta)) = attr.parse_meta() {
475            if meta.path.is_ident("size_of") {
476                for nested in &meta.nested {
477                    if let NestedMeta::Meta(Meta::NameValue(pair)) = nested {
478                        if pair.path.is_ident("crate") {
479                            if let Lit::Str(path) = &pair.lit {
480                                return path.parse().map(Some);
481                            }
482                        }
483                    }
484                }
485            }
486        }
487    }
488
489    Ok(None)
490}
491
492/// Returns `true` if any of the given attributes has an `ident` meta, e.g.
493/// `#[size_of(<ident>)]`
494fn has_ident_attr(ident: &str, attrs: &[Attribute]) -> bool {
495    for attr in attrs {
496        if let Ok(Meta::List(meta)) = attr.parse_meta() {
497            if meta.path.is_ident("size_of") {
498                for nested in &meta.nested {
499                    if matches!(nested, NestedMeta::Meta(Meta::Path(path)) if path.is_ident(ident))
500                    {
501                        return true;
502                    }
503                }
504            }
505        }
506    }
507
508    false
509}
510
511fn find_ident_attr(ident: &str, attrs: &[Attribute]) -> Option<NestedMeta> {
512    for attr in attrs {
513        if let Ok(Meta::List(meta)) = attr.parse_meta() {
514            if meta.path.is_ident("size_of") {
515                for nested in &meta.nested {
516                    if matches!(nested, NestedMeta::Meta(Meta::Path(path)) if path.is_ident(ident))
517                    {
518                        return Some(nested.clone());
519                    }
520                }
521            }
522        }
523    }
524
525    None
526}
527
528/// Returns `true` if any of the given attributes is `#[size_of(skip)]`
529fn has_skip_all(attrs: &[Attribute]) -> bool {
530    has_ident_attr("skip_all", attrs)
531}
532
533/// Returns `true` if any of the given attributes is `#[size_of(skip)]`
534fn has_skip(attrs: &[Attribute]) -> bool {
535    has_ident_attr("skip", attrs)
536}
537
538/// Returns the `#[size_of(skip)]` meta if it exists
539fn find_skip(attrs: &[Attribute]) -> Option<NestedMeta> {
540    find_ident_attr("skip", attrs)
541}
542
543/// Returns `true` if any of the given attributes is `#[size_of(skip_bounds)]`
544fn has_skip_bounds(attrs: &[Attribute]) -> bool {
545    has_ident_attr("skip_bounds", attrs)
546}
547
548/// Returns the `#[size_of(skip_bounds)]` meta if it exists
549fn find_skip_bounds(attrs: &[Attribute]) -> Option<NestedMeta> {
550    find_ident_attr("skip_bounds", attrs)
551}