former_meta/
lib.rs

1//! # Former Meta - Procedural Macro Implementation
2//!
3//! This crate provides the procedural macro implementation for the Former derive macro.
4//! It handles the complex code generation required to implement the builder pattern with
5//! advanced features like subforms, collections, and custom validation.
6//!
7//! ## Architecture Overview
8//!
9//! The Former meta crate is organized around several key components:
10//!
11//! ### Core Processing Pipeline
12//! 1. **Input Parsing**: Parse derive input and extract struct/enum information
13//! 2. **Attribute Processing**: Parse and validate all Former-specific attributes
14//! 3. **Type Analysis**: Analyze generic parameters, lifetimes, and field types
15//! 4. **Code Generation**: Generate the complete Former ecosystem
16//! 5. **Output Assembly** : Combine generated code into final token stream
17//!
18//! ### Key Modules
19//! - [`derive_former`] : Main entry point and orchestration logic
20//! - Field attribute processing and validation
21//! - Struct attribute parsing and management  
22//! - Generic parameter handling for complex scenarios
23//! - Code generation for structs and enums
24//!
25//! ## Supported Constructs
26//!
27//! ### Struct Support
28//! - **Simple Structs** : Basic field-based structures
29//! - **Generic Structs** : Complex generic parameters with constraints
30//! - **Lifetime Parameters** : Full lifetime parameter support
31//! - **Tuple Structs** : Positional field structures
32//!
33//! ### Enum Support  
34//! - **Unit Variants** : Simple enum variants without data
35//! - **Tuple Variants** : Variants with positional fields
36//! - **Struct Variants** : Variants with named fields
37//! - **Mixed Enums** : Enums combining different variant types
38//!
39//! ## Advanced Features
40//!
41//! ### Collection Integration
42//! - Automatic detection and handling of standard collections
43//! - Custom collection support through trait implementations
44//! - Specialized builders for Vec, `HashMap`, `HashSet`, etc.
45//!
46//! ### Subform Support
47//! - Nested structure building with full type safety
48//! - Automatic trait bound propagation
49//! - Context preservation across subform boundaries
50//!
51//! ### Validation and Mutation
52//! - Pre-formation validation through custom mutators
53//! - Storage field manipulation before final formation
54//! - Custom end handlers for specialized formation logic
55//!
56//! ## Error Handling and Diagnostics
57//!
58//! The macro provides comprehensive error reporting :
59//! - Clear error messages for attribute misuse
60//! - Helpful suggestions for common mistakes
61//! - Debug output capabilities for troubleshooting
62//! - Integration with Rust's diagnostic system
63//!
64//! ## Performance Considerations
65//!
66//! - **Compile-time Generation** : All code generated at compile time
67//! - **Minimal Runtime Overhead** : Generated code is highly optimized
68//! - **Memory Efficient** : Strategic use of references and zero-cost abstractions
69//! - **Lazy Evaluation** : Complex analysis only when needed
70
71//#![ feature( proc_macro_totokens ) ] // Enable unstable proc_macro_totokens feature
72#![doc(html_logo_url = "https://raw.githubusercontent.com/Wandalen/wTools/master/asset/img/logo_v3_trans_square.png")]
73#![doc(
74  html_favicon_url = "https://raw.githubusercontent.com/Wandalen/wTools/alpha/asset/img/logo_v3_trans_square_icon_small_v2.ico"
75)]
76#![doc(html_root_url = "https://docs.rs/former_derive_meta/latest/former_derive_meta/")]
77#![ cfg_attr( doc, doc = include_str!( concat!( env!( "CARGO_MANIFEST_DIR" ), "/", "readme.md" ) ) ) ]
78
79#[ allow( unused_imports ) ]
80#[ cfg( feature = "enabled" ) ]
81use macro_tools::{ Result, diag };
82
83#[ cfg( feature = "derive_former" ) ]
84mod derive_former;
85
86/// Derive macro for generating a `Former` struct, applying a Builder Pattern to the annotated struct.
87///
88/// This macro simplifies the construction of complex objects by automatically generating a builder (former) for
89/// the specified struct. It supports extensive customization through attributes that control defaults, setter generation,
90/// and field customization, allowing for flexible and fluent object construction.
91///
92/// # Core Capabilities and Limitations
93///
94/// ## ✅ Supported Scenarios
95/// - **Complex Lifetime Parameters** : Handles `< 'a, T >` patterns, multiple lifetimes, and where clauses
96/// - **Generic Constraints** : Works with `where T: Hash + Eq`, complex trait bounds
97/// - **Nested Structures** : Subform support for complex hierarchical data
98/// - **Collection Types** : `HashMap`, Vec, `HashSet` with proper trait bound handling
99/// - **Optional Fields** : Automatic `Option< T >` handling with sensible defaults
100/// - **Custom Mutators** : Pre-formation data manipulation and validation
101///
102/// ## ⚠️ Common Pitfalls and Solutions
103///
104/// ### 1. Commented-Out Derive Attributes (90% of issues)
105/// ```rust,ignore
106/// // ❌ WRONG: Derive commented out - will appear as "complex" issue
107/// // #[ derive( Debug, PartialEq, Former ) ]
108/// #[ derive( Debug, PartialEq ) ]
109/// pub struct MyStruct { ... }
110///
111/// // ✅ CORRECT: Uncomment derive attribute
112/// #[ derive( Debug, PartialEq, Former ) ]
113/// pub struct MyStruct { ... }
114/// ```
115///
116/// ### 2. Feature Gate Requirements for Collections
117/// ```rust,ignore
118/// // ✅ REQUIRED: Collection tests need proper feature gates
119/// #[ cfg(any(not(feature = "no_std"), feature = "use_alloc")) ]
120/// mod test_with_collections;
121/// ```
122///
123/// ### 3. Hash+Eq Trait Bounds for `HashMap` Keys
124/// ```rust,ignore
125/// // ❌ WRONG: Using non-Hash type as HashMap key
126/// pub struct Definition; // No Hash+Eq implementation
127/// pub struct MyStruct {
128///   map: HashMap< Definition, String >, // Will fail
129/// }
130///
131/// // ✅ CORRECT: Implement required traits or use different key type
132/// #[ derive( Hash, Eq, PartialEq ) ]
133/// pub struct Definition; // Now implements Hash+Eq
134/// ```
135///
136/// ### 4. Lifetime Parameter Complexity
137/// ```rust,ignore
138/// // ✅ WORKS: Complex lifetime scenarios are supported
139/// #[ derive( Former ) ]
140/// pub struct Child< 'child, T >
141/// where
142///   T: 'child + ?Sized,
143/// {
144///   name: String,
145///   data: &'child T,
146/// }
147/// ```
148///
149/// ## 📋 Diagnostic Workflow
150/// When encountering issues :
151/// 1. **Check for commented derives** (resolves 90% of issues)
152/// 2. **Verify feature gate configuration** (for collection tests)
153/// 3. **Assess trait bound requirements** (Hash+Eq for `HashMap` keys)
154/// 4. **Test incremental complexity** (start simple, add complexity gradually)
155/// 5. **Enable debug output** (use `#[ debug ]` to see generated code)
156/// 6. **Check lifetime parameters** (ensure proper lifetime annotations)
157///
158/// ### Common Error Patterns and Solutions
159///
160/// #### E0277: Trait bound not satisfied
161/// ```text
162/// error[E0277] : the trait bound `MyType: Hash` is not satisfied
163/// ```
164/// **Solution** : Implement required traits for `HashMap` keys :
165/// ```rust,ignore
166/// #[ derive( Hash, Eq, PartialEq ) ]
167/// struct MyType { /* fields */ }
168/// ```
169///
170/// #### E0106: Missing lifetime specifier
171/// ```text
172/// error[E0106] : missing lifetime specifier
173/// ```
174/// **Solution** : Add proper lifetime parameters :
175/// ```rust,ignore
176/// #[ derive( Former ) ]
177/// struct MyStruct< 'a > {
178///     reference: &'a str,
179/// }
180/// ```
181///
182/// #### Commented Derive Issues
183/// ```rust,ignore
184/// // ❌ WRONG: This will appear as a "complex" compilation error
185/// // #[ derive( Debug, PartialEq, Former ) ]
186/// #[ derive( Debug, PartialEq ) ]
187/// struct MyStruct { field: String }
188///
189/// // ✅ CORRECT: Uncomment the derive attribute
190/// #[ derive( Debug, PartialEq, Former ) ]
191/// struct MyStruct { field: String }
192/// ```
193///
194/// #### Collection Feature Gate Issues
195/// ```rust,ignore
196/// // ✅ REQUIRED: Add feature gates for collection tests
197/// #[ cfg(any(not(feature = "no_std"), feature = "use_alloc")) ]
198/// mod collection_tests {
199///     // HashMap/Vec tests here
200/// }
201/// ```
202///
203/// # Struct Attributes
204///
205/// - `debug` : Enables debug mode which can be used to print or log the internal state of the builder for debugging purposes.
206/// - `perform` : Specifies a custom method to be invoked automatically at the end of the build process.
207/// - `storage_fields` : Specifies fields that should be treated as part of the storage for the former.
208/// - `mutator` : Defines a custom mutator class or function to manipulate the data just before the object is finalized.
209/// - `standalone_constructors` : Generates top-level constructor functions (e.g., `my_struct()`, `my_variant()`). Return type depends on `former_ignore` (see Option 2 logic in Readme/advanced.md).
210///
211/// # Field Attributes
212///
213/// - `former` : General attribute to specify various options like defaults or inclusion in the former.
214/// - `scalar` : Indicates that the field is a scalar value, enabling direct assignment without the need for a sub-former. Affects the *associated method* constructor for enum variants.
215/// - `collection` : Marks the field as a collection that can use specific former methods to manage its contents.
216/// - `subform` : Specifies that the field should utilize a nested former, facilitating the construction of complex nested structures.
217/// - `former_ignore` : Excludes a field from being an argument for the standalone constructor. Affects constructor signature and return type (see Option 2 logic in Readme/advanced.md).
218///
219/// # Usage Examples
220///
221/// ## Basic Structure Building
222///
223/// ```rust,ignore
224/// use former ::Former;
225///
226/// #[ derive( Debug, PartialEq, Former ) ]
227/// pub struct UserProfile {
228///     age: i32,
229///     username: String,
230///     bio_optional: Option< String >,
231/// }
232///
233/// let profile = UserProfile ::former()
234///     .age(30)
235///     .username("JohnDoe".to_string())
236///     .bio_optional("Software Developer".to_string())
237///     .form();
238/// ```
239///
240/// ## Collection Handling
241///
242/// ```rust,ignore
243/// use former ::Former;
244/// use std ::collections ::HashMap;
245///
246/// #[ derive( Debug, Former ) ]
247/// pub struct Config {
248///     #[ collection ]
249///     settings: HashMap< String, String >,
250///     #[ collection ]
251///     tags: Vec< String >,
252/// }
253///
254/// let config = Config ::former()
255///     .settings().insert("debug", "true").end()
256///     .tags().push("production").push("web").end()
257///     .form();
258/// ```
259///
260/// ## Complex Generic Scenarios
261///
262/// ```rust,ignore
263/// use former ::Former;
264///
265/// #[ derive( Debug, Former ) ]
266/// pub struct Container< 'a, T >
267/// where
268///     T: Clone + 'a,
269/// {
270///     data: &'a T,
271///     metadata: Option< String >,
272/// }
273///
274/// let value = "hello".to_string();
275/// let container = Container ::former()
276///     .data(&value)
277///     .metadata("example".to_string())
278///     .form();
279/// ```
280///
281/// ## Custom Validation with Mutators
282///
283/// ```rust,ignore
284/// use former ::Former;
285///
286/// #[ derive( Debug, Former ) ]
287/// #[ mutator( custom ) ]
288/// pub struct ValidatedStruct {
289///     min_value: i32,
290///     max_value: i32,
291/// }
292///
293/// // Custom mutator implementation
294/// impl FormerMutator  for ValidatedStructDefinitionTypes
295/// {
296///     fn form_mutation(storage: &mut Self ::Storage, _context: &mut Option< Self ::Context >) {
297///  if let (Some(min), Some(max)) = (&storage.min_value, &storage.max_value) {
298///  if min > max {
299///                 std ::mem ::swap(&mut storage.min_value, &mut storage.max_value);
300/// }
301/// }
302/// }
303/// }
304/// ```
305///
306/// ## Debugging Generated Code
307///
308/// The Former derive macro provides comprehensive debugging capabilities through the `#[ debug ]` attribute,
309/// following the design principle that "Proc Macros: Must Implement a 'debug' Attribute".
310///
311/// ### Debug Attribute Usage
312///
313/// ```rust,ignore
314/// use former ::Former;
315///
316/// // Standalone debug attribute
317/// #[ derive( Debug, PartialEq, Former ) ]
318/// #[ debug ]  // <-- Enables comprehensive debug output
319/// pub struct Person {
320///     name: String,
321///     age: u32,
322///     email: Option< String >,
323/// }
324///
325/// // Within #[ former( ... ) ] container
326/// #[ derive( Debug, PartialEq, Former ) ]
327/// #[ former( debug, standalone_constructors ) ]  // <-- Debug with other attributes
328/// pub struct Config {
329///     host: String,
330///     port: u16,
331/// }
332/// ```
333///
334/// ### Comprehensive Debug Information
335///
336/// When `#[ debug ]` is present and the `former_diagnostics_print_generated` feature is enabled,
337/// the macro provides detailed information in four phases :
338///
339/// #### Phase 1 : Input Analysis
340/// - **Target Type Information** : Name, kind (struct/enum), visibility
341/// - **Generic Parameters Analysis** : Lifetimes, type parameters, const parameters, where clauses
342/// - **Field/Variant Analysis** : Field names, types, visibility for structs; variant information for enums
343/// - **Attribute Configuration** : All parsed Former attributes, storage fields, mutator settings
344///
345/// #### Phase 2 : Generic Classification
346/// - **Classification Results** : How generics are categorized (lifetime-only, type-only, mixed, empty)
347/// - **Generated Generic Components** : `impl_generics`, `ty_generics`, `where_clause` breakdown
348/// - **Strategy Explanation** : Why certain generation strategies were chosen
349///
350/// #### Phase 3 : Generated Components Analysis
351/// - **Core Components** : `FormerStorage`, `FormerDefinition`, `FormerDefinitionTypes`, Former struct
352/// - **Trait Implementations** : `EntityToStorage`, `EntityToFormer`, `EntityToDefinition`, etc.
353/// - **Formation Process** : Step-by-step formation workflow explanation
354/// - **Customizations** : How attributes affect the generated code structure
355///
356/// #### Phase 4 : Complete Generated Code
357/// - **Final `TokenStream`** : The complete code that will be compiled
358/// - **Integration Points** : How generated code integrates with existing types
359///
360/// ### Enabling Debug Output
361///
362/// ```bash
363/// # See debug information during compilation
364/// cargo build --features former_diagnostics_print_generated
365///
366/// # For examples
367/// cargo run --example former_debug --features former_diagnostics_print_generated
368///
369/// # For tests with debug output
370/// cargo test --features former_diagnostics_print_generated
371/// ```
372///
373/// ### Debug Use Cases
374///
375/// The debug attribute is particularly useful for :
376///
377/// 1. **Understanding Macro Behavior** : See exactly how the macro processes your struct/enum definition
378/// 2. **Debugging Complex Scenarios** : Troubleshoot generic parameters, lifetime issues, trait bound problems
379/// 3. **Learning Former Pattern** : Understand the complete ecosystem generated for your types
380/// 4. **Verifying Configuration** : Confirm that attributes are parsed correctly and generate expected code
381/// 5. **Performance Analysis** : Understand the complexity of generated code for optimization
382///
383/// ### Integration with Development Workflow
384///
385/// The debug system integrates seamlessly with existing development tools :
386/// - **Zero Runtime Cost** : Debug analysis only runs during compilation
387/// - **Conditional Compilation** : Debug code only included with feature flag
388/// - **IDE Integration** : Debug output appears in compiler output and can be captured by IDEs
389/// - **CI/CD Friendly** : Can be enabled in build pipelines for automated analysis
390#[ cfg( feature = "enabled" ) ]
391#[ cfg( feature = "derive_former" ) ]
392#[
393  proc_macro_derive
394  (
395  Former,
396  attributes // This list defines attributes the derive macro processes
397  (
398   debug, perform, storage_fields, mutator, // struct attributes
399   former, scalar, subform_scalar, subform_collection, subform_entry, // field attributes
400   // < << Added the new attributes here >>>
401   standalone_constructors, // Add struct-level attribute
402   former_ignore,           // Add field-level attribute
403   arg_for_constructor      // Add field-level attribute for constructor inclusion
404 )
405 )
406]
407pub fn former(input: proc_macro::TokenStream) -> proc_macro::TokenStream 
408{
409  let result = derive_former ::former(input);
410  match result 
411  {
412  Ok(stream) => stream.into(),
413  Err(err) => err.to_compile_error().into(),
414 }
415}