tagid_derive/lib.rs
1//! Provides the `Label` derive macro for implementing the `tagid::Label` trait.
2//!
3//! # Overview
4//!
5//! The `Label` derive macro automatically implements the `Label` trait for a given type,
6//! defining an associated `Labeler` type and a default labeling function.
7//!
8//! # Example
9//!
10//! ```rust, ignore
11//! use tagid::Label;
12//!
13//! #[derive(Label)]
14//! struct MyType;
15//! ```
16//!
17//! The derived implementation generates:
18//!
19//! ```rust, ignore
20//! impl tagid::Label for MyType {
21//! type Labeler = tagid::MakeLabeling<Self>;
22//! fn labeler() -> Self::Labeler { tagid::MakeLabeling::default() }
23//! }
24//! ```
25//!
26//! # Dependencies
27//!
28//! This macro relies on the `syn`, `quote`, and `proc_macro` crates to parse the input,
29//! generate Rust code, and interact with the procedural macro system.
30
31use proc_macro::{self, TokenStream};
32use quote::quote;
33use syn::DeriveInput;
34
35/// Derives the `Label` trait for a struct or enum.
36///
37/// This macro implements the `Label` trait for the annotated type,
38/// setting its `Labeler` type to `MakeLabeling<Self>` and providing
39/// a default implementation for `labeler()`.
40///
41/// # Example
42///
43/// ```rust, ignore
44/// use tagid::Label;
45///
46/// #[derive(Label)]
47/// struct Example;
48///
49/// let labeler = Example::labeler();
50/// ```
51///
52/// The generated implementation:
53///
54/// ```ignore
55/// impl tagid::Label for Example {
56/// type Labeler = tagid::MakeLabeling<Self>;
57/// fn labeler() -> Self::Labeler { tagid::MakeLabeling::default() }
58/// }
59/// ```
60#[proc_macro_derive(Label)]
61pub fn label_derive(input: TokenStream) -> TokenStream {
62 let DeriveInput { ident, .. } = syn::parse_macro_input!(input);
63 let output = quote! {
64 impl ::tagid::Label for #ident {
65 type Labeler = ::tagid::MakeLabeling<Self>;
66 fn labeler() -> Self::Labeler { ::tagid::MakeLabeling::default() }
67 }
68 };
69 output.into()
70}