kutil_std_macros/
lib.rs

1// https://stackoverflow.com/a/61417700
2#![cfg_attr(docsrs, feature(doc_auto_cfg))]
3#![warn(missing_docs)]
4
5/*!
6Various Rust utilities to enhance the standard library.
7
8Part of the Kutil family of Rust utility libraries.
9
10The word "kutil" means "do-it-yourselfer" in Czech.
11
12For more information and usage examples see the
13[home page](https://github.com/tliron/rust-kutil).
14*/
15
16mod attributes;
17mod derive_display;
18mod derive_from_str;
19
20// See: https://petanode.com/posts/rust-proc-macro/
21
22/// Procedural macro for `#[derive(Display)]`.
23#[proc_macro_derive(Display, attributes(display, strings))]
24pub fn derive_display(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
25    let mut input: syn::DeriveInput = syn::parse_macro_input!(input);
26
27    match input.data {
28        syn::Data::Enum(_) => derive_display::Generator::generate(&mut input),
29
30        _ => Err(syn::Error::new(input.ident.span(), "`Display`: not an enum")),
31    }
32    .unwrap_or_else(|e| e.to_compile_error())
33    .into()
34}
35
36/// Procedural macro for `#[derive(FromStr)]`.
37#[proc_macro_derive(FromStr, attributes(from_str, strings))]
38pub fn derive_from_str(input: proc_macro::TokenStream) -> proc_macro::TokenStream {
39    let mut input: syn::DeriveInput = syn::parse_macro_input!(input);
40
41    match input.data {
42        syn::Data::Enum(_) => derive_from_str::Generator::generate(&mut input),
43
44        _ => Err(syn::Error::new(input.ident.span(), "`FromStr`: not an enum")),
45    }
46    .unwrap_or_else(|e| e.to_compile_error())
47    .into()
48}