anondb_macros/
lib.rs

1mod anondb;
2mod document;
3mod index;
4
5use index::*;
6
7use proc_macro::TokenStream;
8use syn::punctuated::Punctuated;
9use syn::token::Comma;
10use syn::*;
11
12#[proc_macro_derive(AnonDB, attributes(anondb))]
13pub fn anondb_derive(input: TokenStream) -> TokenStream {
14    let input = parse_macro_input!(input as DeriveInput);
15    match anondb::derive(input) {
16        Ok(t) => t,
17        Err(e) => e.to_compile_error().into(),
18    }
19}
20
21#[proc_macro_derive(Document)]
22pub fn document_derive(input: TokenStream) -> TokenStream {
23    let input = parse_macro_input!(input as DeriveInput);
24    match document::derive(input) {
25        Ok(t) => t,
26        Err(e) => e.to_compile_error().into(),
27    }
28}
29
30fn crate_name() -> proc_macro2::TokenStream {
31    if std::env::var("CARGO_PKG_NAME").ok().as_deref() == Some("anondb") {
32        quote::quote! { crate }
33    } else {
34        quote::quote! { ::anondb }
35    }
36}
37
38/// Parse the derive invocation, the struct, and extract the fields.
39fn parse_struct_and_fields<'a>(
40    input: &'a DeriveInput,
41    macro_name: &str,
42) -> Result<&'a Punctuated<Field, Comma>> {
43    // Only allow structs
44    let data_struct = match &input.data {
45        Data::Struct(s) => s,
46        Data::Enum(_) => {
47            return Err(Error::new_spanned(
48                input,
49                format!("{macro_name} can only be derived for structs, not enums",),
50            ));
51        }
52        Data::Union(_) => {
53            return Err(Error::new_spanned(
54                input,
55                format!("{macro_name} can only be derived for structs, not unions",),
56            ));
57        }
58    };
59
60    // Only allow named fields (bracket syntax)
61    let fields = match &data_struct.fields {
62        Fields::Named(fields) => &fields.named,
63        Fields::Unnamed(_) => {
64            return Err(Error::new_spanned(
65                input,
66                format!(
67                    "{macro_name} only works with structs that have named fields (with braces {{}}), not tuple structs",
68                ),
69            ));
70        }
71        Fields::Unit => {
72            return Err(Error::new_spanned(
73                input,
74                format!(
75                    "{macro_name} only works with structs that have named fields (with braces {{}}), not unit structs",
76                ),
77            ));
78        }
79    };
80    Ok(fields)
81}