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
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
//! Type-State Builder Pattern Implementation
//!
//! A derive macro that generates compile-time safe builders using the type-state pattern.
//! It prevents incomplete object construction by making missing required fields a
//! compile-time error rather than a runtime failure.
//!
//! For complete documentation, installation instructions, and guides, see the
//! [README](https://github.com/welf/type-state-builder#readme).
//!
//! # Design Philosophy
//!
//! This crate was designed with AI-assisted development in mind. Two principles
//! guided its design:
//!
//! ## Compiler-Enforced Correctness
//!
//! In AI-assisted development, code generation happens rapidly. By encoding field
//! requirements in the type system, errors are caught immediately by the compiler
//! rather than manifesting as runtime failures. If the code compiles, the builder
//! is correctly configured.
//!
//! ## Actionable Error Messages
//!
//! Instead of using generic type parameters to track field states (which produce
//! cryptic error messages), this crate generates named structs for each state:
//!
//! ```text
//! UserBuilder_HasName_MissingEmail    // Name set, email missing
//! UserBuilder_HasName_HasEmail        // Both set - build() available
//! ```
//!
//! When an error occurs, the type name immediately indicates which fields are missing.
//! This is particularly valuable for AI assistants that can parse and act on the error.
//!
//! ## Trade-offs
//!
//! This approach generates more structs than type-parameter-based solutions, slightly
//! increasing compile time. However, the improved error message clarity is worth this
//! cost. There is no runtime cost due to Rust's zero-cost abstractions.
//!
//! # Compatibility
//!
//! - **no_std**: Fully compatible. Generated code uses only `core` types.
//! - **MSRV**: Rust 1.70.0 or later.
//!
//! # Overview
//!
//! The macro automatically selects between two builder patterns:
//!
//! - **Type-State Builder**: For structs with required fields, providing compile-time
//!   safety that prevents calling `build()` until all required fields are set
//! - **Regular Builder**: For structs with only optional fields, providing a simple
//!   builder with immediate `build()` availability
//!
//! # Quick Start
//!
//! Add the derive macro to your struct and mark required fields:
//!
//! ```
//! use type_state_builder::TypeStateBuilder;
//!
//! #[derive(TypeStateBuilder)]
//! #[builder(impl_into)]   // Setters arguments are now `impl Into<FieldType>`
//! struct User {
//!     #[builder(required)]
//!     name: String,
//!
//!     #[builder(required)]
//!     email: String,
//!
//!     #[builder(default = Some(30))] // Default value for age
//!     age: Option<u32>,
//!
//!     #[builder(setter_prefix = "is_")] // The setter is now named `is_active`
//!     active: bool, // Will use Default::default() if not set
//! }
//!
//! // Usage - this enforces that name and email are set
//! let user = User::builder()
//!     .name("Alice")              // `impl_into` allows to pass any type that can be converted into String
//!     .email("alice@example.com") // `impl_into` allows to pass any type that can be converted into String
//!     // age is not set and defaults to Some(30)
//!     // active is not set and defaults to false (Default::default())
//!     .build(); // The `build()` method is available since all required fields are set

//!
//! assert_eq!(user.name, "Alice".to_string());
//! assert_eq!(user.email, "alice@example.com".to_string());
//! assert_eq!(user.age, Some(30));
//! assert_eq!(user.active, false);
//! ```
//!
//! # Supported Attributes
//!
//! ## Struct-level Attributes
//!
//! - `#[builder(build_method = "method_name")]` - Custom build method name
//! - `#[builder(setter_prefix = "prefix_")]` - Prefix for all setter method names
//! - `#[builder(impl_into)]` - Generate setters with `impl Into<FieldType>` parameters
//! - `#[builder(const)]` - Generate `const fn` builder methods for compile-time construction
//!
//! ## Field-level Attributes
//!
//! - `#[builder(required)]` - Mark field as required
//! - `#[builder(setter_name = "name")]` - Custom setter method name
//! - `#[builder(setter_prefix = "prefix_")]` - Custom prefix for setter method name
//! - `#[builder(default = expression)]` - Custom default value
//! - `#[builder(skip_setter)]` - Don't generate setter (requires default)
//! - `#[builder(impl_into)]` - Generate setter with `impl Into<FieldType>` parameter
//! - `#[builder(impl_into = false)]` - Override struct-level `impl_into` for this field
//! - `#[builder(converter = |param: InputType| -> FieldType { expression })` - Custom conversion logic for setter input
//! - `#[builder(builder_method)]` - Use this field's setter as the builder entry point (replaces `builder()`)
//!
//! # Advanced Examples
//!
//! ## Custom Defaults and Setter Names
//!
//! ```
//! use type_state_builder::TypeStateBuilder;
//!
//! #[derive(TypeStateBuilder)]
//! #[builder(build_method = "create")]
//! struct Document {
//!     #[builder(required)]
//!     title: String,
//!
//!     #[builder(required, setter_name = "set_content")]
//!     content: String,
//!
//!     #[builder(default = 42)]
//!     page_count: u32,
//!
//!     #[builder(default = String::from("draft"), skip_setter)]
//!     status: String,
//! }
//!
//! let doc = Document::builder()
//!     .title("My Document".to_string())
//!     .set_content("Document content here".to_string())
//!     .create(); // Custom build method name
//! ```
//!
//! ## Generic Types and Lifetimes
//!
//! ```
//! use type_state_builder::TypeStateBuilder;
//!
//! #[derive(TypeStateBuilder)]
//! struct Container<T: Clone>
//! where
//!     T: Send
//! {
//!     #[builder(required)]
//!     value: T,
//!
//!     #[builder(required)]
//!     name: String,
//!
//!     tags: Vec<String>,
//! }
//!
//! let container = Container::builder()
//!     .value(42)
//!     .name("test".to_string())
//!     .tags(vec!["tag1".to_string()])
//!     .build();
//! ```
//!
//! ## Setter Prefix Examples
//!
//! ```
//! use type_state_builder::TypeStateBuilder;
//!
//! // Struct-level setter prefix applies to all fields
//! #[derive(TypeStateBuilder)]
//! #[builder(setter_prefix = "with_")]
//! struct Config {
//!     #[builder(required)]
//!     host: String,
//!
//!     #[builder(required)]
//!     port: u16,
//!
//!     timeout: Option<u32>,
//! }
//!
//! let config = Config::builder()
//!     .with_host("localhost".to_string())
//!     .with_port(8080)
//!     .with_timeout(Some(30))
//!     .build();
//! ```
//!
//! ```
//! use type_state_builder::TypeStateBuilder;
//!
//! // Field-level setter prefix overrides struct-level prefix
//! #[derive(TypeStateBuilder)]
//! #[builder(setter_prefix = "with_")]
//! struct Database {
//!     #[builder(required)]
//!     connection_string: String,
//!
//!     #[builder(required, setter_prefix = "set_")]
//!     credentials: String,
//!
//!     #[builder(setter_name = "timeout_seconds")]
//!     timeout: Option<u32>,
//! }
//!
//! let db = Database::builder()
//!     .with_connection_string("postgresql://...".to_string())
//!     .set_credentials("user:pass".to_string())
//!     .with_timeout_seconds(Some(60))
//!     .build();
//! ```
//!
//! ## Ergonomic Conversions with `impl_into`
//!
//! The `impl_into` attribute generates setter methods that accept `impl Into<FieldType>`
//! parameters, allowing for more ergonomic API usage by automatically converting
//! compatible types.
//!
//! ```
//! use type_state_builder::TypeStateBuilder;
//!
//! // Struct-level impl_into applies to all setters
//! #[derive(TypeStateBuilder)]
//! #[builder(impl_into)]
//! struct ApiClient {
//!     #[builder(required)]
//!     base_url: String,
//!
//!     #[builder(required)]
//!     api_key: String,
//!
//!     timeout: Option<u32>,
//!     user_agent: String, // Uses Default::default()
//! }
//!
//! // Can now use &str directly instead of String::from() or .to_string()
//! let client = ApiClient::builder()
//!     .base_url("https://api.example.com")    // &str -> String
//!     .api_key("secret-key")                   // &str -> String
//!     .timeout(Some(30))
//!     .user_agent("MyApp/1.0")                 // &str -> String
//!     .build();
//! ```
//!
//! ```
//! use type_state_builder::TypeStateBuilder;
//!
//! // Field-level control with precedence rules
//! #[derive(TypeStateBuilder)]
//! #[builder(impl_into)]  // Default for all fields
//! struct Document {
//!     #[builder(required)]
//!     title: String,  // Inherits impl_into = true
//!
//!     #[builder(required, impl_into = false)]
//!     content: String,  // Override: requires String directly
//!
//!     #[builder(impl_into = true)]
//!     category: Option<String>,  // Explicit impl_into = true
//!
//!     #[builder(impl_into = false)]
//!     tags: Vec<String>,  // Override: requires Vec<String> directly
//! }
//!
//! let doc = Document::builder()
//!     .title("My Document")                // &str -> String (inherited)
//!     .content("Content".to_string())      // Must use String (override)
//!     .category(Some("tech".to_string()))  // impl Into for Option<String>
//!     .tags(vec!["rust".to_string()])      // Must use Vec<String> (override)
//!     .build();
//! ```
//!
//! **Note**: `impl_into` is incompatible with `skip_setter` since skipped fields
//! don't have setter methods generated.
//!
//! ### Complete `impl_into` Example
//!
//! ```
//! use type_state_builder::TypeStateBuilder;
//! use std::path::PathBuf;
//!
//! // Demonstrate both struct-level and field-level impl_into usage
//! #[derive(TypeStateBuilder)]
//! #[builder(impl_into)]  // Struct-level default: enable for all fields
//! struct CompleteExample {
//!     #[builder(required)]
//!     name: String,                        // Inherits: accepts impl Into<String>
//!
//!     #[builder(required, impl_into = false)]
//!     id: String,                          // Override: requires String directly
//!
//!     #[builder(impl_into = true)]
//!     description: Option<String>,         // Explicit: accepts impl Into<String>
//!
//!     #[builder(default = PathBuf::from("/tmp"))]
//!     work_dir: PathBuf,                   // Inherits: accepts impl Into<PathBuf>
//!
//!     #[builder(impl_into = false, default = Vec::new())]
//!     tags: Vec<String>,                   // Override: requires Vec<String>
//! }
//!
//! // Usage demonstrating the different setter behaviors
//! let example = CompleteExample::builder()
//!     .name("Alice")                       // &str -> String (inherited impl_into)
//!     .id("user_123".to_string())          // Must use String (override = false)
//!     .description(Some("Engineer".to_string()))  // Option<String> required
//!     .work_dir("/home/alice")             // &str -> PathBuf (inherited impl_into)
//!     .tags(vec!["rust".to_string()])      // Must use Vec<String> (override = false)
//!     .build();
//!
//! assert_eq!(example.name, "Alice");
//! assert_eq!(example.id, "user_123");
//! assert_eq!(example.description, Some("Engineer".to_string()));
//! assert_eq!(example.work_dir, PathBuf::from("/home/alice"));
//! assert_eq!(example.tags, vec!["rust"]);
//! ```
//!
//! ## Custom Conversions with `converter`
//!
//! The `converter` attribute allows you to specify custom conversion logic for field setters,
//! enabling more powerful transformations than `impl_into` can provide. Use closure syntax
//! to define the conversion function with explicit parameter types.
//!
//! ```
//! use type_state_builder::TypeStateBuilder;
//!
//! #[derive(TypeStateBuilder)]
//! struct User {
//!     #[builder(required, impl_into)]
//!     name: String,
//!
//!     // Normalize email to lowercase and trim whitespace
//!     #[builder(required, converter = |email: &str| email.trim().to_lowercase())]
//!     email: String,
//!
//!     // Parse comma-separated tags into Vec<String>
//!     #[builder(converter = |tags: &str| tags.split(',').map(|s| s.trim().to_string()).collect())]
//!     interests: Vec<String>,
//!
//!     // Parse age from string with fallback
//!     #[builder(converter = |age: &str| age.parse().unwrap_or(0))]
//!     age: u32,
//! }
//!
//! let user = User::builder()
//!     .name("Alice")
//!     .email("  ALICE@EXAMPLE.COM  ")  // Will be normalized to "alice@example.com"
//!     .interests("rust, programming, web")  // Parsed to Vec<String>
//!     .age("25")  // Parsed from string to u32
//!     .build();
//!
//! assert_eq!(user.email, "alice@example.com");
//! assert_eq!(user.interests, vec!["rust", "programming", "web"]);
//! assert_eq!(user.age, 25);
//! ```
//!
//! ### Complex Converter Examples
//!
//! ```
//! use type_state_builder::TypeStateBuilder;
//! use std::collections::HashMap;
//!
//! #[derive(TypeStateBuilder)]
//! struct Config {
//!     // Convert environment-style boolean strings
//!     #[builder(converter = |enabled: &str| {
//!         matches!(enabled.to_lowercase().as_str(), "true" | "1" | "yes" | "on")
//!     })]
//!     debug_enabled: bool,
//!
//!     // Parse key=value pairs into HashMap
//!     #[builder(converter = |pairs: &str| {
//!         pairs.split(',')
//!              .filter_map(|pair| {
//!                  let mut split = pair.split('=');
//!                  Some((split.next()?.trim().to_string(),
//!                       split.next()?.trim().to_string()))
//!              })
//!              .collect()
//!     })]
//!     env_vars: HashMap<String, String>,
//!
//!     // Transform slice to owned Vec
//!     #[builder(converter = |hosts: &[&str]| {
//!         hosts.iter().map(|s| s.to_string()).collect()
//!     })]
//!     allowed_hosts: Vec<String>,
//! }
//!
//! let config = Config::builder()
//!     .debug_enabled("true")
//!     .env_vars("LOG_LEVEL=debug,PORT=8080")
//!     .allowed_hosts(&["localhost", "127.0.0.1"])
//!     .build();
//!
//! assert_eq!(config.debug_enabled, true);
//! assert_eq!(config.env_vars.get("LOG_LEVEL"), Some(&"debug".to_string()));
//! assert_eq!(config.allowed_hosts, vec!["localhost", "127.0.0.1"]);
//! ```
//!
//! ### Converter with Generics
//!
//! ```
//! use type_state_builder::TypeStateBuilder;
//!
//! #[derive(TypeStateBuilder)]
//! struct Container<T: Clone + Default> {
//!     #[builder(required, impl_into)]
//!     name: String,
//!
//!     // Converter works with generic fields too
//!     #[builder(converter = |items: &[T]| items.into_iter().map(|item| item.clone()).collect())]
//!     data: Vec<T>,
//! }
//!
//! // Usage with concrete type
//! let container = Container::builder()
//!     .name("numbers")        // Convert &str to String thanks to `impl_into`
//!     .data(&[1, 2, 3, 4, 5]) // Convert &[T] to Vec<T> thanks to `converter`
//!     .build();               // Available only when all required fields are set
//!
//! assert_eq!(container.data, vec![1, 2, 3, 4, 5]);
//! ```
//!
//! ### Converter vs impl_into Comparison
//!
//! | Feature | `impl_into` | `converter` |
//! |---------|-------------|-------------|
//! | **Type conversions** | Only `Into` trait | Any custom logic |
//! | **Parsing strings** | Limited | Full support |
//! | **Data validation** | No | Custom validation |
//! | **Complex transformations** | No | Full support |
//! | **Multiple input formats** | Into only | Any input type |
//! | **Performance** | Zero-cost | Depends on logic |
//! | **Syntax** | Attribute flag | Closure expression |
//!
//! **When to use `converter`:**
//! - Ergonomic setter generation for `Option<String>` fields
//! - Parsing structured data from strings
//! - Normalizing or validating input data
//! - Complex data transformations
//! - Converting between incompatible types
//! - Custom business logic in setters
//!
//! **Note**: `converter` is incompatible with `skip_setter` and `impl_into` since
//! they represent different approaches to setter generation.
//!
//! ## Optional-Only Structs (Regular Builder)
//!
//! ```
//! use type_state_builder::TypeStateBuilder;
//!
//! // No required fields = regular builder pattern
//! #[derive(TypeStateBuilder)]
//! struct Settings {
//!     debug: bool,
//!     max_connections: Option<u32>,
//!
//!     #[builder(default = "default.log".to_string())]
//!     log_file: String,
//!
//!     #[builder(skip_setter, default = 42)]
//!     magic_number: i32,
//! }
//!
//! // Can call build() immediately since no required fields
//! let settings = Settings::builder()
//!     .debug(true)
//!     .max_connections(Some(100))
//!     .build();
//! ```
//!
//! ## Const Builders
//!
//! The `#[builder(const)]` attribute generates `const fn` builder methods, enabling
//! compile-time constant construction. This is useful for embedded systems, static
//! configuration, and other scenarios where values must be known at compile time.
//!
//! ```
//! use type_state_builder::TypeStateBuilder;
//!
//! #[derive(TypeStateBuilder, Debug, PartialEq)]
//! #[builder(const)]
//! struct Config {
//!     #[builder(required)]
//!     name: &'static str,
//!
//!     #[builder(required)]
//!     version: u32,
//!
//!     #[builder(default = 8080)]
//!     port: u16,
//! }
//!
//! // Compile-time constant construction
//! const APP_CONFIG: Config = Config::builder()
//!     .name("my-app")
//!     .version(1)
//!     .port(3000)
//!     .build();
//!
//! // Also works in static context
//! static DEFAULT_CONFIG: Config = Config::builder()
//!     .name("default")
//!     .version(0)
//!     .build();
//!
//! // And in const fn
//! const fn make_config(name: &'static str) -> Config {
//!     Config::builder()
//!         .name(name)
//!         .version(1)
//!         .build()
//! }
//!
//! const CUSTOM: Config = make_config("custom");
//! ```
//!
//! ### Const Builder Requirements
//!
//! When using `#[builder(const)]`, there are some restrictions:
//!
//! - **Explicit defaults required**: Optional fields must use `#[builder(default = expr)]`
//!   because `Default::default()` cannot be called in const context
//! - **No `impl_into`**: The `impl_into` attribute is incompatible with const builders
//!   because trait bounds are not supported in const fn
//! - **Const-compatible types**: Field types must support const construction (e.g.,
//!   `&'static str` instead of `String`, arrays instead of `Vec`)
//!
//! ### Const Builders with Converters
//!
//! Closure converters work with const builders. The macro automatically generates
//! a `const fn` from the closure body:
//!
//! ```
//! use type_state_builder::TypeStateBuilder;
//!
//! #[derive(TypeStateBuilder, Debug, PartialEq)]
//! #[builder(const)]
//! struct Data {
//!     // Converter closure is transformed into a const fn
//!     #[builder(required, converter = |s: &'static str| s.len())]
//!     name_length: usize,
//!
//!     #[builder(default = 0, converter = |n: i32| n * 2)]
//!     doubled: i32,
//! }
//!
//! const DATA: Data = Data::builder()
//!     .name_length("hello")  // Converted to 5
//!     .doubled(21)           // Converted to 42
//!     .build();
//!
//! assert_eq!(DATA.name_length, 5);
//! assert_eq!(DATA.doubled, 42);
//! ```
//!
//! **Note**: The closure body must be const-evaluable. If it contains non-const
//! operations (like heap allocation or trait method calls), the Rust compiler
//! will produce an error.
//!
//! ## Builder Method Entry Point
//!
//! The `#[builder(builder_method)]` attribute makes a required field's setter the
//! entry point to the builder, replacing the `builder()` method. This provides a
//! more ergonomic API when one field is the natural starting point.
//!
//! ```
//! use type_state_builder::TypeStateBuilder;
//!
//! #[derive(TypeStateBuilder, Debug, PartialEq)]
//! struct User {
//!     #[builder(required, builder_method)]
//!     id: u64,
//!     #[builder(required, impl_into)]
//!     name: String,
//! }
//!
//! // Instead of User::builder().id(1).name("Alice").build()
//! let user = User::id(1).name("Alice").build();
//!
//! assert_eq!(user.id, 1);
//! assert_eq!(user.name, "Alice".to_string());
//! ```
//!
//! ### Requirements
//!
//! - Only one field per struct can have `builder_method`
//! - The field must be required (not optional)
//! - Cannot be combined with `skip_setter`
//!
//! ### With Const Builders
//!
//! The `builder_method` attribute works with const builders:
//!
//! ```
//! use type_state_builder::TypeStateBuilder;
//!
//! #[derive(TypeStateBuilder, Debug, PartialEq)]
//! #[builder(const)]
//! struct Config {
//!     #[builder(required, builder_method)]
//!     name: &'static str,
//!     #[builder(default = 0)]
//!     version: u32,
//! }
//!
//! const APP: Config = Config::name("myapp").version(1).build();
//! ```
//!
//! # Error Prevention
//!
//! The macro prevents common mistakes at compile time:
//!
//! ```compile_fail
//! use type_state_builder::TypeStateBuilder;
//!
//! #[derive(TypeStateBuilder)]
//! struct User {
//!     #[builder(required)]
//!     name: String,
//! }
//!
//! let user = User::builder().build(); // ERROR: required field not set
//! ```
//!
//! ```compile_fail
//! use type_state_builder::TypeStateBuilder;
//!
//! #[derive(TypeStateBuilder)]
//! struct BadConfig {
//!     #[builder(required, default = test)]  // ERROR: Invalid combination
//!     name: String,
//! }
//! ```
//!
//! # Invalid Attribute Combinations
//!
//! Several attribute combinations are invalid and will produce compile-time errors
//! with helpful error messages:
//!
//! ## skip_setter + setter_name
//!
//! You can't name a setter method that doesn't exist:
//!
//! ```compile_fail
//! use type_state_builder::TypeStateBuilder;
//!
//! #[derive(TypeStateBuilder)]
//! struct InvalidSetterName {
//!     #[builder(skip_setter, setter_name = "custom_name")]  // ERROR: Conflicting attributes
//!     field: String,
//! }
//! ```
//!
//! ## skip_setter + setter_prefix
//!
//! You can't apply prefixes to non-existent setter methods:
//!
//! ```compile_fail
//! use type_state_builder::TypeStateBuilder;
//!
//! #[derive(TypeStateBuilder)]
//! struct InvalidSetterPrefix {
//!     #[builder(skip_setter, setter_prefix = "with_")]  // ERROR: Conflicting attributes
//!     field: String,
//! }
//! ```
//!
//! ## skip_setter + impl_into
//!
//! Skipped setters can't have parameter conversion rules:
//!
//! ```compile_fail
//! use type_state_builder::TypeStateBuilder;
//!
//! #[derive(TypeStateBuilder)]
//! struct InvalidImplInto {
//!     #[builder(skip_setter, impl_into = true)]  // ERROR: Conflicting attributes
//!     field: String,
//! }
//! ```
//!
//! ## skip_setter + converter
//!
//! Skipped setters can't have custom conversion logic:
//!
//! ```compile_fail
//! use type_state_builder::TypeStateBuilder;
//!
//! #[derive(TypeStateBuilder)]
//! struct InvalidConverter {
//!     #[builder(skip_setter, converter = |x: String| x)]  // ERROR: Conflicting attributes
//!     field: String,
//! }
//! ```
//!
//! ## converter + impl_into
//!
//! Custom converters and `impl_into` are different approaches to parameter handling:
//!
//! ```compile_fail
//! use type_state_builder::TypeStateBuilder;
//!
//! #[derive(TypeStateBuilder)]
//! struct InvalidConverterImplInto {
//!     #[builder(converter = |x: String| x, impl_into = true)]  // ERROR: Conflicting attributes
//!     field: String,
//! }
//! ```
//!
//! ## skip_setter + required
//!
//! Required fields must have setter methods:
//!
//! ```compile_fail
//! use type_state_builder::TypeStateBuilder;
//!
//! #[derive(TypeStateBuilder)]
//! struct InvalidRequired {
//!     #[builder(skip_setter, required)]  // ERROR: Conflicting attributes
//!     field: String,
//! }
//! ```
//!
//! # Module Organization
//!
//! The crate is organized into several modules that handle different aspects
//! of the builder generation process. Most users will only interact with the
//! [`TypeStateBuilder`] derive macro.
//!
//! For complete documentation, examples, and guides, see the
//! [README](https://github.com/welf/type-state-builder#readme).

use proc_macro::TokenStream;
use syn::{parse_macro_input, DeriveInput};

// Internal modules - not exported due to proc-macro restrictions
mod analysis;
mod attributes;
mod generation;
mod utils;
mod validation;

/// Derives a type-safe builder for a struct with compile-time validation of required fields.
///
/// This macro automatically generates an appropriate builder pattern based on the struct
/// configuration:
/// - **Type-State Builder** for structs with required fields
/// - **Regular Builder** for structs with only optional fields
///
/// # Basic Usage
///
/// ```
/// use type_state_builder::TypeStateBuilder;
///
/// #[derive(TypeStateBuilder)]
/// struct Person {
///     #[builder(required)]
///     name: String,
///     age: Option<u32>,
/// }
///
/// let person = Person::builder()
///     .name("Alice".to_string())
///     .build();
/// ```
///
/// # Attribute Reference
///
/// ## Struct Attributes
///
/// - `#[builder(build_method = "name")]` - Custom build method name (default: "build")
/// - `#[builder(setter_prefix = "prefix_")]` - Prefix for all setter method names
///
/// ## Field Attributes
///
/// - `#[builder(required)]` - Field must be set before build() (creates type-state builder)
/// - `#[builder(setter_name = "name")]` - Custom setter method name
/// - `#[builder(setter_prefix = "prefix_")]` - Custom prefix for this field's setter (overrides struct-level)
/// - `#[builder(default = expr)]` - Custom default value (must be valid Rust expression)
/// - `#[builder(skip_setter)]` - Don't generate setter method (requires default value)
///
/// # Generated Methods
///
/// The macro generates:
/// - `YourStruct::builder()` - Creates a new builder instance
/// - `.field_name(value)` - Setter methods for each field (unless skipped)
/// - `.build()` - Constructs the final instance (or custom name from `build_method`)
///
/// # Compile-Time Safety
///
/// The type-state builder (used when there are required fields) prevents:
/// - Calling `build()` before setting required fields
/// - Setting the same required field multiple times
/// - Invalid attribute combinations
///
/// # Error Messages
///
/// The macro provides clear error messages for common mistakes:
/// - Missing required fields at build time
/// - Invalid attribute combinations
/// - Generic parameter mismatches
/// - Syntax errors in default values
///
/// # Examples
///
/// ```
/// use type_state_builder::TypeStateBuilder;
///
/// #[derive(TypeStateBuilder)]
/// struct User {
///     #[builder(required)]
///     name: String,
///     age: Option<u32>,
/// }
///
/// let user = User::builder()
///     .name("Alice".to_string())
///     .build();
/// ```
#[proc_macro_derive(TypeStateBuilder, attributes(builder))]
pub fn derive_type_state_builder(input: TokenStream) -> TokenStream {
    let input = parse_macro_input!(input as DeriveInput);

    match generate_builder_implementation(&input) {
        Ok(tokens) => tokens.into(),
        Err(error) => error.to_compile_error().into(),
    }
}

/// Generates the complete builder implementation for a struct.
///
/// This is the main implementation function that coordinates the analysis,
/// validation, and generation process.
///
/// # Arguments
///
/// * `input` - The parsed derive input from the struct definition
///
/// # Returns
///
/// A `syn::Result<proc_macro2::TokenStream>` containing the complete builder
/// implementation or detailed error information.
///
/// # Process
///
/// 1. **Analysis** - Parse and analyze the struct definition
/// 2. **Validation** - Ensure the configuration is valid
/// 3. **Generation** - Create the appropriate builder code
/// 4. **Assembly** - Combine all components into the final output
///
/// # Error Handling
///
/// Errors are returned with detailed information about:
/// - What went wrong during analysis or generation
/// - How to fix configuration issues
/// - Examples of correct usage
fn generate_builder_implementation(input: &DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
    // Step 1: Analyze the struct definition
    let analysis = analysis::analyze_struct(input)?;

    // Step 2: Validate the analysis for builder generation
    analysis.validate_for_generation()?;

    // Step 3: Generate the appropriate builder implementation
    generation::generate_builder(&analysis)
}

// Internal types for testing - not exported due to proc-macro restrictions

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

    #[test]
    fn test_derive_macro_with_required_fields() {
        let input: DeriveInput = parse_quote! {
            struct Example {
                #[builder(required)]
                name: String,
                age: Option<u32>,
            }
        };

        let result = generate_builder_implementation(&input);
        assert!(result.is_ok());

        let tokens = result.unwrap();
        let code = tokens.to_string();

        // Should contain builder method
        assert!(code.contains("builder"));
        // Should contain setter for required field
        assert!(code.contains("name"));
        // Should contain build method
        assert!(code.contains("build"));
    }

    #[test]
    fn test_derive_macro_with_optional_only() {
        let input: DeriveInput = parse_quote! {
            struct Example {
                name: Option<String>,
                age: u32,
            }
        };

        let result = generate_builder_implementation(&input);
        assert!(result.is_ok());

        let tokens = result.unwrap();
        let code = tokens.to_string();

        // Should generate regular builder for optional-only struct
        assert!(code.contains("builder"));
        assert!(code.contains("build"));
    }

    #[test]
    fn test_derive_macro_with_custom_attributes() {
        let input: DeriveInput = parse_quote! {
            #[builder(build_method = "create")]
            struct Example {
                #[builder(required, setter_name = "set_name")]
                name: String,

                #[builder(default = 42)]
                count: i32,
            }
        };

        let result = generate_builder_implementation(&input);
        assert!(result.is_ok());

        let tokens = result.unwrap();
        let code = tokens.to_string();

        // Should respect custom build method name
        assert!(code.contains("create"));
        // Should respect custom setter name
        assert!(code.contains("set_name"));
    }

    #[test]
    fn test_derive_macro_with_generics() {
        let input: DeriveInput = parse_quote! {
            struct Example<T: Clone> {
                #[builder(required)]
                value: T,
                name: String,
            }
        };

        let result = generate_builder_implementation(&input);
        assert!(result.is_ok());

        let tokens = result.unwrap();
        let code = tokens.to_string();

        // Should handle generics properly
        assert!(code.contains("<"));
        assert!(code.contains("T"));
    }

    #[test]
    fn test_derive_macro_with_undeclared_generic() {
        // This test verifies that undeclared generics are allowed through our validation
        // and the Rust compiler will catch the error later
        let input: DeriveInput = parse_quote! {
            struct Example {
                value: T,  // T is not declared - Rust compiler will catch this
            }
        };

        let result = generate_builder_implementation(&input);
        // Should succeed in our validation (Rust compiler will catch undeclared generic later)
        assert!(result.is_ok());

        let code = result.unwrap().to_string();
        // Should generate code that includes the undeclared generic
        assert!(code.contains("value"));
    }

    #[test]
    fn test_unsupported_input_types() {
        // Test enum - should fail
        let enum_input: DeriveInput = parse_quote! {
            enum Example {
                A, B
            }
        };
        let result = generate_builder_implementation(&enum_input);
        assert!(result.is_err());

        // Test tuple struct - should fail
        let tuple_input: DeriveInput = parse_quote! {
            struct Example(String, i32);
        };
        let result = generate_builder_implementation(&tuple_input);
        assert!(result.is_err());

        // Test unit struct - should fail
        let unit_input: DeriveInput = parse_quote! {
            struct Example;
        };
        let result = generate_builder_implementation(&unit_input);
        assert!(result.is_err());
    }
}