csharp-rs 0.1.2

Generate C# type definitions from Rust structs and enums
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
1017
1018
1019
1020
1021
1022
// Rust guideline compliant 2026-03-15
//! Generate C# type definitions from Rust structs and enums.
//!
//! `csharp-rs` provides a derive macro that generates C# class, record,
//! or enum definitions from Rust types. It respects `serde` attributes
//! for JSON serialization compatibility, making it ideal for sharing
//! types between a Rust backend and a C#/.NET or Unity client.
//!
//! # Examples
//!
//! ```
//! use csharp_rs::CSharp;
//!
//! #[derive(CSharp)]
//! #[csharp(namespace = "Game.Types")]
//! pub struct PlayerProfile {
//!     pub name: String,
//!     pub level: i32,
//!     pub score: Option<f64>,
//! }
//! ```

use std::collections::{HashMap, HashSet};
use std::path::{Path, PathBuf};

/// Re-export of the derive macro from `csharp-rs-macros`.
#[doc(inline)]
pub use csharp_rs_macros::CSharp;

// ---------------------------------------------------------------------------
// Configuration enums
// ---------------------------------------------------------------------------

/// Which JSON serializer library to target in generated C# code.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq)]
pub enum Serializer {
    /// `System.Text.Json` attributes (default).
    #[default]
    SystemTextJson,
    /// `Newtonsoft.Json` attributes.
    Newtonsoft,
}

/// Target C# language version — controls which syntax features are used.
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub enum CSharpVersion {
    /// Unity C# 9.0 — `sealed class` + `{ get; set; }`, no records or init-only setters.
    Unity,
    /// C# 9.0 (default) — positional records, block-scoped namespaces.
    #[default]
    CSharp9,
    /// C# 10.0 — file-scoped namespaces.
    CSharp10,
    /// C# 11.0 — `required` modifier, native `[JsonPolymorphic]`.
    CSharp11,
    /// C# 12.0 — primary constructors.
    CSharp12,
}

impl std::fmt::Display for CSharpVersion {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let s = match self {
            Self::Unity => "Unity",
            Self::CSharp9 => "9.0",
            Self::CSharp10 => "10.0",
            Self::CSharp11 => "11.0",
            Self::CSharp12 => "12.0",
        };
        f.write_str(s)
    }
}

impl CSharpVersion {
    /// Whether the target supports file-scoped namespaces (C# 10+, not Unity).
    #[must_use]
    pub fn supports_file_scoped_namespace(self) -> bool {
        self >= Self::CSharp10
    }

    /// Whether the target supports the `required` modifier (C# 11+, not Unity).
    #[must_use]
    pub fn supports_required_modifier(self) -> bool {
        self >= Self::CSharp11
    }

    /// Whether the target uses `record` types. Unity uses `class` instead.
    #[must_use]
    pub fn uses_records(self) -> bool {
        self != Self::Unity
    }
}

/// A validated C# namespace (e.g. `"Company.Product"`).
///
/// Each segment must start with an ASCII letter or underscore and contain
/// only ASCII alphanumeric characters or underscores.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct CSharpNamespace(String);

impl CSharpNamespace {
    /// Creates a new validated namespace.
    ///
    /// # Errors
    ///
    /// Returns an error message if the namespace is empty, contains empty
    /// segments, or has segments with invalid characters.
    pub fn new(value: impl Into<String>) -> Result<Self, &'static str> {
        let s = value.into();
        validate_namespace(&s)?;
        Ok(Self(s))
    }
}

impl std::fmt::Display for CSharpNamespace {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.0)
    }
}

impl AsRef<str> for CSharpNamespace {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl PartialEq<&str> for CSharpNamespace {
    fn eq(&self, other: &&str) -> bool {
        self.0 == *other
    }
}

/// Validates a C# namespace string.
fn validate_namespace(ns: &str) -> Result<(), &'static str> {
    if ns.is_empty() {
        return Err("namespace must not be empty");
    }
    for segment in ns.split('.') {
        if segment.is_empty() {
            return Err("namespace must not contain empty segments");
        }
        let mut chars = segment.chars();
        let first = chars.next().expect("segment is non-empty");
        if !first.is_ascii_alphabetic() && first != '_' {
            return Err("each segment must start with a letter or underscore");
        }
        if !chars.all(|c| c.is_ascii_alphanumeric() || c == '_') {
            return Err("segments must contain only letters, digits, or underscores");
        }
    }
    Ok(())
}

// ---------------------------------------------------------------------------
// Runtime configuration
// ---------------------------------------------------------------------------

/// Runtime configuration for C# code generation.
///
/// Controls namespace, serializer library, C# language version, and export
/// directory. Construct with [`Config::default`] and customize with builder
/// methods.
///
/// # Examples
///
/// ```
/// use csharp_rs::{Config, Serializer, CSharpVersion};
///
/// let cfg = Config::default()
///     .with_serializer(Serializer::Newtonsoft)
///     .with_target(CSharpVersion::CSharp11);
/// ```
#[derive(Debug)]
pub struct Config {
    namespace: CSharpNamespace,
    serializer: Serializer,
    target: CSharpVersion,
    export_dir: PathBuf,
}

impl Default for Config {
    fn default() -> Self {
        Self {
            namespace: CSharpNamespace::new("Generated").expect("default namespace is valid"),
            serializer: Serializer::SystemTextJson,
            target: CSharpVersion::CSharp9,
            export_dir: PathBuf::from("./csharp-bindings"),
        }
    }
}

impl Config {
    /// Creates a configuration from environment variables.
    ///
    /// Reads the following environment variables, falling back to defaults
    /// for missing or invalid values:
    ///
    /// - `CSHARP_RS_EXPORT_DIR` — output directory (default: `"./csharp-bindings"`)
    /// - `CSHARP_RS_SERIALIZER` — `"stj"` or `"newtonsoft"` (default: `"stj"`)
    /// - `CSHARP_RS_TARGET` — `"unity"`, `"9"`, `"10"`, `"11"`, `"12"` (default: `"9"`)
    /// - `CSHARP_RS_NAMESPACE` — C# namespace (default: `"Generated"`)
    #[must_use]
    pub fn from_env() -> Self {
        let mut cfg = Self::default();

        if let Ok(dir) = std::env::var("CSHARP_RS_EXPORT_DIR") {
            cfg.export_dir = PathBuf::from(dir);
        }

        if let Ok(serializer) = std::env::var("CSHARP_RS_SERIALIZER") {
            if serializer.as_str() == "newtonsoft" {
                cfg.serializer = Serializer::Newtonsoft;
            }
        }

        if let Ok(target) = std::env::var("CSHARP_RS_TARGET") {
            match target.as_str() {
                "unity" => cfg.target = CSharpVersion::Unity,
                "9" => cfg.target = CSharpVersion::CSharp9,
                "10" => cfg.target = CSharpVersion::CSharp10,
                "11" => cfg.target = CSharpVersion::CSharp11,
                "12" => cfg.target = CSharpVersion::CSharp12,
                _ => {} // unknown value, keep default
            }
        }

        if let Ok(ns) = std::env::var("CSHARP_RS_NAMESPACE") {
            if let Ok(validated) = CSharpNamespace::new(ns) {
                cfg.namespace = validated;
            }
        }

        cfg
    }

    /// Sets the root namespace. Panics if the value is not a valid C#
    /// namespace.
    ///
    /// # Panics
    ///
    /// Panics if `ns` fails [`CSharpNamespace`] validation.
    #[must_use]
    pub fn with_namespace(mut self, ns: &str) -> Self {
        self.namespace =
            CSharpNamespace::new(ns).unwrap_or_else(|e| panic!("invalid namespace \"{ns}\": {e}"));
        self
    }

    /// Sets the root namespace from a pre-validated [`CSharpNamespace`].
    #[must_use]
    pub fn with_validated_namespace(mut self, ns: CSharpNamespace) -> Self {
        self.namespace = ns;
        self
    }

    /// Sets the target serializer library.
    #[must_use]
    pub fn with_serializer(mut self, serializer: Serializer) -> Self {
        self.serializer = serializer;
        self
    }

    /// Sets the target C# language version.
    #[must_use]
    pub fn with_target(mut self, target: CSharpVersion) -> Self {
        self.target = target;
        self
    }

    /// Sets the export directory for generated `.cs` files.
    #[must_use]
    pub fn with_export_dir(mut self, dir: impl Into<PathBuf>) -> Self {
        self.export_dir = dir.into();
        self
    }

    /// Returns the configured namespace as a string slice.
    #[must_use]
    pub fn namespace(&self) -> &str {
        self.namespace.as_ref()
    }

    /// Returns the configured serializer.
    #[must_use]
    pub fn serializer(&self) -> Serializer {
        self.serializer
    }

    /// Returns the configured C# target version.
    #[must_use]
    pub fn target(&self) -> CSharpVersion {
        self.target
    }

    /// Returns the configured export directory.
    #[must_use]
    pub fn export_dir(&self) -> &Path {
        &self.export_dir
    }
}

/// Metadata for a C# field, used by `#[serde(flatten)]` to inline properties.
#[derive(Debug, Clone)]
pub enum CSharpFieldInfo {
    /// A regular property to inline into the parent record.
    Property {
        /// C# property name (`PascalCase`).
        property_name: String,
        /// JSON serialization key.
        json_name: String,
        /// Resolved C# type name (e.g. `"string"`, `"int"`).
        type_name: String,
        /// Whether the field is nullable.
        is_optional: bool,
    },
    /// An extension data container (from flattened `HashMap`).
    ExtensionData {
        /// C# key type name (typically `"string"`).
        key_type_name: String,
        /// C# value type name.
        value_type_name: String,
    },
}

/// Generates a C# type definition as a string.
///
/// Implementors produce a complete `.cs` file content including
/// `using` directives, namespace declaration, and type definition.
pub trait CSharp {
    /// Returns the C# type name (e.g., `"int"`, `"MyStruct"`).
    fn csharp_name(cfg: &Config) -> String;

    /// Returns the complete `.cs` file content for this type, or empty for
    /// primitives / generics.
    fn csharp_definition(cfg: &Config) -> String;

    /// Returns C# type names this type depends on (for transitive export).
    fn dependencies(cfg: &Config) -> Vec<String>;

    /// Returns metadata about this type's fields (used by `#[serde(flatten)]`).
    ///
    /// Only meaningful for struct types. Primitives, generics, and enums
    /// return an empty vec (the default implementation).
    #[must_use]
    fn csharp_fields(_cfg: &Config) -> Vec<CSharpFieldInfo> {
        Vec::new()
    }
}

/// Writes the C# definition of `T` to `path`.
///
/// Creates parent directories if they do not exist.
///
/// # Errors
///
/// Returns an I/O error if the file cannot be written.
pub fn export_to<T: CSharp>(cfg: &Config, path: impl AsRef<Path>) -> std::io::Result<()> {
    let path = path.as_ref();
    if let Some(parent) = path.parent() {
        std::fs::create_dir_all(parent)?;
    }
    std::fs::write(path, T::csharp_definition(cfg))
}

// ---------------------------------------------------------------------------
// Primitive type mappings
// ---------------------------------------------------------------------------

macro_rules! impl_csharp_primitive {
    ($rust_ty:ty, $csharp_name:expr) => {
        impl CSharp for $rust_ty {
            fn csharp_name(_cfg: &Config) -> String {
                String::from($csharp_name)
            }

            fn csharp_definition(_cfg: &Config) -> String {
                // Primitives have no standalone definition.
                String::new()
            }

            fn dependencies(_cfg: &Config) -> Vec<String> {
                Vec::new()
            }
        }
    };
}

impl_csharp_primitive!(String, "string");
impl_csharp_primitive!(bool, "bool");

// Signed integers
impl_csharp_primitive!(i8, "sbyte");
impl_csharp_primitive!(i16, "short");
impl_csharp_primitive!(i32, "int");
impl_csharp_primitive!(i64, "long");
// C# `decimal` (128-bit, 96-bit mantissa) cannot represent all `i128` values.
// `System.Int128` requires .NET 7+ / C# 11+, outside the default C# 9.0 target.
impl_csharp_primitive!(i128, "decimal");

// Unsigned integers
impl_csharp_primitive!(u8, "byte");
impl_csharp_primitive!(u16, "ushort");
impl_csharp_primitive!(u32, "uint");
impl_csharp_primitive!(u64, "ulong");
// C# `decimal` (128-bit, 96-bit mantissa) cannot represent all `u128` values.
// `System.UInt128` requires .NET 7+ / C# 11+, outside the default C# 9.0 target.
impl_csharp_primitive!(u128, "decimal");

// Floating point
impl_csharp_primitive!(f32, "float");
impl_csharp_primitive!(f64, "double");

// ---------------------------------------------------------------------------
// Feature-gated external type impls
// ---------------------------------------------------------------------------

#[cfg(feature = "uuid-impl")]
impl_csharp_primitive!(uuid::Uuid, "Guid");

#[cfg(feature = "chrono-impl")]
mod chrono_impl;

#[cfg(feature = "serde-json-impl")]
mod serde_json_impl;

// ---------------------------------------------------------------------------
// Generic type mappings
// ---------------------------------------------------------------------------

/// Returns the inner type name without a nullable suffix.
///
/// Nullability (`?`) is handled by the derive macro via the `is_optional`
/// flag in codegen, not by the trait. Calling `<Option<i32>>::csharp_name()`
/// returns `"int"`, not `"int?"`.
impl<T: CSharp> CSharp for Option<T> {
    fn csharp_name(cfg: &Config) -> String {
        T::csharp_name(cfg)
    }

    fn csharp_definition(_cfg: &Config) -> String {
        String::new()
    }

    fn dependencies(cfg: &Config) -> Vec<String> {
        vec![T::csharp_name(cfg)]
    }
}

impl<T: CSharp> CSharp for Vec<T> {
    fn csharp_name(cfg: &Config) -> String {
        format!("List<{}>", T::csharp_name(cfg))
    }

    fn csharp_definition(_cfg: &Config) -> String {
        String::new()
    }

    fn dependencies(cfg: &Config) -> Vec<String> {
        vec![T::csharp_name(cfg)]
    }
}

impl<K: CSharp, V: CSharp, S: std::hash::BuildHasher> CSharp for HashMap<K, V, S> {
    fn csharp_name(cfg: &Config) -> String {
        format!(
            "Dictionary<{}, {}>",
            K::csharp_name(cfg),
            V::csharp_name(cfg)
        )
    }

    fn csharp_definition(_cfg: &Config) -> String {
        String::new()
    }

    fn dependencies(cfg: &Config) -> Vec<String> {
        vec![K::csharp_name(cfg), V::csharp_name(cfg)]
    }
}

impl<T: CSharp, S: std::hash::BuildHasher> CSharp for HashSet<T, S> {
    fn csharp_name(cfg: &Config) -> String {
        format!("HashSet<{}>", T::csharp_name(cfg))
    }

    fn csharp_definition(_cfg: &Config) -> String {
        String::new()
    }

    fn dependencies(cfg: &Config) -> Vec<String> {
        vec![T::csharp_name(cfg)]
    }
}

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

    #[test]
    fn serializer_default_is_system_text_json() {
        assert_eq!(Serializer::default(), Serializer::SystemTextJson);
    }

    #[test]
    fn csharp_version_default_is_csharp9() {
        assert_eq!(CSharpVersion::default(), CSharpVersion::CSharp9);
    }

    #[test]
    fn csharp_version_ordering() {
        assert!(CSharpVersion::Unity < CSharpVersion::CSharp9);
        assert!(CSharpVersion::CSharp9 < CSharpVersion::CSharp10);
        assert!(CSharpVersion::CSharp10 < CSharpVersion::CSharp11);
        assert!(CSharpVersion::CSharp11 < CSharpVersion::CSharp12);
    }

    #[test]
    fn csharp_version_display() {
        assert_eq!(CSharpVersion::Unity.to_string(), "Unity");
        assert_eq!(CSharpVersion::CSharp9.to_string(), "9.0");
        assert_eq!(CSharpVersion::CSharp10.to_string(), "10.0");
        assert_eq!(CSharpVersion::CSharp11.to_string(), "11.0");
        assert_eq!(CSharpVersion::CSharp12.to_string(), "12.0");
    }

    #[test]
    fn unity_does_not_support_file_scoped_namespace() {
        assert!(!CSharpVersion::Unity.supports_file_scoped_namespace());
    }

    #[test]
    fn unity_does_not_support_required_modifier() {
        assert!(!CSharpVersion::Unity.supports_required_modifier());
    }

    #[test]
    fn unity_does_not_use_records() {
        assert!(!CSharpVersion::Unity.uses_records());
    }

    #[test]
    fn csharp9_uses_records() {
        assert!(CSharpVersion::CSharp9.uses_records());
    }

    #[test]
    fn csharp10_supports_file_scoped() {
        assert!(CSharpVersion::CSharp10.supports_file_scoped_namespace());
    }

    #[test]
    fn csharp11_supports_all_features() {
        assert!(CSharpVersion::CSharp11.supports_file_scoped_namespace());
        assert!(CSharpVersion::CSharp11.supports_required_modifier());
        assert!(CSharpVersion::CSharp11.uses_records());
    }

    #[test]
    fn namespace_valid_single_segment() {
        let ns = CSharpNamespace::new("MyGame").unwrap();
        assert_eq!(ns.as_ref(), "MyGame");
    }

    #[test]
    fn namespace_valid_multi_segment() {
        let ns = CSharpNamespace::new("Company.Product.Module").unwrap();
        assert_eq!(ns.as_ref(), "Company.Product.Module");
    }

    #[test]
    fn namespace_underscore_prefix_valid() {
        assert!(CSharpNamespace::new("_Internal").is_ok());
    }

    #[test]
    fn namespace_invalid_empty() {
        assert!(CSharpNamespace::new("").is_err());
    }

    #[test]
    fn namespace_invalid_starts_with_digit() {
        assert!(CSharpNamespace::new("1Invalid").is_err());
    }

    #[test]
    fn namespace_invalid_special_chars() {
        assert!(CSharpNamespace::new("My-Namespace").is_err());
    }

    #[test]
    fn namespace_invalid_empty_segment() {
        assert!(CSharpNamespace::new("A..B").is_err());
    }

    #[test]
    fn namespace_display() {
        let ns = CSharpNamespace::new("Test.Ns").unwrap();
        assert_eq!(ns.to_string(), "Test.Ns");
    }

    #[test]
    fn namespace_partial_eq_str() {
        let ns = CSharpNamespace::new("Generated").unwrap();
        assert_eq!(ns, "Generated");
    }

    #[test]
    fn config_default_values() {
        let cfg = Config::default();
        assert_eq!(cfg.namespace(), "Generated");
        assert_eq!(cfg.serializer(), Serializer::SystemTextJson);
        assert_eq!(cfg.target(), CSharpVersion::CSharp9);
        assert_eq!(cfg.export_dir(), Path::new("./csharp-bindings"));
    }

    #[test]
    fn config_with_serializer() {
        let cfg = Config::default().with_serializer(Serializer::Newtonsoft);
        assert_eq!(cfg.serializer(), Serializer::Newtonsoft);
    }

    #[test]
    fn config_with_target() {
        let cfg = Config::default().with_target(CSharpVersion::CSharp12);
        assert_eq!(cfg.target(), CSharpVersion::CSharp12);
    }

    #[test]
    fn config_with_namespace() {
        let cfg = Config::default().with_namespace("My.Game");
        assert_eq!(cfg.namespace(), "My.Game");
    }

    #[test]
    #[should_panic(expected = "each segment must start with a letter")]
    fn config_with_namespace_panics_on_invalid() {
        let _ = Config::default().with_namespace("1Bad");
    }

    #[test]
    fn config_with_validated_namespace() {
        let ns = CSharpNamespace::new("Pre.Validated").unwrap();
        let cfg = Config::default().with_validated_namespace(ns);
        assert_eq!(cfg.namespace(), "Pre.Validated");
    }

    #[test]
    fn config_with_export_dir() {
        let cfg = Config::default().with_export_dir("./output");
        assert_eq!(cfg.export_dir(), Path::new("./output"));
    }

    #[test]
    fn config_builder_chaining() {
        let cfg = Config::default()
            .with_namespace("Unity.Types")
            .with_serializer(Serializer::Newtonsoft)
            .with_target(CSharpVersion::CSharp11)
            .with_export_dir("./generated");
        assert_eq!(cfg.namespace(), "Unity.Types");
        assert_eq!(cfg.serializer(), Serializer::Newtonsoft);
        assert_eq!(cfg.target(), CSharpVersion::CSharp11);
        assert_eq!(cfg.export_dir(), Path::new("./generated"));
    }

    // NOTE: Tests that call `std::env::set_var` / `remove_var` are NOT
    // thread-safe.  Run with `--test-threads=1` if they start flaking.

    #[test]
    fn from_env_defaults_match_default() {
        let cfg = Config::from_env();
        let default = Config::default();
        assert_eq!(cfg.namespace(), default.namespace());
        assert_eq!(cfg.serializer(), default.serializer());
        assert_eq!(cfg.target(), default.target());
        assert_eq!(cfg.export_dir(), default.export_dir());
    }

    #[test]
    fn from_env_reads_serializer() {
        // SAFETY: single-threaded test; no concurrent env access.
        unsafe { std::env::set_var("CSHARP_RS_SERIALIZER", "newtonsoft") };
        let cfg = Config::from_env();
        assert_eq!(cfg.serializer(), Serializer::Newtonsoft);
        // SAFETY: single-threaded test; restoring env to original state.
        unsafe { std::env::remove_var("CSHARP_RS_SERIALIZER") };
    }

    #[test]
    fn from_env_reads_target_unity() {
        // SAFETY: single-threaded test; no concurrent env access.
        unsafe { std::env::set_var("CSHARP_RS_TARGET", "unity") };
        let cfg = Config::from_env();
        assert_eq!(cfg.target(), CSharpVersion::Unity);
        // SAFETY: single-threaded test; restoring env to original state.
        unsafe { std::env::remove_var("CSHARP_RS_TARGET") };
    }

    #[test]
    fn from_env_reads_target_version() {
        // SAFETY: single-threaded test; no concurrent env access.
        unsafe { std::env::set_var("CSHARP_RS_TARGET", "11") };
        let cfg = Config::from_env();
        assert_eq!(cfg.target(), CSharpVersion::CSharp11);
        // SAFETY: single-threaded test; restoring env to original state.
        unsafe { std::env::remove_var("CSHARP_RS_TARGET") };
    }

    #[test]
    fn from_env_reads_namespace() {
        // SAFETY: single-threaded test; no concurrent env access.
        unsafe { std::env::set_var("CSHARP_RS_NAMESPACE", "Game.Types") };
        let cfg = Config::from_env();
        assert_eq!(cfg.namespace(), "Game.Types");
        // SAFETY: single-threaded test; restoring env to original state.
        unsafe { std::env::remove_var("CSHARP_RS_NAMESPACE") };
    }

    #[test]
    fn from_env_reads_export_dir() {
        // SAFETY: single-threaded test; no concurrent env access.
        unsafe { std::env::set_var("CSHARP_RS_EXPORT_DIR", "/tmp/csharp-out") };
        let cfg = Config::from_env();
        assert_eq!(cfg.export_dir(), Path::new("/tmp/csharp-out"));
        // SAFETY: single-threaded test; restoring env to original state.
        unsafe { std::env::remove_var("CSHARP_RS_EXPORT_DIR") };
    }

    #[test]
    fn from_env_invalid_namespace_falls_back() {
        // SAFETY: single-threaded test; no concurrent env access.
        unsafe { std::env::set_var("CSHARP_RS_NAMESPACE", "123invalid") };
        let cfg = Config::from_env();
        assert_eq!(cfg.namespace(), "Generated");
        // SAFETY: single-threaded test; restoring env to original state.
        unsafe { std::env::remove_var("CSHARP_RS_NAMESPACE") };
    }

    #[test]
    fn from_env_unknown_serializer_falls_back() {
        // SAFETY: single-threaded test; no concurrent env access.
        unsafe { std::env::set_var("CSHARP_RS_SERIALIZER", "protobuf") };
        let cfg = Config::from_env();
        assert_eq!(cfg.serializer(), Serializer::SystemTextJson);
        // SAFETY: single-threaded test; restoring env to original state.
        unsafe { std::env::remove_var("CSHARP_RS_SERIALIZER") };
    }

    #[test]
    fn string_maps_to_csharp_string() {
        let cfg = Config::default();
        assert_eq!(String::csharp_name(&cfg), "string");
    }

    #[test]
    fn bool_maps_to_csharp_bool() {
        let cfg = Config::default();
        assert_eq!(bool::csharp_name(&cfg), "bool");
    }

    #[test]
    fn integer_type_mappings() {
        let cfg = Config::default();
        assert_eq!(i8::csharp_name(&cfg), "sbyte");
        assert_eq!(i16::csharp_name(&cfg), "short");
        assert_eq!(i32::csharp_name(&cfg), "int");
        assert_eq!(i64::csharp_name(&cfg), "long");
        assert_eq!(i128::csharp_name(&cfg), "decimal");
        assert_eq!(u8::csharp_name(&cfg), "byte");
        assert_eq!(u16::csharp_name(&cfg), "ushort");
        assert_eq!(u32::csharp_name(&cfg), "uint");
        assert_eq!(u64::csharp_name(&cfg), "ulong");
        assert_eq!(u128::csharp_name(&cfg), "decimal");
    }

    #[test]
    fn float_type_mappings() {
        let cfg = Config::default();
        assert_eq!(f32::csharp_name(&cfg), "float");
        assert_eq!(f64::csharp_name(&cfg), "double");
    }

    #[test]
    fn option_unwraps_inner_type() {
        let cfg = Config::default();
        assert_eq!(<Option<i32>>::csharp_name(&cfg), "int");
    }

    #[test]
    fn vec_maps_to_list() {
        let cfg = Config::default();
        assert_eq!(<Vec<String>>::csharp_name(&cfg), "List<string>");
    }

    #[test]
    fn hashmap_maps_to_dictionary() {
        let cfg = Config::default();
        assert_eq!(
            <HashMap<String, i32>>::csharp_name(&cfg),
            "Dictionary<string, int>"
        );
    }

    #[test]
    fn hashset_maps_to_hashset() {
        let cfg = Config::default();
        assert_eq!(<HashSet<String>>::csharp_name(&cfg), "HashSet<string>");
    }

    #[test]
    fn nested_generics() {
        let cfg = Config::default();
        assert_eq!(<Vec<Option<i32>>>::csharp_name(&cfg), "List<int>");
        assert_eq!(
            <HashMap<String, Vec<f64>>>::csharp_name(&cfg),
            "Dictionary<string, List<double>>"
        );
    }

    // --- primitive csharp_definition / dependencies coverage ---

    #[test]
    fn primitive_definition_is_empty() {
        let cfg = Config::default();
        assert!(String::csharp_definition(&cfg).is_empty());
        assert!(bool::csharp_definition(&cfg).is_empty());
        assert!(i32::csharp_definition(&cfg).is_empty());
        assert!(u64::csharp_definition(&cfg).is_empty());
        assert!(f64::csharp_definition(&cfg).is_empty());
    }

    #[test]
    fn primitive_dependencies_is_empty() {
        let cfg = Config::default();
        assert!(String::dependencies(&cfg).is_empty());
        assert!(bool::dependencies(&cfg).is_empty());
        assert!(i32::dependencies(&cfg).is_empty());
        assert!(u64::dependencies(&cfg).is_empty());
        assert!(f64::dependencies(&cfg).is_empty());
    }

    // --- generic csharp_definition / dependencies coverage ---

    #[test]
    fn option_definition_is_empty() {
        let cfg = Config::default();
        assert!(<Option<i32>>::csharp_definition(&cfg).is_empty());
    }

    #[test]
    fn option_dependencies_contains_inner() {
        let cfg = Config::default();
        let deps = <Option<i32>>::dependencies(&cfg);
        assert_eq!(deps, vec!["int"]);
    }

    #[test]
    fn vec_definition_is_empty() {
        let cfg = Config::default();
        assert!(<Vec<String>>::csharp_definition(&cfg).is_empty());
    }

    #[test]
    fn vec_dependencies_contains_inner() {
        let cfg = Config::default();
        let deps = <Vec<String>>::dependencies(&cfg);
        assert_eq!(deps, vec!["string"]);
    }

    #[test]
    fn hashmap_definition_is_empty() {
        let cfg = Config::default();
        assert!(<HashMap<String, i32>>::csharp_definition(&cfg).is_empty());
    }

    #[test]
    fn hashmap_dependencies_contains_key_and_value() {
        let cfg = Config::default();
        let deps = <HashMap<String, i32>>::dependencies(&cfg);
        assert_eq!(deps, vec!["string", "int"]);
    }

    #[test]
    fn hashset_definition_is_empty() {
        let cfg = Config::default();
        assert!(<HashSet<String>>::csharp_definition(&cfg).is_empty());
    }

    #[test]
    fn hashset_dependencies_contains_inner() {
        let cfg = Config::default();
        let deps = <HashSet<String>>::dependencies(&cfg);
        assert_eq!(deps, vec!["string"]);
    }

    // --- csharp_fields coverage ---

    #[test]
    fn primitive_csharp_fields_is_empty() {
        let cfg = Config::default();
        assert!(String::csharp_fields(&cfg).is_empty());
        assert!(i32::csharp_fields(&cfg).is_empty());
        assert!(bool::csharp_fields(&cfg).is_empty());
    }

    #[test]
    fn generic_csharp_fields_is_empty() {
        let cfg = Config::default();
        assert!(<Vec<String>>::csharp_fields(&cfg).is_empty());
        assert!(<Option<i32>>::csharp_fields(&cfg).is_empty());
        assert!(<HashMap<String, i32>>::csharp_fields(&cfg).is_empty());
        assert!(<HashSet<String>>::csharp_fields(&cfg).is_empty());
    }

    // --- export_to coverage ---

    #[test]
    fn export_to_writes_file() {
        let cfg = Config::default();
        let dir = std::env::temp_dir().join("csharp_rs_test_export");
        let _ = std::fs::remove_dir_all(&dir);
        let path = dir.join("sub").join("Test.cs");

        export_to::<i32>(&cfg, &path).expect("export_to should succeed");

        let content = std::fs::read_to_string(&path).expect("file should exist");
        // Primitives have empty definitions
        assert!(content.is_empty());

        // Cleanup
        let _ = std::fs::remove_dir_all(&dir);
    }

    // --- uuid feature-gated tests ---

    #[cfg(feature = "uuid-impl")]
    #[test]
    fn uuid_maps_to_guid() {
        let cfg = Config::default();
        assert_eq!(<uuid::Uuid as CSharp>::csharp_name(&cfg), "Guid");
        assert!(<uuid::Uuid as CSharp>::csharp_definition(&cfg).is_empty());
        assert!(<uuid::Uuid as CSharp>::dependencies(&cfg).is_empty());
    }
}

// ---------------------------------------------------------------------------
// Feature-gated external type tests
// ---------------------------------------------------------------------------

#[cfg(feature = "chrono-impl")]
#[cfg(test)]
mod chrono_tests {
    use super::*;

    #[test]
    fn datetime_utc_maps_to_datetimeoffset() {
        let cfg = Config::default();
        assert_eq!(
            <chrono::DateTime<chrono::Utc> as CSharp>::csharp_name(&cfg),
            "DateTimeOffset"
        );
    }

    #[test]
    fn naive_date_maps_to_dateonly() {
        let cfg = Config::default();
        assert_eq!(<chrono::NaiveDate as CSharp>::csharp_name(&cfg), "DateOnly");
    }

    #[test]
    fn naive_time_maps_to_timeonly() {
        let cfg = Config::default();
        assert_eq!(<chrono::NaiveTime as CSharp>::csharp_name(&cfg), "TimeOnly");
    }

    #[test]
    fn naive_datetime_maps_to_datetime() {
        let cfg = Config::default();
        assert_eq!(
            <chrono::NaiveDateTime as CSharp>::csharp_name(&cfg),
            "DateTime"
        );
    }

    #[test]
    fn duration_maps_to_timespan() {
        let cfg = Config::default();
        assert_eq!(<chrono::Duration as CSharp>::csharp_name(&cfg), "TimeSpan");
    }
}

#[cfg(feature = "serde-json-impl")]
#[cfg(test)]
mod serde_json_tests {
    use super::*;

    #[test]
    fn serde_json_value_stj_maps_to_json_element() {
        let cfg = Config::default();
        assert_eq!(
            <serde_json::Value as CSharp>::csharp_name(&cfg),
            "JsonElement"
        );
    }

    #[test]
    fn serde_json_value_newtonsoft_maps_to_jtoken() {
        let cfg = Config::default().with_serializer(Serializer::Newtonsoft);
        assert_eq!(<serde_json::Value as CSharp>::csharp_name(&cfg), "JToken");
    }

    #[test]
    fn serde_json_number_maps_to_double() {
        let cfg = Config::default();
        assert_eq!(<serde_json::Number as CSharp>::csharp_name(&cfg), "double");
    }

    #[test]
    fn serde_json_value_definition_is_empty() {
        let cfg = Config::default();
        assert!(<serde_json::Value as CSharp>::csharp_definition(&cfg).is_empty());
    }
}