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
13extern crate proc_macro2;
14#[macro_use]
15extern crate syn;
16#[macro_use]
17extern crate synstructure;
18
19#[cfg(not(test))]
20decl_derive!([MallocSizeOf, attributes(ignore_malloc_size_of, conditional_malloc_size_of)] => malloc_size_of_derive);
21
22fn malloc_size_of_derive(s: synstructure::Structure) -> proc_macro2::TokenStream {
23    let match_body = s.each(|binding| {
24        let mut ignore = false;
25        let mut conditional = false;
26        for attr in binding.ast().attrs.iter() {
27            match attr.meta {
28                syn::Meta::Path(ref path) | syn::Meta::List(syn::MetaList { ref path, .. }) => {
29                    assert!(
30                        !path.is_ident("ignore_malloc_size_of"),
31                        "#[ignore_malloc_size_of] should have an explanation, \
32                         e.g. #[ignore_malloc_size_of = \"because reasons\"]"
33                    );
34                    if path.is_ident("conditional_malloc_size_of") {
35                        conditional = true;
36                    }
37                }
38                syn::Meta::NameValue(syn::MetaNameValue { ref path, .. }) => {
39                    if path.is_ident("ignore_malloc_size_of") {
40                        ignore = true;
41                    }
42                    if path.is_ident("conditional_malloc_size_of") {
43                        conditional = true;
44                    }
45                }
46            }
47        }
48
49        assert!(
50            !ignore || !conditional,
51            "ignore_malloc_size_of and conditional_malloc_size_of are incompatible"
52        );
53
54        if ignore {
55            return None;
56        }
57
58        let path = if conditional {
59            quote! { ::malloc_size_of::MallocConditionalSizeOf::conditional_size_of }
60        } else {
61            quote! { ::malloc_size_of::MallocSizeOf::size_of }
62        };
63
64        if let syn::Type::Array(..) = binding.ast().ty {
65            Some(quote! {
66                for item in #binding.iter() {
67                    sum += #path(item, ops);
68                }
69            })
70        } else {
71            Some(quote! {
72                sum += #path(#binding, ops);
73            })
74        }
75    });
76
77    let ast = s.ast();
78    let name = &ast.ident;
79    let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
80    let mut where_clause = where_clause.unwrap_or(&parse_quote!(where)).clone();
81    for param in ast.generics.type_params() {
82        let ident = &param.ident;
83        where_clause
84            .predicates
85            .push(parse_quote!(#ident: ::malloc_size_of::MallocSizeOf));
86    }
87
88    let tokens = quote! {
89        impl #impl_generics ::malloc_size_of::MallocSizeOf for #name #ty_generics #where_clause {
90            #[inline]
91            #[allow(unused_variables, unused_mut, unreachable_code)]
92            fn size_of(&self, ops: &mut ::malloc_size_of::MallocSizeOfOps) -> usize {
93                let mut sum = 0;
94                match *self {
95                    #match_body
96                }
97                sum
98            }
99        }
100    };
101
102    tokens
103}
104
105#[test]
106fn test_struct() {
107    let source = syn::parse_str(
108        "struct Foo<T> { bar: Bar, baz: T, #[ignore_malloc_size_of = \"\"] z: Arc<T> }",
109    )
110    .unwrap();
111    let source = synstructure::Structure::new(&source);
112
113    let expanded = malloc_size_of_derive(source).to_string();
114    let mut no_space = expanded.replace(" ", "");
115    macro_rules! match_count {
116        ($e: expr, $count: expr) => {
117            assert_eq!(
118                no_space.matches(&$e.replace(" ", "")).count(),
119                $count,
120                "counting occurences of {:?} in {:?} (whitespace-insensitive)",
121                $e,
122                expanded
123            )
124        };
125    }
126    match_count!("struct", 0);
127    match_count!("ignore_malloc_size_of", 0);
128    match_count!("impl<T> ::malloc_size_of::MallocSizeOf for Foo<T> where T: ::malloc_size_of::MallocSizeOf {", 1);
129    match_count!("sum += ::malloc_size_of::MallocSizeOf::size_of(", 2);
130
131    let source = syn::parse_str("struct Bar([Baz; 3]);").unwrap();
132    let source = synstructure::Structure::new(&source);
133    let expanded = malloc_size_of_derive(source).to_string();
134    no_space = expanded.replace(" ", "");
135    match_count!("for item in", 1);
136}
137
138#[should_panic(expected = "should have an explanation")]
139#[test]
140fn test_no_reason() {
141    let input = syn::parse_str("struct A { #[ignore_malloc_size_of] b: C }").unwrap();
142    malloc_size_of_derive(synstructure::Structure::new(&input));
143}