derive_atom_set/lib.rs
1#![doc = include_str!("../README.md")]
2
3use proc_macro::TokenStream;
4use syn::{DeriveInput, parse_macro_input};
5
6mod atom_set;
7
8/// Derives an efficient `AtomSet` implementation (the trait from the `atom_set` crate) for interned identifiers.
9///
10/// This proc macro automatically generates optimized string-to-enum matching code.
11///
12/// ## Variant Attributes
13///
14/// - `#[default]`: Marks this variant as the empty/fallback value (returns empty string)
15/// - `#[atom("custom")]`: Overrides the default string representation
16///
17/// ## Container Attributes
18///
19/// - `#[atom_set(case_sensitive)]`: `from_str` matches bytes exactly instead of ASCII case-insensitively
20///
21/// ## Naming Convention
22///
23/// If `#[atom("")]` is not provided a string is derived from the variant name:
24/// - `Px` → `"px"`
25/// - `FontSize` → `"font-size"`
26/// - `WebkitTransform` → `"webkit-transform"`
27///
28/// # Example
29///
30/// ```rust
31/// use atom_set::AtomSet;
32/// use derive_atom_set::AtomSet as DeriveAtomSet;
33///
34/// #[derive(Debug, Default, Copy, Clone, PartialEq, DeriveAtomSet)]
35/// pub enum MyAtomSet {
36/// #[default]
37/// Unknown, // Must provide an empty default!
38///
39/// // Absolute units
40/// Px, Pt, Pc, In, Cm, Mm, Q,
41///
42/// // Relative units
43/// Em, Ex, Ch, Rem, Lh,
44///
45/// // Viewport units
46/// Vw, Vh, Vi, Vb, Vmin, Vmax,
47///
48/// // Container query units
49/// Cqw, Cqh, Cqi, Cqb, Cqmin, Cqmax,
50///
51/// // Special case
52/// #[atom("%")]
53/// Percent,
54/// }
55///
56/// // Usage:
57/// assert_eq!(MyAtomSet::from_str("px"), MyAtomSet::Px);
58/// assert_eq!(MyAtomSet::from_str("PX"), MyAtomSet::Px); // Case insensitive matches
59/// assert_eq!(MyAtomSet::Px.to_str(), "px");
60/// assert_eq!(MyAtomSet::Percent.to_str(), "%");
61/// assert_eq!(MyAtomSet::from_str("unknown"), MyAtomSet::Unknown);
62/// ```
63#[proc_macro_derive(AtomSet, attributes(default, atom, atom_set))]
64pub fn derive_atom_set(input: TokenStream) -> TokenStream {
65 let ast = parse_macro_input!(input as DeriveInput);
66 atom_set::generate(proc_macro2::TokenStream::new(), ast).into()
67}