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#[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
92fn size_of_derive_inner(input: DeriveInput) -> Result<TokenStream> {
96 let crate_path = find_crate_name(&input.attrs)?
99 .unwrap_or_else(|| parse_quote_spanned!(Span::mixed_site() => ::size_of));
100
101 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 } 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 } 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 let (field_types, field_sizes) = collect_field_info(&crate_path, &structure.fields);
138
139 let generics = make_generic_bounds(&input, &crate_path, &field_types);
141 let (intro_generics, fwd_generics, where_clause) = generics.split_for_impl();
142
143 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 let mut variant_types: Vec<_> = enumeration
166 .variants
167 .iter()
168 .flat_map(|variant| {
169 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 Fields::Unit => quote! { Self::#variant_name => {} },
249 }
250 });
251
252 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 let body = if enumeration.variants.is_empty() {
260 quote! {
261 match *self {}
262 }
263
264 } else if all_variants_empty(enumeration.variants.iter()) {
267 TokenStream::new()
268
269 } 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 Data::Union(_) => Err(Error::new_spanned(
292 input,
293 "cannot derive TotalSize on unions, try manually implementing it",
294 )),
295 }
296}
297
298fn 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 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 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 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 Fields::Unit => (Vec::new(), Vec::new()),
375 };
376
377 dedup_types(&mut field_types);
380
381 (field_types, field_sizes)
382}
383
384fn is_trivial_bound(ty: &Type) -> bool {
395 matches!(ty, Type::BareFn(_) | Type::Ptr(_))
396}
397
398fn normalize_type(mut ty: Type) -> Type {
402 normalize_type_mut(&mut ty);
403 ty
404}
405
406fn normalize_type_mut(ty: &mut Type) {
410 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
443fn dedup_types(field_types: &mut Vec<Type>) {
445 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 != ¤t
460 };
461 field_idx += 1;
462
463 should_retain
464 });
465
466 idx += 1;
467 }
468}
469
470fn 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
492fn 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
528fn has_skip_all(attrs: &[Attribute]) -> bool {
530 has_ident_attr("skip_all", attrs)
531}
532
533fn has_skip(attrs: &[Attribute]) -> bool {
535 has_ident_attr("skip", attrs)
536}
537
538fn find_skip(attrs: &[Attribute]) -> Option<NestedMeta> {
540 find_ident_attr("skip", attrs)
541}
542
543fn has_skip_bounds(attrs: &[Attribute]) -> bool {
545 has_ident_attr("skip_bounds", attrs)
546}
547
548fn find_skip_bounds(attrs: &[Attribute]) -> Option<NestedMeta> {
550 find_ident_attr("skip_bounds", attrs)
551}