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
use quote::quote;
use synstructure::{decl_derive, AddBounds, Structure};

decl_derive! {
    [Trace, attributes(unsafe_ignore_trace)] =>
    /// Derive an `impl` of `Trace` on a type.
    derive_trace
}

fn derive_trace(mut s: Structure<'_>) -> proc_macro2::TokenStream {
    s.underscore_const(true);
    s.filter(|bi| {
        !bi.ast()
            .attrs
            .iter()
            .any(|attr| attr.path.is_ident("unsafe_ignore_trace"))
    });

    let untrace_body = s.each(|bi| quote!(Trace::untrace(#bi)));
    let trace_body = s.each(|bi| quote!(Trace::trace(#bi)));
    let set_undone_body = s.each(|bi| quote!(Trace::set_undone(#bi)));
    let counts_match_body = s.fold(
        quote!(true),
        |acc, bi| quote!(#acc & Trace::counts_match(#bi)),
    );

    s.add_bounds(AddBounds::Generics);

    s.gen_impl(quote! {
        extern crate mjb_gc;

        use mjb_gc::Trace;

        gen unsafe impl Trace for @Self {
            #[allow(unused_unsafe)]
            unsafe fn untrace(&self) {
                unsafe { match *self { #untrace_body } }
            }

            #[allow(unused_unsafe)]
            unsafe fn trace(&self) {
                unsafe { match *self { #trace_body } }
            }

            #[allow(unused_unsafe)]
            unsafe fn set_undone(&self) {
                unsafe { match *self { #set_undone_body } }
            }

            fn counts_match(&self) -> bool {
                match *self { #counts_match_body }
            }
        }
    })
}