quick_macros/
lib.rs

1//! # Quick Macros
2//!
3//! This crate provides simple macros:
4//! - **Derive**
5//!     - FieldNames - macro used for generating functions returning a name of a field
6//!
7
8use proc_macro::TokenStream;
9use proc_macro_error::proc_macro_error;
10use syn::{parse_macro_input, DeriveInput};
11mod ctor;
12mod field_names;
13
14/// Generates methods for retrieving field names of a struct as string literals.
15///
16/// This function is used as part of a procedural macro. It takes a struct definition,
17/// extracts its named fields, and generates a method for each field. Each generated method
18/// follows the naming pattern `nameof_<field_name>()`, which returns the field name as a static string.
19///
20/// # Example
21/// ```
22/// use quick_macros::FieldNames;
23///
24/// #[derive(FieldNames)]
25/// struct Person {
26///     name: String,
27///     age: u32,
28/// }
29///
30/// assert_eq!(Person::nameof_name(), "name");
31/// assert_eq!(Person::nameof_age(), "age");
32/// ```
33///
34/// # Panics
35/// - If the macro is applied to a non-struct type (e.g., an enum or union), it will panic.
36#[proc_macro_derive(FieldNames)]
37#[proc_macro_error]
38pub fn field_names(input: TokenStream) -> TokenStream {
39    let input = parse_macro_input!(input as DeriveInput);
40    field_names::field_names(input).into()
41}
42
43/// Generates a constructor method for a struct, allowing instantiation with all fields.
44///
45/// This procedural macro derives an implementation of a new method for a struct.
46/// The generated method takes each field of the struct as a parameter and returns an instance
47/// of the struct with those fields initialized.
48///
49/// # Example
50/// ```
51/// use quick_macros::FullCtor;
52///
53/// #[derive(FullCtor)]
54/// struct Person {
55///     name: String,
56///     age: u32,
57/// }
58///
59/// let person = Person::new("Alice".to_string(), 30);
60/// assert_eq!(person.name, "Alice");
61/// assert_eq!(person.age, 30);
62/// ```
63///
64/// # Panics
65/// - If the macro is applied to a non-struct type (e.g., an enum or union), it will panic.
66#[proc_macro_derive(FullCtor)]
67#[proc_macro_error]
68pub fn full_ctor(input: TokenStream) -> TokenStream {
69    let input = parse_macro_input!(input as DeriveInput);
70    ctor::full_ctor(input).into()
71}