type-state-builder 0.5.1

Type-state builder pattern derive macro with compile-time safety and enhanced ergonomics.
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
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
//! Token Generation Utilities
//!
//! This module provides the `TokenGenerator` utility that centralizes token stream
//! generation with configurable behavior. It separates the concerns of data analysis
//! from code generation, providing a clean interface for creating Rust code tokens.
//!
//! # Design Philosophy
//!
//! The `TokenGenerator` follows these principles:
//! - **Separation of concerns** - Analysis data separate from generation logic
//! - **Configurable output** - Control documentation, error messages, and formatting
//! - **Consistent generation** - Standardized patterns across all generated code
//! - **Comprehensive documentation** - Self-documenting generated code
//!

use crate::analysis::StructAnalysis;
use crate::generation::GenerationConfig;
use crate::utils::identifiers::generate_unique_identifier;
use proc_macro2::TokenStream;
use quote::quote;

/// Central utility for generating token streams with configurable behavior.
///
/// The `TokenGenerator` provides a consistent interface for generating Rust code
/// tokens from analyzed struct information. It encapsulates generation configuration
/// and provides methods for creating common code patterns.
///
/// # Configuration
///
/// The generator's behavior is controlled by a `GenerationConfig` that affects:
/// - Documentation generation (comprehensive vs minimal)
/// - Error message inclusion (helpful vs compact)
/// - Debug trait implementations
/// - Path qualification (full vs short paths)
///
/// # Generated Code Quality
///
/// The generator ensures:
/// - **Consistent formatting** - All generated code follows the same patterns
/// - **Comprehensive documentation** - Every generated item is documented
/// - **Error handling** - Helpful error messages for common mistakes
/// - **Generic safety** - Proper handling of complex generic parameters
#[derive(Debug, Clone)]
pub struct TokenGenerator<'a> {
    /// Reference to the analyzed struct information
    analysis: &'a StructAnalysis,

    /// Configuration controlling generation behavior
    config: GenerationConfig,

    /// Cached PhantomData field name for consistency across generation
    phantom_data_field_name: String,
}

impl<'a> TokenGenerator<'a> {
    /// Creates a new token generator with configuration derived from struct attributes.
    ///
    /// # Arguments
    ///
    /// * `analysis` - The analyzed struct information to generate code for
    ///
    /// # Returns
    ///
    /// A `TokenGenerator` configured based on struct attributes.
    ///
    pub fn new(analysis: &'a StructAnalysis) -> Self {
        let config = GenerationConfig {
            const_builder: analysis.struct_attributes().get_const_builder(),
            ..Default::default()
        };

        Self {
            analysis,
            config,
            phantom_data_field_name: generate_unique_identifier("_marker"),
        }
    }

    /// Gets a reference to the struct analysis.
    ///
    /// # Returns
    ///
    /// A reference to the `StructAnalysis` used by this generator.
    pub fn analysis(&self) -> &StructAnalysis {
        self.analysis
    }

    /// Gets a reference to the generation configuration.
    ///
    /// # Returns
    ///
    /// A reference to the `GenerationConfig` used by this generator.
    pub fn config(&self) -> &GenerationConfig {
        &self.config
    }

    /// Returns whether const-compatible builder methods should be generated.
    ///
    /// # Returns
    ///
    /// `true` if all builder methods should be `const fn`, `false` otherwise.
    pub fn is_const_builder(&self) -> bool {
        self.config.const_builder
    }

    /// Returns the `const` keyword token if const builder is enabled, otherwise empty.
    ///
    /// This helper method simplifies conditional const generation in method signatures.
    ///
    /// # Returns
    ///
    /// A `TokenStream` containing `const` if const builder is enabled, empty otherwise.
    pub fn const_keyword(&self) -> TokenStream {
        if self.config.const_builder {
            quote! { const }
        } else {
            quote! {}
        }
    }

    /// Gets the consistent PhantomData field name for this generator.
    ///
    /// This method ensures that the same PhantomData field name is used
    /// across all generated code for a single struct analysis.
    ///
    /// # Returns
    ///
    /// A reference to the PhantomData field name string.
    pub fn get_phantom_data_field_name(&self) -> &str {
        &self.phantom_data_field_name
    }

    // Generic token generation methods

    /// Generates impl generics tokens for implementation blocks.
    ///
    /// These are the generic parameters with their bounds, suitable for use
    /// in `impl<...>` declarations.
    ///
    /// # Returns
    ///
    /// A `TokenStream` containing the impl generics or empty if no generics.
    ///
    /// # Examples
    ///
    /// For `struct Example<T: Clone>`, generates: `< T : Clone >`
    pub fn impl_generics_tokens(&self) -> TokenStream {
        self.analysis.impl_generics_tokens()
    }

    /// Generates type generics tokens for type references.
    ///
    /// These are just the generic parameter names without bounds, suitable
    /// for use when referencing the type.
    ///
    /// # Returns
    ///
    /// A `TokenStream` containing the type generics or empty if no generics.
    ///
    /// # Examples
    ///
    /// For `struct Example<T, U>`, generates: `< T , U >`
    pub fn type_generics_tokens(&self) -> TokenStream {
        self.analysis.type_generics_tokens()
    }

    /// Generates where clause tokens for type definitions.
    ///
    /// # Returns
    ///
    /// A `TokenStream` containing the where clause or empty if none.
    ///
    /// # Examples
    ///
    /// For `struct Example<T> where T: Send`, generates: `where T : Send`
    pub fn where_clause_tokens(&self) -> TokenStream {
        self.analysis.where_clause_tokens()
    }

    // Documentation generation methods

    /// Generates a documentation comment for a struct method.
    ///
    /// The documentation style depends on the configuration. Full documentation
    /// includes examples and detailed descriptions, while minimal documentation
    /// provides only basic information.
    ///
    /// # Arguments
    ///
    /// * `method_name` - The name of the method being documented
    /// * `description` - Brief description of what the method does
    /// * `additional_info` - Optional additional information to include
    ///
    /// # Returns
    ///
    /// A `TokenStream` containing the documentation comment.
    ///
    pub fn generate_method_documentation(
        &self,
        method_name: &str,
        description: &str,
        additional_info: Option<&str>,
    ) -> TokenStream {
        if !self.config.include_documentation {
            return quote! {};
        }

        let mut doc_lines = vec![format!("{description}.")];

        if let Some(info) = additional_info {
            doc_lines.push(String::new()); // Empty line
            doc_lines.push(info.to_string());
        }

        if self.config.include_error_guidance {
            match method_name {
                "builder" => {
                    doc_lines.push(String::new());
                    let build_method_name =
                        self.analysis.struct_attributes().get_build_method_name();
                    doc_lines.push(format!(
                        "Create a builder, set required fields, then call `{build_method_name}()`."
                    ));
                }
                "build" => {
                    doc_lines.push(String::new());
                    doc_lines.push("# Panics".to_string());
                    doc_lines.push(String::new());
                    doc_lines.push(
                        "This method is only available after all required fields have been set."
                            .to_string(),
                    );
                }
                _ => {}
            }
        }

        let doc_comments: Vec<TokenStream> = doc_lines
            .into_iter()
            .map(|line| quote! { #[doc = #line] })
            .collect();

        quote! { #(#doc_comments)* }
    }

    /// Generates a documentation comment for a struct field.
    ///
    /// # Arguments
    ///
    /// * `field_name` - The name of the field
    /// * `field_type` - The type of the field
    /// * `is_required` - Whether the field is required
    /// * `context` - Context description (e.g., "Builder field for")
    ///
    /// # Returns
    ///
    /// A `TokenStream` containing the field documentation.
    pub fn generate_field_documentation(
        &self,
        field_name: &str,
        field_type: &str,
        is_required: bool,
        context: &str,
    ) -> TokenStream {
        if !self.config.include_documentation {
            return quote! {};
        }

        let requirement = if is_required { "required" } else { "optional" };
        let doc_text =
            format!("{context} {requirement} field `{field_name}` of type `{field_type}`.");

        quote! { #[doc = #doc_text] }
    }

    // Code generation utility methods

    /// Generates appropriate type paths based on configuration.
    ///
    /// When qualified paths are enabled, generates fully qualified paths
    /// for reliability. Otherwise, generates shorter paths for readability.
    ///
    /// # Arguments
    ///
    /// * `type_name` - The type name to generate a path for
    ///
    /// # Returns
    ///
    /// A `TokenStream` containing the appropriate type path.
    ///
    /// # Examples
    ///
    /// - Qualified: `::core::option::Option`
    /// - Unqualified: `Option`
    pub fn generate_type_path(&self, type_name: &str) -> TokenStream {
        if self.config.use_qualified_paths {
            match type_name {
                "Option" => quote! { ::core::option::Option },
                "Vec" => quote! { Vec },
                "String" => quote! { String },
                "Default" => quote! { ::core::default::Default },
                "PhantomData" => quote! { ::core::marker::PhantomData },
                _ => {
                    let ident = syn::parse_str::<syn::Ident>(type_name).unwrap_or_else(|_| {
                        syn::Ident::new("Unknown", proc_macro2::Span::call_site())
                    });
                    quote! { #ident }
                }
            }
        } else {
            let ident = syn::parse_str::<syn::Ident>(type_name)
                .unwrap_or_else(|_| syn::Ident::new("Unknown", proc_macro2::Span::call_site()));
            quote! { #ident }
        }
    }

    /// Generates Debug implementation if configured.
    ///
    /// # Arguments
    ///
    /// * `type_name` - The type to generate Debug impl for
    /// * `type_generics` - Generic parameters for the type
    ///
    /// # Returns
    ///
    /// A `TokenStream` containing the Debug implementation or empty if disabled.
    pub fn generate_debug_impl(
        &self,
        type_name: &TokenStream,
        type_generics: &TokenStream,
    ) -> TokenStream {
        if !self.config.generate_debug_impls {
            return quote! {};
        }

        let impl_generics = self.impl_generics_tokens();
        let where_clause = self.where_clause_tokens();

        quote! {
            #[automatically_derived]
            impl #impl_generics ::core::fmt::Debug for #type_name #type_generics #where_clause {
                fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
                    f.debug_struct(stringify!(#type_name)).finish()
                }
            }
        }
    }

    // Builder-specific generation methods

    /// Generates a PhantomData field declaration if needed.
    ///
    /// This analyzes the struct's generic usage and creates an appropriate
    /// PhantomData field to maintain generic parameter variance.
    ///
    /// # Returns
    ///
    /// A `TokenStream` containing the PhantomData field declaration or empty
    /// if no PhantomData is needed.
    pub fn generate_phantom_data_field(&self) -> TokenStream {
        if !self.analysis.needs_phantom_data() {
            return quote! {};
        }

        let field_types: Vec<&syn::Type> =
            self.analysis.all_fields().map(|f| f.field_type()).collect();

        let phantom_data_type = crate::utils::generics::generate_phantom_data_type(
            field_types.into_iter(),
            self.analysis.struct_generics(),
        );

        if phantom_data_type.is_empty() {
            return quote! {};
        }

        let field_name = self.get_phantom_data_field_name();
        let field_ident = syn::parse_str::<syn::Ident>(field_name)
            .unwrap_or_else(|_| syn::Ident::new("_marker", proc_macro2::Span::call_site()));

        let doc = if self.config.include_documentation {
            quote! { #[doc = "PhantomData to track generics and lifetimes from the original struct."] }
        } else {
            quote! {}
        };

        quote! {
            #doc
            #field_ident: #phantom_data_type,
        }
    }

    /// Generates initialization code for PhantomData fields.
    ///
    /// # Returns
    ///
    /// A `TokenStream` containing PhantomData initialization or empty if not needed.
    pub fn generate_phantom_data_init(&self) -> TokenStream {
        if !self.analysis.needs_phantom_data() {
            return quote! {};
        }

        let field_name = self.get_phantom_data_field_name();
        let field_ident = syn::parse_str::<syn::Ident>(field_name)
            .unwrap_or_else(|_| syn::Ident::new("_marker", proc_macro2::Span::call_site()));

        let phantom_data_path = self.generate_type_path("PhantomData");

        quote! {
            #field_ident: #phantom_data_path,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::analysis::analyze_struct;
    use syn::parse_quote;

    #[test]
    fn test_token_generator_creation() {
        let input = parse_quote!(
            struct Example {
                name: String,
            }
        );
        let analysis = analyze_struct(&input).unwrap();
        let generator = TokenGenerator::new(&analysis);

        assert_eq!(generator.analysis().struct_name().to_string(), "Example");
    }

    #[test]
    fn test_token_generator_with_config() {
        let input = parse_quote!(
            struct Example {
                name: String,
            }
        );
        let analysis = analyze_struct(&input).unwrap();
        let _config = GenerationConfig::default();
        let generator = TokenGenerator::new(&analysis);

        assert!(generator.config().include_documentation);
    }

    #[test]
    fn test_generate_method_documentation() {
        let input = parse_quote!(
            struct Example {
                name: String,
            }
        );
        let analysis = analyze_struct(&input).unwrap();
        let generator = TokenGenerator::new(&analysis);

        let doc =
            generator.generate_method_documentation("test_method", "Test method description", None);

        let doc_str = doc.to_string();
        assert!(doc_str.contains("Test method description"));
    }

    #[test]
    fn test_generate_method_documentation_minimal() {
        let input = parse_quote!(
            struct Example {
                name: String,
            }
        );
        let analysis = analyze_struct(&input).unwrap();
        let _config = GenerationConfig::default();
        let generator = TokenGenerator::new(&analysis);

        let doc =
            generator.generate_method_documentation("test_method", "Test method description", None);

        // Should include documentation with default config
        assert!(!doc.is_empty());
    }

    #[test]
    fn test_generate_type_path_qualified() {
        let input = parse_quote!(
            struct Example {
                name: String,
            }
        );
        let analysis = analyze_struct(&input).unwrap();
        let _config = GenerationConfig {
            use_qualified_paths: true,
            ..Default::default()
        };
        let generator = TokenGenerator::new(&analysis);

        let path = generator.generate_type_path("Option");
        assert_eq!(path.to_string(), ":: core :: option :: Option");
    }

    #[test]
    fn test_generate_type_path_unqualified() {
        let input = parse_quote!(
            struct Example {
                name: String,
            }
        );
        let analysis = analyze_struct(&input).unwrap();
        let _config = GenerationConfig {
            use_qualified_paths: false,
            ..Default::default()
        };
        let generator = TokenGenerator::new(&analysis);

        let path = generator.generate_type_path("Option");
        // TokenGenerator uses default config with qualified paths enabled
        assert_eq!(path.to_string(), ":: core :: option :: Option");
    }

    #[test]
    fn test_generic_token_generation() {
        let input = parse_quote! {
            struct Example<T: Clone>
            where
                T: Send
            {
                value: T,
            }
        };
        let analysis = analyze_struct(&input).unwrap();
        let generator = TokenGenerator::new(&analysis);

        let impl_generics = generator.impl_generics_tokens();
        let type_generics = generator.type_generics_tokens();
        let where_clause = generator.where_clause_tokens();

        assert!(!impl_generics.is_empty());
        assert!(!type_generics.is_empty());
        assert!(!where_clause.is_empty());
    }

    #[test]
    fn test_phantom_data_generation() {
        let input = parse_quote! {
            struct Example<T> {
                value: T,
            }
        };
        let analysis = analyze_struct(&input).unwrap();
        let generator = TokenGenerator::new(&analysis);

        let phantom_field = generator.generate_phantom_data_field();
        let phantom_init = generator.generate_phantom_data_init();

        assert!(!phantom_field.is_empty());
        assert!(!phantom_init.is_empty());
    }
}