Skip to main content

fuse_rust_derive/
lib.rs

1#![warn(missing_docs)]
2
3//! Derive macro for the [`Fuseable`] trait of the
4//! [`fuse-rust`](https://docs.rs/fuse-rust) crate.
5//!
6//! This crate is re-exported by `fuse-rust` when its `derive` feature is enabled, so
7//! there is normally no need to depend on it directly.
8//!
9//! [`Fuseable`]: https://docs.rs/fuse-rust/latest/fuse_rust/trait.Fuseable.html
10
11use proc_macro::TokenStream;
12use proc_macro2::TokenStream as TokenStream2;
13use quote::quote;
14use syn::spanned::Spanned;
15use syn::{parse_macro_input, Data, DeriveInput, Fields, Ident, Lit};
16
17/// Derives `Fuseable` for a struct with named fields.
18///
19/// Mark each field that should take part in the search with `#[fuse]`. Fields without
20/// the attribute are ignored, so a struct may freely hold ids, counts or any other
21/// non-textual data.
22///
23/// # Examples
24///
25/// A bare `#[fuse]` gives the field a weight of `1.0`:
26///
27/// ```ignore
28/// #[derive(Fuseable)]
29/// struct Tag {
30///     #[fuse]
31///     name: String,
32/// }
33/// ```
34///
35/// Use `#[fuse(weight = ...)]` to weigh fields against each other. Weights must be
36/// greater than `0.0` and no greater than `1.0`:
37///
38/// ```ignore
39/// #[derive(Fuseable)]
40/// struct Book {
41///     #[fuse(weight = 0.3)]
42///     title: String,
43///     #[fuse(weight = 0.7)]
44///     author: String,
45///     isbn: u64, // not searched
46/// }
47/// ```
48///
49/// Every annotated field must be usable as a `&str`, which covers `String` and `&str`.
50#[proc_macro_derive(Fuseable, attributes(fuse))]
51pub fn derive_fuseable(input: TokenStream) -> TokenStream {
52    let input = parse_macro_input!(input as DeriveInput);
53    match expand(input) {
54        Ok(tokens) => tokens.into(),
55        Err(error) => error.to_compile_error().into(),
56    }
57}
58
59fn expand(input: DeriveInput) -> syn::Result<TokenStream2> {
60    let ident = &input.ident;
61    let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
62    let fields = named_fields(&input)?;
63
64    let mut selected: Vec<(Ident, f64)> = Vec::new();
65    for field in fields {
66        if let Some(weight) = field_weight(field)? {
67            let name = field
68                .ident
69                .clone()
70                .expect("named fields always have an identifier");
71            selected.push((name, weight));
72        }
73    }
74
75    if selected.is_empty() {
76        return Err(syn::Error::new(
77            ident.span(),
78            "`Fuseable` needs at least one searchable field: \
79             mark one with `#[fuse]`, or `#[fuse(weight = 0.5)]` to weigh it",
80        ));
81    }
82
83    let properties = selected.iter().map(|(name, weight)| {
84        let key = name.to_string();
85        quote! {
86            ::fuse_rust::FuseProperty {
87                value: ::std::string::String::from(#key),
88                weight: #weight,
89            }
90        }
91    });
92
93    let arms = selected.iter().map(|(name, _)| {
94        let key = name.to_string();
95        quote! { #key => ::core::option::Option::Some(&self.#name) }
96    });
97
98    Ok(quote! {
99        #[automatically_derived]
100        impl #impl_generics ::fuse_rust::Fuseable for #ident #ty_generics #where_clause {
101            fn properties(&self) -> ::std::vec::Vec<::fuse_rust::FuseProperty> {
102                ::std::vec![#(#properties),*]
103            }
104
105            fn lookup(&self, key: &str) -> ::core::option::Option<&str> {
106                match key {
107                    #(#arms,)*
108                    _ => ::core::option::Option::None,
109                }
110            }
111        }
112    })
113}
114
115/// `Fuseable` maps field names to values, so the struct must have named fields.
116fn named_fields(
117    input: &DeriveInput,
118) -> syn::Result<&syn::punctuated::Punctuated<syn::Field, syn::token::Comma>> {
119    match &input.data {
120        Data::Struct(data) => match &data.fields {
121            Fields::Named(named) => Ok(&named.named),
122            Fields::Unnamed(fields) => Err(syn::Error::new(
123                fields.span(),
124                "`Fuseable` cannot be derived for a tuple struct, because its fields have no names to look up",
125            )),
126            Fields::Unit => Err(syn::Error::new(
127                input.ident.span(),
128                "`Fuseable` cannot be derived for a unit struct, because it has no fields to search",
129            )),
130        },
131        Data::Enum(data) => Err(syn::Error::new(
132            data.enum_token.span(),
133            "`Fuseable` can only be derived for structs",
134        )),
135        Data::Union(data) => Err(syn::Error::new(
136            data.union_token.span(),
137            "`Fuseable` can only be derived for structs",
138        )),
139    }
140}
141
142/// Returns the weight for a field, or `None` when the field carries no `#[fuse]`
143/// attribute and so should not be searched.
144fn field_weight(field: &syn::Field) -> syn::Result<Option<f64>> {
145    let mut weight: Option<f64> = None;
146    let mut marked = false;
147
148    for attr in &field.attrs {
149        if !attr.path().is_ident("fuse") {
150            continue;
151        }
152        marked = true;
153
154        if matches!(attr.meta, syn::Meta::Path(_)) {
155            continue; // bare `#[fuse]`, weight defaults to 1.0
156        }
157
158        attr.parse_nested_meta(|meta| {
159            if meta.path.is_ident("weight") {
160                let literal: Lit = meta.value()?.parse()?;
161                weight = Some(parse_weight(&literal)?);
162                Ok(())
163            } else {
164                Err(meta.error("unknown `fuse` option, expected `weight`"))
165            }
166        })?;
167    }
168
169    Ok(marked.then(|| weight.unwrap_or(1.0)))
170}
171
172/// Weights are combined as `1.0 - weight`, so anything outside `(0.0, 1.0]` would score
173/// nonsensically. Reject it here rather than at search time.
174fn parse_weight(literal: &Lit) -> syn::Result<f64> {
175    let value = match literal {
176        Lit::Float(float) => float.base10_parse::<f64>()?,
177        Lit::Int(int) => int.base10_parse::<i64>()? as f64,
178        other => {
179            return Err(syn::Error::new(
180                other.span(),
181                "`weight` must be a number, for example `#[fuse(weight = 0.3)]`",
182            ))
183        }
184    };
185
186    if !value.is_finite() || value <= 0.0 || value > 1.0 {
187        return Err(syn::Error::new(
188            literal.span(),
189            "`weight` must be greater than 0.0 and at most 1.0",
190        ));
191    }
192
193    Ok(value)
194}