structural_typing_macros/lib.rs
1use proc_macro::TokenStream;
2use syn::{DeriveInput, parse_macro_input};
3
4mod codegen;
5mod parsing;
6
7/// Generates type-safe structural typing support for a struct.
8///
9/// This macro transforms a struct to track which fields are present/absent at the type level,
10/// enabling compile-time enforcement of field requirements.
11///
12/// **Note**: If you use `#[derive(...)]` on your struct, you must add `derive-where` to your dependencies:
13/// ```bash
14/// cargo add derive-where
15/// ```
16///
17/// # Generated Code
18///
19/// For a struct `MyStruct`, this macro generates:
20///
21/// - A `my_struct` module with `Fields` trait, `FieldSet<...>` type, and `with::` aliases
22/// - Builder methods: `.field(value)`
23/// - Getter methods: `.get_field()`, `.get_field_mut()`
24/// - `.merge()`, `.split()`, `.try_split()` operations
25///
26/// # Field States
27///
28/// - **Present**: Value of type `T`
29/// - **Optional**: `Option<T>`
30/// - **Absent**: `PhantomData<T>`
31///
32/// # Example
33///
34/// ```ignore
35/// use structural_typing::{structural, presence::Present};
36///
37/// #[structural]
38/// struct User {
39/// name: String,
40/// email: String,
41/// }
42///
43/// // Build incrementally
44/// let user = User::empty().name("Alice".to_owned());
45///
46/// // Methods can require specific fields
47/// impl<F: user::Fields<name = Present>> User<F> {
48/// fn greet(&self) -> String {
49/// format!("Hello, {}!", self.name)
50/// }
51/// }
52///
53/// user.greet(); // ✓ Compiles
54/// ```
55///
56/// # Restrictions
57///
58/// - Named structs only
59/// - No generics
60/// - At least one field
61#[proc_macro_attribute]
62pub fn structural(_attr: TokenStream, item: TokenStream) -> TokenStream {
63 let input = parse_macro_input!(item as DeriveInput);
64
65 match codegen::generate(input) {
66 Ok(tokens) => tokens.into(),
67 Err(err) => err.to_compile_error().into(),
68 }
69}