Skip to main content

enum_strings/
lib.rs

1//! `#[derive(EnumStrings)]`: a `const fn` per named string on a unit enum,
2//! where every variant must supply every string or the derive fails.
3//!
4//! ```
5//! use enum_strings::EnumStrings;
6//!
7//! #[derive(Clone, Copy, EnumStrings)]
8//! enum Route {
9//!     #[strings(path = "/", label = "Home")]
10//!     Home,
11//!     #[strings(path = "/docs", label = "Docs")]
12//!     Docs,
13//! }
14//!
15//! assert_eq!(Route::Docs.path(), "/docs");
16//! assert_eq!(Route::Home.label(), "Home");
17//! ```
18//!
19//! The first variant decides which strings exist. A variant that leaves one
20//! out, adds one, or repeats one is a compile error on that variant, which is
21//! the check a `match` gives you and a runtime property lookup does not.
22
23use proc_macro2::TokenStream;
24use quote::{format_ident, quote};
25use syn::{Data, DeriveInput, Error, Fields, Ident, LitStr, Result, Variant};
26
27/// See the [crate documentation](crate).
28#[proc_macro_derive(EnumStrings, attributes(strings))]
29pub fn derive_enum_strings(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
30    syn::parse2(TokenStream::from(input))
31        .and_then(|input| expand(&input))
32        .unwrap_or_else(Error::into_compile_error)
33        .into()
34}
35
36/// The strings of one variant, in attribute order.
37struct Strings {
38    /// The variant they belong to.
39    variant: Ident,
40    /// Each `key = "value"`.
41    values: Vec<(Ident, LitStr)>,
42}
43
44/// Parses every `#[strings(key = "value")]` on a variant.
45fn parse_variant(variant: &Variant) -> Result<Strings> {
46    if !matches!(variant.fields, Fields::Unit) {
47        return Err(Error::new_spanned(
48            variant,
49            "EnumStrings only supports unit variants",
50        ));
51    }
52    let mut values: Vec<(Ident, LitStr)> = Vec::new();
53    for attr in variant
54        .attrs
55        .iter()
56        .filter(|a| a.path().is_ident("strings"))
57    {
58        attr.parse_nested_meta(|meta| {
59            let key = meta.path.require_ident()?.clone();
60            if values.iter().any(|(seen, _)| *seen == key) {
61                return Err(meta.error(format!("`{key}` given twice")));
62            }
63            let value: LitStr = meta.value()?.parse()?;
64            values.push((key, value));
65            Ok(())
66        })?;
67    }
68    if values.is_empty() {
69        return Err(Error::new_spanned(
70            variant,
71            "missing `#[strings(...)]`, every variant must supply every string",
72        ));
73    }
74    Ok(Strings {
75        variant: variant.ident.clone(),
76        values,
77    })
78}
79
80/// Checks a variant against the strings the first variant declared.
81fn check_keys(strings: &Strings, keys: &[Ident]) -> Result<()> {
82    let expected = keys
83        .iter()
84        .map(|key| format!("`{key}`"))
85        .collect::<Vec<_>>()
86        .join(", ");
87    for (key, _) in &strings.values {
88        if !keys.contains(key) {
89            return Err(Error::new(
90                key.span(),
91                format!("unknown string `{key}`, the first variant declares {expected}"),
92            ));
93        }
94    }
95    for key in keys {
96        if !strings.values.iter().any(|(seen, _)| seen == key) {
97            return Err(Error::new(
98                strings.variant.span(),
99                format!("variant `{}` is missing `{key}`", strings.variant),
100            ));
101        }
102    }
103    Ok(())
104}
105
106/// Generates the `impl` with one `const fn` per string.
107fn expand(input: &DeriveInput) -> Result<TokenStream> {
108    let Data::Enum(data) = &input.data else {
109        return Err(Error::new_spanned(input, "EnumStrings only supports enums"));
110    };
111    let variants = data
112        .variants
113        .iter()
114        .map(parse_variant)
115        .collect::<Result<Vec<_>>>()?;
116    let keys: Vec<Ident> = variants
117        .first()
118        .map(|first| first.values.iter().map(|(key, _)| key.clone()).collect())
119        .unwrap_or_default();
120    for strings in &variants {
121        check_keys(strings, &keys)?;
122    }
123
124    let name = &input.ident;
125    let vis = &input.vis;
126    let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
127    let methods = keys.iter().map(|key| {
128        let doc = format!("The `{key}` of this variant.");
129        let method = format_ident!("{key}");
130        let arms = variants.iter().map(|strings| {
131            let variant = &strings.variant;
132            // `check_keys` guarantees the key is present on every variant.
133            let value = strings
134                .values
135                .iter()
136                .find(|(seen, _)| seen == key)
137                .map(|(_, value)| value);
138            quote! { Self::#variant => #value }
139        });
140        quote! {
141            #[doc = #doc]
142            #[must_use]
143            #vis const fn #method(self) -> &'static str {
144                match self {
145                    #(#arms),*
146                }
147            }
148        }
149    });
150    Ok(quote! {
151        #[automatically_derived]
152        impl #impl_generics #name #ty_generics #where_clause {
153            #(#methods)*
154        }
155    })
156}
157
158#[cfg(test)]
159mod tests {
160    use syn::parse_quote;
161
162    use super::*;
163
164    /// The error message the derive reports for `input`, or `None` when it
165    /// expands.
166    fn error(input: &DeriveInput) -> Option<String> {
167        expand(input).err().map(|error| error.to_string())
168    }
169
170    #[test]
171    fn generates_a_const_fn_per_string() -> anyhow::Result<()> {
172        let input: DeriveInput = parse_quote! {
173            pub enum Route {
174                #[strings(path = "/", label = "Home")]
175                Home,
176                #[strings(label = "Docs", path = "/docs")]
177                Docs,
178            }
179        };
180        let expanded = expand(&input)?.to_string();
181        assert!(
182            expanded.contains("pub const fn path (self) -> & 'static str"),
183            "{expanded}"
184        );
185        assert!(
186            expanded.contains("pub const fn label (self) -> & 'static str"),
187            "{expanded}"
188        );
189        assert!(expanded.contains("Self :: Docs => \"/docs\""), "{expanded}");
190        assert!(expanded.contains("Self :: Docs => \"Docs\""), "{expanded}");
191        Ok(())
192    }
193
194    #[test]
195    fn every_variant_must_supply_every_string() {
196        let input: DeriveInput = parse_quote! {
197            enum Route {
198                #[strings(path = "/", label = "Home")]
199                Home,
200                #[strings(path = "/docs")]
201                Docs,
202            }
203        };
204        assert_eq!(
205            error(&input).as_deref(),
206            Some("variant `Docs` is missing `label`")
207        );
208
209        let input: DeriveInput = parse_quote! {
210            enum Route {
211                #[strings(path = "/", label = "Home")]
212                Home,
213                Docs,
214            }
215        };
216        assert_eq!(
217            error(&input).as_deref(),
218            Some("missing `#[strings(...)]`, every variant must supply every string")
219        );
220    }
221
222    #[test]
223    fn strings_must_match_the_first_variant() {
224        let input: DeriveInput = parse_quote! {
225            enum Route {
226                #[strings(path = "/", label = "Home")]
227                Home,
228                #[strings(path = "/docs", lable = "Docs")]
229                Docs,
230            }
231        };
232        assert_eq!(
233            error(&input).as_deref(),
234            Some("unknown string `lable`, the first variant declares `path`, `label`")
235        );
236
237        let input: DeriveInput = parse_quote! {
238            enum Route {
239                #[strings(path = "/", path = "/again")]
240                Home,
241            }
242        };
243        assert_eq!(error(&input).as_deref(), Some("`path` given twice"));
244    }
245
246    #[test]
247    fn only_unit_variants_of_enums() {
248        let input: DeriveInput = parse_quote! {
249            enum Route {
250                #[strings(path = "/")]
251                Home(u8),
252            }
253        };
254        assert_eq!(
255            error(&input).as_deref(),
256            Some("EnumStrings only supports unit variants")
257        );
258
259        let input: DeriveInput = parse_quote! {
260            struct Route;
261        };
262        assert_eq!(
263            error(&input).as_deref(),
264            Some("EnumStrings only supports enums")
265        );
266    }
267}