Skip to main content

heap_drop_macros/
lib.rs

1//! This crate provides a derive macro for the `HeapDrop` trait, providing a function that returns a vector of children.
2
3use proc_macro::TokenStream;
4use proc_macro2::{Ident, Span};
5use quote::quote;
6use syn::{Data, DeriveInput, Fields, parse_macro_input};
7
8/// Derives the `HeapDrop` trait for a struct or enum, allowing it to be disposed of using a heap-allocated queue.
9#[proc_macro_derive(HeapDrop)]
10pub fn heap_drop_derive(input: TokenStream) -> TokenStream {
11    let input = parse_macro_input!(input as DeriveInput);
12
13    let struct_name = &input.ident;
14    let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
15
16    let body = match &input.data {
17        Data::Struct(s) => {
18            let arm = deconstruct_fields(&s.fields);
19            quote! { match *self { Self #arm } }
20        }
21        Data::Enum(e) => {
22            let arms = e.variants.iter().map(|v| {
23                let arm = deconstruct_fields(&v.fields);
24                let variant = &v.ident;
25                quote! { Self::#variant #arm }
26            });
27
28            quote! { match *self { #(#arms),* } }
29        }
30
31        _ => panic!("HeapDrop can only be derived for structs and enums"),
32    };
33
34    TokenStream::from(quote! {
35        impl #impl_generics ::heap_drop::HeapDrop for #struct_name #ty_generics #where_clause {
36            fn into_children(self: Box<Self>) -> Vec<Box<dyn ::heap_drop::HeapDrop>>
37            {
38                #body
39            }
40        }
41    })
42}
43
44/// Emits the tokens to deconstruct fields and collect those which implement `HeapDrop` into a vector.
45fn deconstruct_fields(fields: &Fields) -> proc_macro2::TokenStream {
46    match fields {
47        Fields::Named(fields) => {
48            let vars = fields.named.iter().filter_map(|f| f.ident.clone()).collect::<Vec<Ident>>();
49            let detections = collect_implementing_vars(&vars);
50            quote! { { #(#vars),* , .. } => {#detections} }
51        }
52        Fields::Unnamed(fields) => {
53            let vars = (0..fields.unnamed.len())
54                .map(|i| Ident::new(&format!("f{}", i), Span::call_site()))
55                .collect::<Vec<Ident>>();
56            let detections = collect_implementing_vars(&vars);
57            quote! { (#(#vars),*) => {#detections} }
58        }
59        Fields::Unit => quote! { => vec![] },
60    }
61}
62
63/// Emits the tokens to collect the values stored at the given identifiers into a vector of those which implement `HeapDrop`.
64fn collect_implementing_vars(vars: &Vec<Ident>) -> proc_macro2::TokenStream {
65    quote! {
66        let mut children: Vec<Box<dyn ::heap_drop::HeapDrop>> = vec![];
67        #(if let Some(child) = ::heap_drop::maybe_as_heap_drop!(#vars) { children.push(child); })*
68        children
69    }
70}