flow_record_derive/
lib.rs1use darling::FromDeriveInput;
2use proc_macro::TokenStream;
3use quote::quote;
4use record_attributes::RecordAttributes;
5use struct_info::StructInfo;
6use syn::{parse_macro_input, DeriveInput};
7
8mod field_info;
9mod record_attributes;
10mod struct_info;
11mod without_lifetimes;
12
13#[proc_macro_derive(FlowRecord, attributes(flow_record))]
14pub fn derive_flow_record(input: TokenStream) -> TokenStream {
15 let mut input = parse_macro_input!(input as DeriveInput);
16 FromDeriveInput::from_derive_input(&input)
17 .and_then(|attrs| expand(&mut input, attrs))
18 .map(Into::into)
19 .unwrap_or_else(|e| e.write_errors().into())
21}
22
23fn expand(ast: &mut syn::DeriveInput, attrs: RecordAttributes) -> darling::Result<TokenStream> {
24 let name = &ast.ident;
25 let name_as_string = name.to_string();
26
27 let descriptor;
28 let child_descriptors;
29 let hash;
30 let values: Vec<_>;
31
32 let from_parameter_name = quote! {self};
33
34 match &ast.data {
35 syn::Data::Struct(s) => {
36 let struct_info = StructInfo::new(name_as_string.clone(), s.clone(), attrs);
37 descriptor = struct_info.descriptor();
38 child_descriptors = struct_info.child_descriptors();
39 hash = struct_info.descriptor_hash();
40 values = struct_info.values(quote! {#from_parameter_name}).collect();
41 }
42
43 syn::Data::Enum(_) => panic!("no support for enums yet"),
44 syn::Data::Union(_) => panic!("no support for unions yet"),
45 }
46
47 let children = child_descriptors.into_iter().map(|c| {
48 let (hash, descriptor) = (c.hash, c.descriptor);
49 quote! {#hash, #descriptor}
50 });
51
52 let (impl_generics, ty_generics, where_clause) = ast.generics.split_for_impl();
53
54 let gen = quote!(
55 use flow_record::prelude::rmpv::Value;
56
57 impl #impl_generics FlowRecord for #name #ty_generics #where_clause {
58 fn name() -> &'static str {
59 #name_as_string
60 }
61 fn descriptor() -> &'static Value {
62 static D: std::sync::LazyLock<Value> = std::sync::LazyLock::new(|| Value::from( #descriptor ) );
63 &*D
64 }
65 fn descriptor_hash() -> u32 {
66 static H: std::sync::LazyLock<u32> = std::sync::LazyLock::new(|| #hash);
67 *H
68 }
69 fn into_value(self) -> Value {
70 Value::Array(vec![
71 #(#values),*,
72 ])
73 }
74 fn child_descriptors() -> &'static ::std::collections::HashMap<u32, Value> {
75 static D: std::sync::LazyLock<::std::collections::HashMap<u32, Value>> = std::sync::LazyLock::new(||
76 {
77 let mut d = ::std::collections::HashMap::new();
78 #( d.insert( #children ); )*
79 d
80 }
81 );
82 &*D
83 }
84 }
85 );
86 Ok(gen.into())
87}
88
89#[proc_macro_attribute]
90pub fn has_descriptor(_input: TokenStream, annotated_item: TokenStream) -> TokenStream {
91 annotated_item
92}