malloc_size_of_derive/
lib.rs

1// Copyright 2016-2017 The Servo Project Developers. See the COPYRIGHT
2// file at the top-level directory of this distribution and at
3// http://rust-lang.org/COPYRIGHT.
4//
5// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8// option. This file may not be copied, modified, or distributed
9// except according to those terms.
10
11//! A crate for deriving the MallocSizeOf trait.
12
13use syn::parse_quote;
14use synstructure::quote;
15
16#[cfg(not(test))]
17use synstructure::decl_derive;
18
19#[cfg(not(test))]
20decl_derive!([MallocSizeOf, attributes(ignore_malloc_size_of)] => malloc_size_of_derive);
21
22fn malloc_size_of_derive(
23    s: synstructure::Structure,
24) -> proc_macro2::TokenStream {
25    let match_body = s.each(|binding| {
26        let ignore = binding.ast().attrs.iter().any(|attr| {
27            match attr.parse_meta().unwrap() {
28                syn::Meta::Path(ref path)
29                | syn::Meta::List(syn::MetaList { ref path, .. })
30                    if path.is_ident("ignore_malloc_size_of") =>
31                {
32                    panic!(
33                        "#[ignore_malloc_size_of] should have an explanation, \
34                         e.g. #[ignore_malloc_size_of = \"because reasons\"]"
35                    );
36                }
37                syn::Meta::NameValue(syn::MetaNameValue {
38                    ref path, ..
39                }) if path.is_ident("ignore_malloc_size_of") => true,
40                _ => false,
41            }
42        });
43        if ignore {
44            None
45        } else if let syn::Type::Array(..) = binding.ast().ty {
46            Some(quote! {
47                for item in #binding.iter() {
48                    sum += ::malloc_size_of::MallocSizeOf::size_of(item, ops);
49                }
50            })
51        } else {
52            Some(quote! {
53                sum += ::malloc_size_of::MallocSizeOf::size_of(#binding, ops);
54            })
55        }
56    });
57
58    let ast = s.ast();
59    let name = &ast.ident;
60    let (impl_generics, ty_generics, where_clause) =
61        ast.generics.split_for_impl();
62    let mut where_clause = where_clause.unwrap_or(&parse_quote!(where)).clone();
63    for param in ast.generics.type_params() {
64        let ident = &param.ident;
65        where_clause
66            .predicates
67            .push(parse_quote!(#ident: ::malloc_size_of::MallocSizeOf));
68    }
69
70    let tokens = quote! {
71        impl #impl_generics ::malloc_size_of::MallocSizeOf for #name #ty_generics #where_clause {
72            #[inline]
73            #[allow(unused_variables, unused_mut, unreachable_code)]
74            fn size_of(&self, ops: &mut ::malloc_size_of::MallocSizeOfOps) -> usize {
75                let mut sum = 0;
76                match *self {
77                    #match_body
78                }
79                sum
80            }
81        }
82    };
83
84    tokens
85}
86
87#[test]
88fn test_struct() {
89    let source = syn::parse_str(
90        "struct Foo<T> { bar: Bar, baz: T, #[ignore_malloc_size_of = \"\"] z: Arc<T> }",
91    )
92        .unwrap();
93    let source = synstructure::Structure::new(&source);
94
95    let expanded = malloc_size_of_derive(source).to_string();
96    let mut no_space = expanded.replace(" ", "");
97    macro_rules! match_count {
98        ($e:expr, $count:expr) => {
99            assert_eq!(
100                no_space.matches(&$e.replace(" ", "")).count(),
101                $count,
102                "counting occurrences of {:?} in {:?} (whitespace-insensitive)",
103                $e,
104                expanded
105            )
106        };
107    }
108    match_count!("struct", 0);
109    match_count!("ignore_malloc_size_of", 0);
110    match_count!("impl<T> ::malloc_size_of::MallocSizeOf for Foo<T> where T: ::malloc_size_of::MallocSizeOf {", 1);
111    match_count!("sum += ::malloc_size_of::MallocSizeOf::size_of(", 2);
112
113    let source = syn::parse_str("struct Bar([Baz; 3]);").unwrap();
114    let source = synstructure::Structure::new(&source);
115    let expanded = malloc_size_of_derive(source).to_string();
116    no_space = expanded.replace(" ", "");
117    match_count!("for item in", 1);
118}
119
120#[should_panic(expected = "should have an explanation")]
121#[test]
122fn test_no_reason() {
123    let input =
124        syn::parse_str("struct A { #[ignore_malloc_size_of] b: C }").unwrap();
125    malloc_size_of_derive(synstructure::Structure::new(&input));
126}