struct_mapper_derive/lib.rs
1//! # struct-mapper-derive
2//!
3//! Procedural macro crate for `struct-mapper`.
4//! Provides `#[derive(MapFrom)]` to auto-generate `impl From<Source> for Target`.
5//!
6//! **Do not depend on this crate directly.** Use `struct-mapper` instead.
7
8use proc_macro::TokenStream;
9use syn::{parse_macro_input, DeriveInput};
10
11mod codegen;
12mod error;
13mod field_match;
14mod parse;
15
16/// Derive macro that generates `impl From<Source> for Target` by mapping fields.
17///
18/// # Usage
19///
20/// ```rust,ignore
21/// use struct_mapper::MapFrom;
22///
23/// struct UserEntity {
24/// name: String,
25/// email: String,
26/// }
27///
28/// #[derive(MapFrom)]
29/// #[map_from(UserEntity)]
30/// struct UserResponse {
31/// name: String,
32/// email: String,
33/// }
34///
35/// // Now you can do:
36/// let entity = UserEntity { name: "Alice".into(), email: "a@b.com".into() };
37/// let response: UserResponse = entity.into();
38/// ```
39///
40/// # Field Attributes
41///
42/// - `#[map(from = "source_field")]` — Map from a differently-named source field
43/// - `#[map(skip, default)]` — Skip this field, use `Default::default()`
44/// - `#[map(into)]` — Call `.into()` on the source field value
45/// - `#[map(with = "path::to::fn")]` — Apply a custom conversion function
46#[proc_macro_derive(MapFrom, attributes(map_from, map))]
47pub fn derive_map_from(input: TokenStream) -> TokenStream {
48 let input = parse_macro_input!(input as DeriveInput);
49
50 match codegen::expand_map_from(&input) {
51 Ok(tokens) => tokens.into(),
52 Err(err) => err.to_compile_error().into(),
53 }
54}