loupe_derive/lib.rs
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
//! Companion of the [`loupe`](../loupe-derive/index.html) crate.
use proc_macro::TokenStream;
use quote::{format_ident, quote, quote_spanned};
use syn::{
parse, Attribute, Data, DataEnum, DataStruct, DeriveInput, Fields, Generics, Ident, Index,
};
/// Procedural macro to implement the `loupe::MemoryUsage` trait
/// automatically for structs and enums.
///
/// All struct fields and enum variants must implement `MemoryUsage`
/// trait. If it's not possible, the `#[loupe(skip)]` attribute can be
/// used on a field or a variant to instruct the derive procedural
/// macro to skip that item.
///
/// # Example
///
/// ```rust,ignore
/// #[derive(MemoryUsage)]
/// struct Point {
/// x: i32,
/// y: i32,
/// }
///
/// struct Mystery { ptr: *const i32 }
///
/// #[derive(MemoryUsage)]
/// struct S {
/// points: Vec<Point>,
///
/// #[loupe(skip)]
/// other: Mystery,
/// }
/// ```
#[proc_macro_derive(MemoryUsage, attributes(loupe))]
pub fn derive_memory_usage(input: TokenStream) -> TokenStream {
let derive_input: DeriveInput = parse(input).unwrap();
match derive_input.data {
Data::Struct(ref struct_data) => {
derive_memory_usage_for_struct(&derive_input.ident, struct_data, &derive_input.generics)
}
Data::Enum(ref enum_data) => {
derive_memory_usage_for_enum(&derive_input.ident, enum_data, &derive_input.generics)
}
Data::Union(_) => panic!("unions are not yet implemented"),
/*
// TODO: unions.
// We have no way of knowing which union member is active, so we should
// refuse to derive an impl except for unions where all members are
// primitive types or arrays of them.
Data::Union(ref union_data) => {
derive_memory_usage_union(union_data)
},
*/
}
}
// TODO: use Iterator::fold_first once it's stable. https://github.com/rust-lang/rust/pull/79805
fn join_fold<I, F, B>(mut iter: I, function: F, empty: B) -> B
where
I: Iterator<Item = B>,
F: FnMut(B, I::Item) -> B,
{
if let Some(first) = iter.next() {
iter.fold(first, function)
} else {
empty
}
}
fn derive_memory_usage_for_struct(
struct_name: &Ident,
data: &DataStruct,
generics: &Generics,
) -> TokenStream {
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
let sum = join_fold(
// Check all fields of the `struct`.
match &data.fields {
// Field has the form:
//
// F { x, y }
Fields::Named(ref fields) => fields
.named
.iter()
.filter_map(|field| {
if must_skip(&field.attrs) {
return None;
}
let ident = field.ident.as_ref().unwrap();
let span = ident.span();
Some(quote_spanned!(
span => loupe::MemoryUsage::size_of_val(&self.#ident, visited) - std::mem::size_of_val(&self.#ident)
))
})
.collect(),
// Field has the form:
//
// F
Fields::Unit => vec![],
// Field has the form:
//
// F(x, y)
Fields::Unnamed(ref fields) => fields
.unnamed
.iter()
.enumerate()
.filter_map(|(nth, field)| {
if must_skip(&field.attrs) {
return None;
}
let ident = Index::from(nth);
Some(quote! { loupe::MemoryUsage::size_of_val(&self.#ident, visited) - std::mem::size_of_val(&self.#ident) })
})
.collect(),
}
.into_iter(),
|x, y| quote! { #x + #y },
quote! { 0 },
);
// Implement the `MemoryUsage` trait for `struct_name`.
(quote! {
#[allow(dead_code)]
impl #impl_generics loupe::MemoryUsage for #struct_name #ty_generics
#where_clause
{
fn size_of_val(&self, visited: &mut loupe::MemoryUsageTracker) -> usize {
std::mem::size_of_val(self) + #sum
}
}
})
.into()
}
fn derive_memory_usage_for_enum(
enum_name: &Ident,
data: &DataEnum,
generics: &Generics,
) -> TokenStream {
let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
let match_arms = join_fold(
data.variants
.iter()
.map(|variant| {
let ident = &variant.ident;
let span = ident.span();
// Check all the variants of the `enum`.
//
// We want to generate something like this:
//
// Self::Variant ... => { ... }
// ^^^^^^^ ^^^ ^^^
// | | |
// | | given by the `sum` variable
// | given by the `pattern` variable
// given by the `ident` variable
//
// Let's compute the `pattern` and `sum` parts.
let (pattern, mut sum) = match variant.fields {
// Variant has the form:
//
// V { x, y }
//
// We want to generate:
//
// Self::V { x, y } => { /* memory usage of x + y */ }
Fields::Named(ref fields) => {
// Collect the identifiers.
let identifiers = fields.named.iter().map(|field| {
let ident = field.ident.as_ref().unwrap();
let span = ident.span();
quote_spanned!(span => #ident)
});
// Generate the `pattern` part.
let pattern = {
let pattern = join_fold(
identifiers.clone(),
|x, y| quote! { #x , #y },
quote! {}
);
quote! { { #pattern } }
};
// Generate the `sum` part.
let sum = {
let sum = join_fold(
identifiers.map(|ident| quote! {
loupe::MemoryUsage::size_of_val(#ident, visited) - std::mem::size_of_val(#ident)
}),
|x, y| quote! { #x + #y },
quote! { 0 },
);
quote! { #sum }
};
(pattern, sum)
}
// Variant has the form:
//
// V
//
// We want to generate:
//
// Self::V => { 0 }
Fields::Unit => {
let pattern = quote! {};
let sum = quote! { 0 };
(pattern, sum)
},
// Variant has the form:
//
// V(x, y)
//
// We want to generate:
//
// Self::V(x, y) => { /* memory usage of x + y */ }
Fields::Unnamed(ref fields) => {
// Collect the identifiers. They are unnamed,
// so let's use the `xi` convention where `i`
// is the identifier index.
let identifiers = fields
.unnamed
.iter()
.enumerate()
.map(|(nth, _field)| {
let ident = format_ident!("x{}", Index::from(nth));
quote! { #ident }
});
// Generate the `pattern` part.
let pattern = {
let pattern = join_fold(
identifiers.clone(),
|x, y| quote! { #x , #y },
quote! {}
);
quote! { ( #pattern ) }
};
// Generate the `sum` part.
let sum = {
let sum = join_fold(
identifiers.map(|ident| quote! {
loupe::MemoryUsage::size_of_val(#ident, visited) - std::mem::size_of_val(#ident)
}),
|x, y| quote! { #x + #y },
quote! { 0 },
);
quote! { #sum }
};
(pattern, sum)
}
};
if must_skip(&variant.attrs) {
sum = quote! { 0 };
}
// At this step, `pattern` and `sum` are well
// defined. Let's generate the full arm for the
// `match` statement.
quote_spanned! { span => Self::#ident#pattern => #sum }
}
),
|x, y| quote! { #x , #y },
quote! {},
);
// Implement the `MemoryUsage` trait for `enum_name`.
(quote! {
#[allow(dead_code)]
impl #impl_generics loupe::MemoryUsage for #enum_name #ty_generics
#where_clause
{
fn size_of_val(&self, visited: &mut loupe::MemoryUsageTracker) -> usize {
std::mem::size_of_val(self) + match self {
#match_arms
}
}
}
})
.into()
}
fn must_skip(attrs: &[Attribute]) -> bool {
attrs.iter().any(|attr| {
attr.path.is_ident("loupe") && matches!(attr.parse_args::<Ident>(), Ok(a) if a == "skip")
})
}