Skip to main content

variants_derive/
lib.rs

1/*
2    Appellation: variants-derive <library>
3    Contrib: FL03 <jo3mccain@icloud.com>
4*/
5//! The derive macros for the `variants` crate.
6//! 
7//! - [`VariantConstructors`]: generate functional constructors for all variants of an enum
8#![allow(
9    clippy::missing_safety_doc,
10    clippy::module_inception,
11    clippy::needless_doctest_main,
12    clippy::upper_case_acronyms
13)]
14#![cfg_attr(not(feature = "std"), no_std)]
15
16#[cfg(feature = "alloc")]
17extern crate alloc;
18
19#[cfg(not(any(feature = "std", feature = "alloc")))]
20compile_error! {
21    "Either feature `std` or `alloc` must be enabled"
22}
23
24extern crate proc_macro;
25extern crate quote;
26extern crate syn;
27
28#[allow(dead_code)]
29pub(crate) mod attrs;
30pub(crate) mod impls;
31pub(crate) mod utils;
32
33use proc_macro::TokenStream;
34use syn::{Data, DeriveInput};
35
36/// This macro automatically generates functional constructors for all enclosed variants.
37#[proc_macro_derive(VariantConstructors, attributes(variants))]
38pub fn variant_constructors(input: TokenStream) -> TokenStream {
39    let ast: DeriveInput = syn::parse(input).unwrap();
40
41    match ast.data {
42        Data::Enum(inner) => impls::impl_functional_constructors(&ast.ident, &inner.variants),
43        _ => panic!("This derive macro only works with enums"),
44    }
45    .into()
46}