Skip to main content

ossa_typeable_derive/
lib.rs

1use proc_macro2::TokenStream;
2use quote::quote;
3use std::collections::HashSet;
4use syn::{
5    punctuated::Punctuated, token::Comma, AttrStyle, Attribute, Data, Expr, Field, Fields,
6    GenericParam, Ident, Lit, Meta, Type,
7};
8
9#[proc_macro_derive(Typeable, attributes(tag))]
10pub fn typeable_derive(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
11    // Construct a representation of Rust code as a syntax tree
12    // that we can manipulate
13    let ast = syn::parse(input).unwrap();
14
15    // Build the trait implementation
16    impl_typeable_macro(&ast)
17}
18
19fn impl_type_ident(t: &Type) -> TokenStream {
20    quote! {
21        h.update(<#t as ossa_typeable::Typeable>::type_ident().identifier());
22    }
23}
24
25// Skip types like `PhantomData` and eventually check attributes.
26fn skip_field(f: &Field) -> bool {
27    fn extract_type_name(t: &Type) -> Option<&Ident> {
28        match t {
29            Type::Path(p) => {
30                let segment = p.path.segments.first()?;
31                Some(&segment.ident)
32            }
33            _ => None,
34        }
35    }
36    let type_name = extract_type_name(&f.ty);
37
38    type_name.map_or(false, |n| n == "PhantomData")
39}
40
41fn impl_fields(fs: &Fields) -> TokenStream {
42    let empty = Punctuated::<Field, Comma>::new();
43    let (tag, fields) = match fs {
44        Fields::Named(fs) => (0u8, fs.named.iter()),
45        Fields::Unnamed(fs) => (1, fs.unnamed.iter()),
46        Fields::Unit => (0, empty.iter()),
47    };
48
49    // Filter any fields.
50    let mut fields = fields.filter(|f| !skip_field(&f)).collect::<Vec<_>>();
51
52    let c = fields.len();
53
54    let fields = match &fs {
55        Fields::Named(_) => {
56            // Sort the fields by their name.
57            fields.sort_by_key(|f| f.ident.as_ref());
58
59            TokenStream::from_iter(fields.iter().map(|f| {
60                let name = f.ident.as_ref().unwrap().to_string();
61                let ty = impl_type_ident(&f.ty);
62
63                quote! {
64                    helper_string(&mut h, #name);
65                    #ty
66                }
67            }))
68        }
69        Fields::Unnamed(_) => TokenStream::from_iter(fields.iter().map(|f| impl_type_ident(&f.ty))),
70        Fields::Unit => {
71            quote! {}
72        }
73    };
74
75    quote! {
76        helper_u8(&mut h, #tag);
77        helper_counter(&mut h, #c);
78        #fields
79    }
80}
81
82fn impl_tag(attrs: &[Attribute]) -> TokenStream {
83    fn get_tag(a: &Attribute) -> Option<String> {
84        match &a.meta {
85            Meta::NameValue(v) => {
86                let seg = v.path.segments.first()?;
87                if &seg.ident.to_string() == "tag" {
88                    match &v.value {
89                        Expr::Lit(l) => match &l.lit {
90                            Lit::Str(s) => Some(s.value()),
91                            _ => None,
92                        },
93                        _ => None,
94                    }
95                } else {
96                    None
97                }
98            }
99            _ => None,
100        }
101    }
102    if let Some(attr) = attrs.iter().find_map(|a| {
103        if a.style == AttrStyle::Outer {
104            get_tag(a)
105        } else {
106            None
107        }
108    }) {
109        quote! {
110            helper_string(&mut h, #attr);
111        }
112    } else {
113        quote! {}
114    }
115}
116
117fn impl_where(ast: &syn::DeriveInput) -> TokenStream {
118    fn extract_fields_types(fs: Fields) -> impl Iterator<Item = Type> {
119        let empty = Punctuated::<Field, Comma>::new();
120        let fields = match fs {
121            Fields::Named(n) => n.named,
122            Fields::Unnamed(u) => u.unnamed,
123            Fields::Unit => empty,
124        };
125        fields.into_iter().filter(|f| !skip_field(&f)).map(|f| f.ty)
126    }
127
128    fn extract_field_types(d: &Data) -> HashSet<Type> {
129        match d {
130            Data::Struct(s) => extract_fields_types(s.fields.clone()).collect(),
131            Data::Enum(e) => e
132                .variants
133                .iter()
134                .flat_map(|v| extract_fields_types(v.fields.clone()))
135                .collect(),
136            Data::Union(_) => {
137                panic!("Union types are not supported.")
138            }
139        }
140    }
141
142    let where_predicates = ast.generics.where_clause.as_ref().map(|w| &w.predicates);
143
144    let constraints = TokenStream::from_iter(extract_field_types(&ast.data).iter().map(|t| {
145        quote! {
146            #t: ossa_typeable::Typeable,
147        }
148    }));
149
150    quote! {
151        where
152            #where_predicates
153            #constraints
154    }
155}
156
157fn impl_typeable_macro(ast: &syn::DeriveInput) -> proc_macro::TokenStream {
158    let name = &ast.ident;
159    let name_lit = ast.ident.to_string();
160    let type_args_count: u8 = ast
161        .generics
162        .params
163        .iter()
164        .filter(|t| is_type_arg(t))
165        .count()
166        .try_into()
167        .unwrap();
168    let type_args = &ast.generics.params;
169    let abbr_type_args = TokenStream::from_iter(ast.generics.params.iter().map(|p| match p {
170        GenericParam::Lifetime(l) => {
171            let name = &l.lifetime;
172            quote! {
173                #name,
174            }
175        }
176        GenericParam::Type(t) => {
177            let name = &t.ident;
178            quote! {
179                #name,
180            }
181        }
182        GenericParam::Const(c) => {
183            let name = &c.ident;
184            quote! {
185                #name,
186            }
187        }
188    }));
189    let body = match &ast.data {
190        Data::Struct(s) => {
191            let fs = impl_fields(&s.fields);
192            quote! {
193                helper_u8(&mut h, 0);
194                #fs
195            }
196        }
197        Data::Enum(e) => {
198            let c = e.variants.len();
199            let vs = TokenStream::from_iter(e.variants.iter().map(|v| {
200                let name = v.ident.to_string();
201                let fs = impl_fields(&v.fields);
202
203                quote! {
204                    helper_string(&mut h, #name);
205                    #fs
206                }
207            }));
208            quote! {
209                helper_u8(&mut h, 1);
210                helper_counter(#c);
211                #vs
212            }
213        }
214        Data::Union(_) => {
215            panic!("Union types are not supported.")
216        }
217    };
218    let where_clause = impl_where(&ast);
219    let tag = impl_tag(&ast.attrs);
220
221    let gen = quote! {
222        #[automatically_derived]
223        impl<#type_args> ossa_typeable::Typeable for #name<#abbr_type_args> #where_clause {
224            fn type_ident() -> ossa_typeable::TypeId {
225                use ossa_typeable::internal::*;
226
227                let mut h = Sha256::new();
228                helper_type_constructor(&mut h, #name_lit);
229                helper_type_args_count(&mut h, #type_args_count);
230
231                #tag
232                #body
233
234                ossa_typeable::TypeId::new(h.finalize().into())
235            }
236        }
237    };
238    gen.into()
239}
240
241fn is_type_arg(a: &GenericParam) -> bool {
242    match a {
243        GenericParam::Type(_) => true,
244        _ => false,
245    }
246}