former_meta 2.43.0

A flexible implementation of the Builder pattern supporting nested builders and collection-specific subformers. Implementation of its derive macro. Should not be used independently, instead use module::former which relies on the module.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
//! # Enum Former Generation - Comprehensive Enum Variant Former Generation
//!
//! This module implements sophisticated enum variant constructor generation for the Former pattern,
//! handling all possible enum variant types with proper attribute support and generic parameter
//! propagation. It resolves enum-specific pitfalls that manual implementations commonly encounter.
//!
//! ## Core Functionality
//!
//! ### Variant Type Support
//! - **Unit Variants** : `Variant` → Direct constructors
//! - **Tuple Variants** : `Variant(T1, T2, ...)` → Direct or subform constructors
//! - **Struct Variants** : `Variant { field1: T1, field2: T2, ... }` → Direct or implicit former constructors
//! - **Zero-Field Variants** : `Variant()` and `Variant {}` → Specialized handling
//!
//! ### Attribute-Driven Generation
//! - **`#[ scalar ]`** : Forces direct constructor generation for all variant types
//! - **`#[ subform_scalar ]`** : Enables subform-based construction with inner/variant formers
//! - **Default Behavior** : Intelligent selection based on variant field characteristics
//! - **`#[ standalone_constructors ]`** : Generates top-level constructor functions
//!
//! ## Expected Enum Former Behavior Matrix
//!
//! ### 1. `#[ scalar ]` Attribute Behavior
//! - **Unit Variant** : `Enum ::variant() -> Enum` (Direct constructor)
//! - **Zero-Field Tuple** : `Enum ::variant() -> Enum` (Direct constructor)
//! - **Zero-Field Struct** : `Enum ::variant() -> Enum` (Direct constructor)
//! - **Single-Field Tuple** : `Enum ::variant(InnerType) -> Enum` (Direct with parameter)
//! - **Single-Field Struct** : `Enum ::variant { field: InnerType } -> Enum` (Direct with named field)
//! - **Multi-Field Tuple** : `Enum ::variant(T1, T2, ...) -> Enum` (Direct with all parameters)
//! - **Multi-Field Struct** : `Enum ::variant { f1: T1, f2: T2, ... } -> Enum` (Direct with all fields)
//! - **Error Prevention** : Cannot be combined with `#[ subform_scalar ]` (generates compile error)
//!
//! ### 2. `#[ subform_scalar ]` Attribute Behavior
//! - **Unit Variant** : Error - No fields to form
//! - **Zero-Field Variants** : Error - No fields to form
//! - **Single-Field Tuple** : `Enum ::variant() -> InnerFormer< ... >` (Inner type former)
//! - **Single-Field Struct** : `Enum ::variant() -> VariantFormer< ... >` (Implicit variant former)
//! - **Multi-Field Tuple** : Error - Cannot subform multi-field tuples
//! - **Multi-Field Struct** : `Enum ::variant() -> VariantFormer< ... >` (Implicit variant former)
//!
//! ### 3. Default Behavior (No Attribute)
//! - **Unit Variant** : `Enum ::variant() -> Enum` (Direct constructor)
//! - **Zero-Field Tuple** : `Enum ::variant() -> Enum` (Direct constructor)
//! - **Zero-Field Struct** : Error - Requires explicit `#[ scalar ]` attribute
//! - **Single-Field Tuple** : `Enum ::variant() -> InnerFormer< ... >` (Inner type former - PROBLEMATIC: fails for primitives)
//! - **Single-Field Struct** : `Enum ::variant() -> VariantFormer< ... >` (Implicit variant former)
//! - **Multi-Field Tuple** : `Enum ::variant(T1, T2, ...) -> Enum` (Direct constructor - behaves like `#[ scalar ]`)
//! - **Multi-Field Struct** : `Enum ::variant() -> VariantFormer< ... >` (Implicit variant former)
//!
//! ### 4. `#[ standalone_constructors ]` Body-Level Attribute
//! - Generates top-level constructor functions for each variant: `my_variant()`
//! - Return type depends on `#[ former_ignore ]` field annotations
//! - Integrates with variant-level attribute behavior
//!
//! ## Critical Pitfalls Resolved
//!
//! ### 1. Enum Attribute Validation (Critical Prevention)
//! **Issue Resolved** : Manual implementations using incompatible attribute combinations
//! **Root Cause** : Unclear rules about which attributes can be combined
//! **Solution** : Comprehensive attribute validation with clear error messages
//! **Prevention** : Compile-time validation prevents incompatible attribute combinations
//!
//! ### 2. Variant Field Count Handling (Prevention)
//! **Issue Resolved** : Manual implementations not properly handling zero-field vs multi-field variants
//! **Root Cause** : Different field count scenarios requiring different generation strategies
//! **Solution** : Specialized handlers for each field count and variant type combination
//! **Prevention** : Automatic field count detection with appropriate handler selection
//!
//! ### 3. Generic Parameter Propagation (Prevention)
//! **Issue Resolved** : Enum generic parameters not properly propagated to variant constructors
//! **Root Cause** : Complex generic parameter tracking through enum variant generation
//! **Solution** : Systematic generic parameter preservation and propagation
//! **Prevention** : Complete generic information maintained through all generation phases
//!
//! ### 4. Inner Former Type Resolution (Critical Prevention)
//! **Issue Resolved** : Subform constructors not finding appropriate Former implementations
//! **Root Cause** : Manual implementations not validating that field types implement Former trait
//! **Solution** : Automatic Former trait validation with clear error messages
//! **Prevention** : Compile-time verification of Former trait availability for subform scenarios
//!
//! ## Architecture Overview
//!
//! ### Modular Handler Structure
//! The enum generation is organized into specialized handler modules for maintainability :
//!
//! ```text
//! former_enum/
//! ├── mod.rs                           # Main dispatch logic and shared definitions
//! ├── common_emitters.rs               # Shared code generation patterns
//! ├── unit_variant_handler.rs          # Unit variant processing
//! ├── tuple_*_handler.rs               # Tuple variant processing (zero/single/multi field)
//! └── struct_*_handler.rs              # Struct variant processing (zero/single/multi field)
//! ```
//!
//! ### Handler Dispatch Logic
//! 1. **Variant Analysis** : Determine variant type (Unit, Tuple, Struct) and field count
//! 2. **Attribute Processing** : Parse and validate variant-level attributes
//! 3. **Handler Selection** : Route to appropriate specialized handler
//! 4. **Generic Propagation** : Ensure generic parameters are properly maintained
//! 5. **Code Generation** : Generate appropriate constructor methods
//!
//! ### Shared Context and Utilities
//! - **`EnumVariantHandlerContext`** : Shared context information for all handlers
//! - **`EnumVariantFieldInfo`** : Standardized field information structure
//! - **Common Emitters** : Reusable code generation patterns for consistency
//!
//! ## Quality Assurance Features
//! - **Compile-Time Validation** : All attribute combinations validated at compile time
//! - **Generic Safety** : Generic parameters properly tracked and propagated
//! - **Type Safety** : All generated constructors maintain Rust's type safety guarantees
//! - **Error Reporting** : Clear, actionable error messages for invalid configurations
//!
#![allow(clippy ::wildcard_imports)] // Keep if present
#![allow(clippy ::unnecessary_wraps)] // Temporary for placeholder handlers
#![allow(clippy ::used_underscore_binding)] // Temporary for placeholder handlers
#![allow(clippy ::no_effect_underscore_binding)] // Temporary for placeholder handlers
#![allow(dead_code)] // Temporary for placeholder handlers
#![allow(unused_variables)] // Temporary for placeholder handlers


use macro_tools :: { Result, generic_params ::GenericsRef, syn, proc_macro2 };
#[ cfg( feature = "former_diagnostics_print_generated" ) ]
use macro_tools ::diag;
use macro_tools ::quote :: { format_ident, quote };
use macro_tools ::proc_macro2 ::TokenStream;
use super ::struct_attrs ::ItemAttributes; // Corrected import
use super ::field_attrs ::FieldAttributes; // Corrected import

// Declare new sibling modules
mod common_emitters;
mod struct_multi_fields_scalar;
mod struct_multi_fields_subform;
mod struct_single_field_scalar;
mod struct_single_field_subform;
mod struct_zero_fields_handler;
mod tuple_multi_fields_scalar;
mod tuple_multi_fields_subform;
mod tuple_single_field_scalar;
mod tuple_single_field_subform;
mod tuple_zero_fields_handler;
mod unit_variant_handler;

// Ensure EnumVariantHandlerContext and EnumVariantFieldInfo structs are defined
// or re-exported for use by submodules.
// These will remain in this file.
// qqq: Define EnumVariantFieldInfo struct
#[ allow( dead_code ) ] // Suppress warnings about unused fields
pub(super) struct EnumVariantFieldInfo
{
  pub ident: syn ::Ident,
  pub ty: syn ::Type,
  pub attrs: FieldAttributes,
  pub is_constructor_arg: bool,
}

// qqq: Define EnumVariantHandlerContext struct
#[ allow( dead_code ) ] // Suppress warnings about unused fields
pub(super) struct EnumVariantHandlerContext< 'a >
{
  pub ast: &'a syn ::DeriveInput,
  pub variant: &'a syn ::Variant,
  pub struct_attrs: &'a ItemAttributes,
  pub enum_name: &'a syn ::Ident,
  pub vis: &'a syn ::Visibility,
  pub generics: &'a syn ::Generics,
  pub original_input: &'a TokenStream,
  pub variant_attrs: &'a FieldAttributes,
  pub variant_field_info: &'a [EnumVariantFieldInfo],
  pub merged_where_clause: Option< &'a syn ::WhereClause >,
  pub methods: &'a mut Vec< TokenStream >,
  pub end_impls: &'a mut Vec< TokenStream >,
  pub standalone_constructors: &'a mut Vec< TokenStream >,

  pub has_debug: bool,


}

#[ allow( clippy ::too_many_lines ) ]
pub(super) fn former_for_enum(
  ast: &syn ::DeriveInput,
  data_enum: &syn ::DataEnum,
  original_input: &TokenStream,
  item_attributes: &ItemAttributes, // Changed: Accept parsed ItemAttributes
  has_debug: bool,
) -> Result< TokenStream > {
  let enum_name = &ast.ident;
  let vis = &ast.vis;
  let generics = &ast.generics;
  // let struct_attrs = ItemAttributes ::from_attrs( ast.attrs.iter() )?; // REMOVED: Use passed item_attributes
  let struct_attrs = item_attributes; // Use the passed-in item_attributes
   // qqq: Ensure ItemAttributes and FieldAttributes are accessible/imported

  // Diagnostic print for has_debug status (has_debug is now correctly determined by the caller)

  let mut methods = Vec ::new();
  let mut end_impls = Vec ::new();
  let generics_ref = GenericsRef ::new(generics);
  let enum_type_path = generics_ref.type_path_tokens_if_any(enum_name);
  let mut standalone_constructors = Vec ::new();
  let merged_where_clause = generics.where_clause.as_ref();

  for variant in &data_enum.variants 
  {
  let variant_attrs = FieldAttributes ::from_attrs(variant.attrs.iter())?;
  let variant_field_info: Vec< Result< EnumVariantFieldInfo >> =  match &variant.fields 
  {
   // qqq: Logic to populate variant_field_info (from previous plan)
   syn ::Fields ::Named(f) => f
  .named
  .iter()
  .map(|field| {
   let attrs = FieldAttributes ::from_attrs(field.attrs.iter())?;
   let is_constructor_arg =  if attrs.former_ignore.value(false) 
  {
  false  // Explicitly ignored
 } else  if attrs.arg_for_constructor.value(false) 
  {
  true   // Explicitly included
 } else {
  false  // Default: exclude (arg_for_constructor is opt-in)
 };
   Ok(EnumVariantFieldInfo {
  ident: field
   .ident
   .clone()
   .ok_or_else(|| syn ::Error ::new_spanned(field, "Named field requires an identifier"))?,
  ty: field.ty.clone(),
  attrs,
  is_constructor_arg,
 })
 })
  .collect(),
   syn ::Fields ::Unnamed(f) => f
  .unnamed
  .iter()
  .enumerate()
  .map(|(index, field)| {
   let attrs = FieldAttributes ::from_attrs(field.attrs.iter())?;
   let is_constructor_arg =  if attrs.former_ignore.value(false) 
  {
  false  // Explicitly ignored
 } else  if attrs.arg_for_constructor.value(false) 
  {
  true   // Explicitly included
 } else {
  false  // Default: exclude (arg_for_constructor is opt-in)
 };
   Ok(EnumVariantFieldInfo {
  ident: format_ident!("_{}", index),
  ty: field.ty.clone(),
  attrs,
  is_constructor_arg,
 })
 })
  .collect(),
   syn ::Fields ::Unit => vec![],
 };
  let variant_field_info: Vec< EnumVariantFieldInfo > = variant_field_info.into_iter().collect :: < Result< _ >>()?;

  let mut ctx = EnumVariantHandlerContext {
   ast,
   variant,
   struct_attrs,
   enum_name,
   vis,
   generics,
   original_input,
   variant_attrs: &variant_attrs,
   variant_field_info: &variant_field_info,
   merged_where_clause,
   methods: &mut methods,
   end_impls: &mut end_impls,
   standalone_constructors: &mut standalone_constructors,
   has_debug,
 };

  // Dispatch logic directly here
  match &ctx.variant.fields 
  {
   syn ::Fields ::Unit =>
  {
  let generated = unit_variant_handler ::handle(&mut ctx)?;
  ctx.methods.push(generated); // Collect generated tokens
 }
   syn ::Fields ::Unnamed(fields) =>  match fields.unnamed.len() 
  {
  0 =>
  {
   let generated = tuple_zero_fields_handler ::handle(&mut ctx)?;
   ctx.methods.push(generated); // Collect generated tokens
 }
  1 =>
  {
   if ctx.variant_attrs.scalar.is_some() 
   {
  let generated = tuple_single_field_scalar ::handle(&mut ctx)?;
  ctx.methods.push(generated); // Collect generated tokens
 } else {
  // CRITICAL ROUTING ISSUE: Default behavior attempts subform which fails for primitives
  // tuple_single_field_subform expects field type to implement Former trait
  // Primitive types (u32, String, etc.) don't implement Former, causing compilation errors
  // WORKAROUND: Users must add explicit #[ scalar ] for primitive field types
  // TODO: Add compile-time Former trait detection or auto-route to scalar for primitives
  let generated = tuple_single_field_subform ::handle(&mut ctx)?;
  ctx.methods.push(generated); // Collect generated tokens
 }
 }
  _ =>
  {
   if ctx.variant_attrs.subform_scalar.is_some() 
   {
  return Err(syn ::Error ::new_spanned(
   ctx.variant,
   "#[ subform_scalar ] cannot be used on tuple variants with multiple fields.",
 ));
 }
   if ctx.variant_attrs.scalar.is_some() 
   {
  let generated = tuple_multi_fields_scalar ::handle(&mut ctx)?;
  ctx.methods.push(generated); // Collect generated tokens
 } else {
  // Rule 3f: Multi-field tuple variants without attributes get implicit variant former
  // FIXED: This handler was completely non-functional due to syntax errors
  // Applied critical fixes: turbo fish syntax, PhantomData generics, empty generics handling
  // STATUS: Now fully functional and reliable for all multi-field tuple patterns
  let generated = tuple_multi_fields_subform ::handle(&mut ctx)?;
  ctx.methods.push(generated); // Collect generated tokens
 }
 }
 },
   syn ::Fields ::Named(fields) =>  match fields.named.len() 
  {
  0 =>
  {
   if ctx.variant_attrs.subform_scalar.is_some() 
   {
  return Err(syn ::Error ::new_spanned(
   ctx.variant,
   "#[ subform_scalar ] is not allowed on zero-field struct variants.",
 ));
 }
   if ctx.variant_attrs.scalar.is_none() 
   {
  return Err(syn ::Error ::new_spanned(
   ctx.variant,
   "Zero-field struct variants require `#[ scalar ]` attribute for direct construction.",
 ));
 }
   let generated = struct_zero_fields_handler ::handle(&mut ctx)?;
   ctx.methods.push(generated); // Collect generated tokens
 }
  _len =>
  {
   if ctx.variant_attrs.scalar.is_some() 
   {
  if fields.named.len() == 1 
  {
   let generated = struct_single_field_scalar ::handle(&mut ctx)?;
   ctx.methods.push(generated); // Collect generated tokens
 } else {
   let generated = struct_multi_fields_scalar ::handle(&mut ctx)?;
   ctx.methods.push(generated); // Collect generated tokens
 }
 } else  if fields.named.len() == 1 
  {
  let generated = struct_single_field_subform ::handle(&mut ctx)?;
  ctx.methods.push(generated); // Collect generated tokens
 } else {
  let generated = struct_multi_fields_subform ::handle(&mut ctx)?;
  ctx.methods.push(generated); // Collect generated tokens
 }
 }
 },
 }

 }

  let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();

  #[ cfg( feature = "former_diagnostics_print_generated" ) ]
  if has_debug 
  {
  diag ::report_print(
   format!("DEBUG: Raw generics for {enum_name}"),
   original_input,
   &quote! { #generics },
 );
  diag ::report_print(
   format!("DEBUG: impl_generics for {enum_name}"),
   original_input,
   &quote! { #impl_generics },
 );
  diag ::report_print(
   format!("DEBUG: ty_generics for {enum_name}"),
   original_input,
   &quote! { #ty_generics },
 );
  diag ::report_print(
   format!("DEBUG: where_clause for {enum_name}"),
   original_input,
   &quote! { #where_clause },
 );
 }

  let result = {
  let impl_header = quote! { impl #impl_generics #enum_name #ty_generics };

  #[ cfg( feature = "former_diagnostics_print_generated" ) ]
  if has_debug 
  {
   diag ::report_print(
  format!("DEBUG: Methods collected before final quote for {enum_name}"),
  original_input,
  &quote! { #( #methods )* },
 );
   diag ::report_print(
  format!("DEBUG: Impl header for {enum_name}"),
  original_input,
  &quote! { #impl_header },
 );
 }

  quote! {
   #( #end_impls )*

   impl #impl_generics #enum_name #ty_generics
   #where_clause
   {
   #( #methods )*
 }

   #( #standalone_constructors )*
 }
 };

  #[ cfg( feature = "former_diagnostics_print_generated" ) ]
  if has_debug 
  {
  let about = format!("derive: Former\nenum: {enum_name}");
  diag ::report_print(about, original_input, &result);
 }

  Ok(result)
}