dotscope 0.6.0

A high-performance, cross-platform framework for analyzing and reverse engineering .NET PE executables
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
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
//! # Type Builder
//!
//! This module provides the [`TypeBuilder`] struct, which offers a fluent API for constructing
//! complex .NET type specifications through a builder pattern. The builder enables the creation
//! of various types including primitives, classes, value types, interfaces, pointers, arrays,
//! and generic types while ensuring proper registration in the [`TypeRegistry`].
//!
//! ## Overview
//!
//! The [`TypeBuilder`] is designed to simplify the creation of type specifications commonly
//! found in .NET metadata. It provides a chainable interface that allows you to:
//!
//! - Create primitive types (integers, floats, etc.)
//! - Build complex reference types (classes, interfaces)
//! - Construct value types (structs, enums)
//! - Add type modifiers (pointers, references, arrays)
//! - Handle generic type instantiations
//! - Apply type constraints and modifiers
//!
//! ## Builder Pattern
//!
//! The builder uses a fluent interface where most methods return `Self`, allowing for method
//! chaining. The builder maintains state about the current type being constructed and can
//! apply various transformations.
//!
//! ## Usage Examples
//!
//! ### Basic Types
//!
//! ```rust
//! use dotscope::metadata::typesystem::{TypeBuilder, TypeRegistry, CilPrimitiveKind};
//! use dotscope::metadata::identity::{AssemblyIdentity, AssemblyVersion};
//! use std::sync::Arc;
//!
//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
//! let identity = AssemblyIdentity::new("TestAssembly", AssemblyVersion::new(1, 0, 0, 0), None, None, None);
//! let registry = Arc::new(TypeRegistry::new(identity)?);
//!
//! // Create a simple integer type
//! let int_type = TypeBuilder::new(registry.clone())
//!     .primitive(CilPrimitiveKind::I4)?
//!     .build()?;
//!
//! // Create a string class
//! let string_type = TypeBuilder::new(registry.clone())
//!     .class("System", "String")?
//!     .build()?;
//! # Ok(())
//! # }
//! ```
//!
//! ### Complex Types
//!
//! ```rust
//! # use dotscope::metadata::typesystem::{TypeBuilder, TypeRegistry, CilPrimitiveKind};
//! # use dotscope::metadata::identity::{AssemblyIdentity, AssemblyVersion};
//! # use std::sync::Arc;
//! # fn example() -> Result<(), Box<dyn std::error::Error>> {
//! # let identity = AssemblyIdentity::new("TestAssembly", AssemblyVersion::new(1, 0, 0, 0), None, None, None);
//! # let registry = Arc::new(TypeRegistry::new(identity)?);
//! // Create an array of integers: int[]
//! let int_array = TypeBuilder::new(registry.clone())
//!     .primitive(CilPrimitiveKind::I4)?
//!     .array()?
//!     .build()?;
//!
//! // Create a pointer to an integer: int*
//! let int_pointer = TypeBuilder::new(registry.clone())
//!     .primitive(CilPrimitiveKind::I4)?
//!     .pointer()?
//!     .build()?;
//!
//! // Create a reference to a string: ref string
//! let string_ref = TypeBuilder::new(registry.clone())
//!     .class("System", "String")?
//!     .by_ref()?
//!     .build()?;
//! # Ok(())
//! # }
//! ```
//!
//! ### Generic Types
//!
//! Generic type construction requires specifying the type arguments through a builder closure.
//! The API has evolved to provide better type safety and memory management for complex generic
//! instantiations.
//!
//! ## Type Context
//!
//! The builder maintains context about where types are being created through the [`TypeSource`]
//! which helps with resolution and proper metadata references.
//!
//! ## Thread Safety
//!
//! The [`TypeBuilder`] is designed to work with the thread-safe [`TypeRegistry`] and can be
//! used safely across multiple threads when the underlying registry supports it.
//!
//! ## References
//!
//! - [`crate::metadata::typesystem::TypeRegistry`] - Type storage and retrieval
//! - [`crate::metadata::typesystem::CilFlavor`] - Type categorization
//! - [ECMA-335 §I.8 - Common Type System](https://www.ecma-international.org/publications-and-standards/standards/ecma-335/)
//!
//! [`TypeRegistry`]: crate::metadata::typesystem::TypeRegistry
//! [`TypeSource`]: crate::metadata::typesystem::TypeSource

use std::sync::Arc;

use crate::{
    metadata::{
        signatures::{SignatureMethod, SignatureMethodSpec},
        tables::MethodSpec,
        token::Token,
        typesystem::{
            CilFlavor, CilModifier, CilPrimitiveKind, CilTypeRc, CilTypeReference,
            CompleteTypeSpec, TypeRegistry, TypeSource,
        },
    },
    Error::TypeError,
    Result,
};

/// A fluent builder for constructing .NET type specifications.
///
/// This struct provides a chainable interface for building complex type specifications
/// from simple primitives to complex constructed types like generics, arrays, and pointers.
/// The builder maintains state about the current type being constructed and provides
/// methods to apply various type transformations.
///
/// ## State Management
///
/// The builder maintains several pieces of state:
/// - **Registry**: Reference to the type registry for type storage/retrieval
/// - **Source Context**: Information about where the type is being created
/// - **Current Type**: The type currently being built (if any)
/// - **Initial Token**: Optional token for the root type being constructed
///
/// ## Usage Pattern
///
/// 1. Create a builder with [`TypeBuilder::new()`]
/// 2. Optionally set context with [`with_source()`](Self::with_source) or [`with_token_init()`](Self::with_token_init)
/// 3. Start with a base type (primitive, class, value type, interface)
/// 4. Apply transformations (pointer, array, generic instantiation, etc.)
/// 5. Build the final type with [`build()`](Self::build)
///
/// ## Example
///
/// ```rust
/// use dotscope::metadata::typesystem::{TypeBuilder, TypeRegistry, CilPrimitiveKind};
/// use dotscope::metadata::identity::AssemblyIdentity;
/// use std::sync::Arc;
///
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// let test_identity = AssemblyIdentity::parse("TestAssembly, Version=1.0.0.0").unwrap();
/// let registry = Arc::new(TypeRegistry::new(test_identity)?);
///
/// // Build int**[] (array of pointers to pointers to int)
/// let complex_type = TypeBuilder::new(registry)
///     .primitive(CilPrimitiveKind::I4)?    // Start with int
///     .pointer()?                           // Make it int*
///     .pointer()?                           // Make it int**
///     .array()?                            // Make it int**[]
///     .build()?;
/// # Ok(())
/// # }
/// ```
///
/// ## Thread Safety
///
/// [`TypeBuilder`] itself is not `Send` or `Sync` as it maintains mutable state during
/// construction. However, it works with the thread-safe [`TypeRegistry`] for the actual
/// type storage.
///
/// [`TypeRegistry`]: crate::metadata::typesystem::TypeRegistry
pub struct TypeBuilder {
    /// Reference to the type registry for storing and retrieving type instances.
    ///
    /// The registry provides centralized storage for all types and ensures
    /// that equivalent types share the same instance (type identity).
    registry: Arc<TypeRegistry>,

    /// Source context indicating where this type is being created.
    ///
    /// This helps with type resolution and determines how relative references
    /// should be interpreted (e.g., current module vs. external assembly).
    source: TypeSource,

    /// The type currently being constructed by this builder.
    ///
    /// Starts as `None` and gets populated when a base type is created
    /// (primitive, class, etc.). Subsequent operations transform this type.
    current_type: Option<CilTypeRc>,

    /// Optional token for the initial/root type being constructed.
    ///
    /// Used to associate the constructed type with a specific metadata
    /// table entry, enabling proper cross-references in the metadata.
    token_init: Option<Token>,
}

impl TypeBuilder {
    /// Creates a new type builder with the specified type registry.
    ///
    /// The builder is initialized with default settings:
    /// - Source context set to the current assembly ([`TypeSource::Assembly`])
    /// - No current type (must be set with a base type method)
    /// - No initial token
    ///
    /// ## Arguments
    ///
    /// * `registry` - Shared reference to the type registry where types will be stored
    ///
    /// ## Returns
    ///
    /// A new [`TypeBuilder`] instance ready for use.
    ///
    /// ## Example
    ///
    /// ```rust
    /// use dotscope::metadata::typesystem::{TypeBuilder, TypeRegistry};
    /// use dotscope::metadata::identity::AssemblyIdentity;
    /// use std::sync::Arc;
    ///
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// let test_identity = AssemblyIdentity::parse("TestAssembly, Version=1.0.0.0").unwrap();
    /// let registry = Arc::new(TypeRegistry::new(test_identity)?);
    /// let builder = TypeBuilder::new(registry);
    /// # Ok(())
    /// # }
    /// ```
    pub fn new(registry: Arc<TypeRegistry>) -> Self {
        let source = registry.current_assembly_source();
        TypeBuilder {
            registry,
            source,
            current_type: None,
            token_init: None,
        }
    }

    /// Sets the source context for type resolution.
    ///
    /// The source context determines how the builder should interpret type references
    /// and where to look for type definitions. This affects how relative type names
    /// are resolved and which assemblies are searched.
    ///
    /// ## Arguments
    ///
    /// * `source` - The [`TypeSource`] context to use for type resolution
    ///
    /// ## Returns
    ///
    /// The builder instance for method chaining.
    ///
    /// ## Example
    ///
    /// ```rust
    /// # use dotscope::metadata::typesystem::{TypeBuilder, TypeRegistry, TypeSource};
    /// # use dotscope::metadata::identity::{AssemblyIdentity, AssemblyVersion};
    /// # use dotscope::metadata::token::Token;
    /// # use std::sync::Arc;
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let identity = AssemblyIdentity::new("TestAssembly", AssemblyVersion::new(1, 0, 0, 0), None, None, None);
    /// # let registry = Arc::new(TypeRegistry::new(identity)?);
    /// let builder = TypeBuilder::new(registry)
    ///     .with_source(TypeSource::Module(Token::new(0x26000001)));
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`TypeSource`]: crate::metadata::typesystem::TypeSource
    #[must_use]
    pub fn with_source(mut self, source: TypeSource) -> Self {
        self.source = source;
        self
    }

    /// Sets the initial token for the root type being constructed.
    ///
    /// This associates the type being built with a specific metadata table entry,
    /// which is important for maintaining proper cross-references in the metadata
    /// and ensuring that the type can be properly resolved later.
    ///
    /// ## Arguments
    ///
    /// * `token` - The [`crate::metadata::token::Token`] representing the metadata table entry for this type
    ///
    /// ## Returns
    ///
    /// The builder instance for method chaining.
    ///
    /// ## Example
    ///
    /// ```rust
    /// # use dotscope::metadata::typesystem::{TypeBuilder, TypeRegistry};
    /// # use dotscope::metadata::token::Token;
    /// # use dotscope::metadata::identity::{AssemblyIdentity, AssemblyVersion};
    /// # use std::sync::Arc;
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let identity = AssemblyIdentity::new("TestAssembly", AssemblyVersion::new(1, 0, 0, 0), None, None, None);
    /// # let registry = Arc::new(TypeRegistry::new(identity)?);
    /// # let token = Token::new(0x02000001); // TypeDef token
    /// let builder = TypeBuilder::new(registry)
    ///     .with_token_init(token);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`crate::metadata::token::Token`]: crate::metadata::token::Token
    #[must_use]
    pub fn with_token_init(mut self, token: Token) -> Self {
        self.token_init = Some(token);
        self
    }

    /// Starts building with a primitive type as the base.
    ///
    /// Primitive types are the built-in types provided by the .NET runtime,
    /// such as integers, floating-point numbers, booleans, and characters.
    /// This method retrieves the appropriate primitive type from the registry.
    ///
    /// ## Arguments
    ///
    /// * `primitive` - The [`CilPrimitiveKind`] specifying which primitive type to use
    ///
    /// ## Returns
    ///
    /// The builder instance for method chaining, or an error if the primitive
    /// type cannot be retrieved from the registry.
    ///
    /// ## Errors
    ///
    /// Returns [`TypeError`] if the primitive type is not available in the registry.
    ///
    /// ## Example
    ///
    /// ```rust
    /// # use dotscope::metadata::typesystem::{TypeBuilder, TypeRegistry, CilPrimitiveKind};
    /// # use dotscope::metadata::identity::{AssemblyIdentity, AssemblyVersion};
    /// # use std::sync::Arc;
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let identity = AssemblyIdentity::new("TestAssembly", AssemblyVersion::new(1, 0, 0, 0), None, None, None);
    /// # let registry = Arc::new(TypeRegistry::new(identity)?);
    /// // Create a 32-bit signed integer type
    /// let int_type = TypeBuilder::new(registry.clone())
    ///     .primitive(CilPrimitiveKind::I4)?
    ///     .build()?;
    ///
    /// // Create a string type
    /// let string_type = TypeBuilder::new(registry)
    ///     .primitive(CilPrimitiveKind::String)?
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`CilPrimitiveKind`]: crate::metadata::typesystem::CilPrimitiveKind
    /// [`TypeError`]: crate::Error::TypeError
    pub fn primitive(mut self, primitive: CilPrimitiveKind) -> Result<Self> {
        self.current_type = Some(self.registry.get_primitive(primitive)?);
        Ok(self)
    }

    /// Starts building with a reference type (class) as the base.
    ///
    /// Classes are reference types that are allocated on the managed heap and support
    /// inheritance. This method creates or retrieves a class type with the specified
    /// namespace and name from the registry.
    ///
    /// ## Arguments
    ///
    /// * `namespace` - The namespace containing the class (e.g., "System")
    /// * `name` - The name of the class (e.g., "String")
    ///
    /// ## Returns
    ///
    /// The builder instance for method chaining, or an error if the class
    /// type cannot be created or retrieved.
    ///
    /// ## Errors
    ///
    /// Returns [`TypeError`] if the class type cannot be created or found in the registry.
    ///
    /// ## Example
    ///
    /// ```rust
    /// # use dotscope::metadata::typesystem::{TypeBuilder, TypeRegistry};
    /// # use dotscope::metadata::identity::{AssemblyIdentity, AssemblyVersion};
    /// # use std::sync::Arc;
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let identity = AssemblyIdentity::new("TestAssembly", AssemblyVersion::new(1, 0, 0, 0), None, None, None);
    /// # let registry = Arc::new(TypeRegistry::new(identity)?);
    /// // Create a System.String class type
    /// let string_type = TypeBuilder::new(registry.clone())
    ///     .class("System", "String")?
    ///     .build()?;
    ///
    /// // Create a custom class
    /// let custom_type = TypeBuilder::new(registry)
    ///     .class("MyNamespace", "MyClass")?
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`TypeError`]: crate::Error::TypeError
    pub fn class(mut self, namespace: &str, name: &str) -> Result<Self> {
        self.current_type = Some(self.registry.get_or_create_type(&CompleteTypeSpec {
            token_init: self.token_init.take(),
            flavor: CilFlavor::Class,
            namespace: namespace.to_string(),
            name: name.to_string(),
            source: self.source.clone(),
            generic_args: None,
            base_type: None,
            flags: None,
        })?);
        Ok(self)
    }

    /// Starts building with a value type (struct) as the base.
    ///
    /// Value types are typically allocated on the stack or inline within objects
    /// and have value semantics (copying creates a new instance). This method
    /// creates or retrieves a value type with the specified namespace and name.
    ///
    /// ## Arguments
    ///
    /// * `namespace` - The namespace containing the value type (e.g., "System")
    /// * `name` - The name of the value type (e.g., "Int32")
    ///
    /// ## Returns
    ///
    /// The builder instance for method chaining, or an error if the value type
    /// cannot be created or retrieved.
    ///
    /// ## Errors
    ///
    /// Returns [`TypeError`] if the value type cannot be created or found in the registry.
    ///
    /// ## Example
    ///
    /// ```rust
    /// # use dotscope::metadata::typesystem::{TypeBuilder, TypeRegistry};
    /// # use dotscope::metadata::identity::{AssemblyIdentity, AssemblyVersion};
    /// # use std::sync::Arc;
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let identity = AssemblyIdentity::new("TestAssembly", AssemblyVersion::new(1, 0, 0, 0), None, None, None);
    /// # let registry = Arc::new(TypeRegistry::new(identity)?);
    /// // Create a System.DateTime value type
    /// let datetime_type = TypeBuilder::new(registry.clone())
    ///     .value_type("System", "DateTime")?
    ///     .build()?;
    ///
    /// // Create a custom struct
    /// let point_type = TypeBuilder::new(registry)
    ///     .value_type("MyNamespace", "Point")?
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`TypeError`]: crate::Error::TypeError
    pub fn value_type(mut self, namespace: &str, name: &str) -> Result<Self> {
        self.current_type = Some(self.registry.get_or_create_type(&CompleteTypeSpec {
            token_init: self.token_init.take(),
            flavor: CilFlavor::ValueType,
            namespace: namespace.to_string(),
            name: name.to_string(),
            source: self.source.clone(),
            generic_args: None,
            base_type: None,
            flags: None,
        })?);
        Ok(self)
    }

    /// Starts building with an interface type as the base.
    ///
    /// Interfaces define contracts that can be implemented by classes and structs.
    /// They specify method signatures, properties, and events that implementing
    /// types must provide. This method creates or retrieves an interface type
    /// with the specified namespace and name.
    ///
    /// ## Arguments
    ///
    /// * `namespace` - The namespace containing the interface (e.g., "System.Collections")
    /// * `name` - The name of the interface (e.g., `IEnumerable`)
    ///
    /// ## Returns
    ///
    /// The builder instance for method chaining, or an error if the interface
    /// type cannot be created or retrieved.
    ///
    /// ## Errors
    ///
    /// Returns [`TypeError`] if the interface type cannot be created or found in the registry.
    ///
    /// ## Example
    ///
    /// ```rust
    /// # use dotscope::metadata::typesystem::{TypeBuilder, TypeRegistry};
    /// # use dotscope::metadata::identity::{AssemblyIdentity, AssemblyVersion};
    /// # use std::sync::Arc;
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let identity = AssemblyIdentity::new("TestAssembly", AssemblyVersion::new(1, 0, 0, 0), None, None, None);
    /// # let registry = Arc::new(TypeRegistry::new(identity)?);
    /// // Create IDisposable interface
    /// let disposable_interface = TypeBuilder::new(registry.clone())
    ///     .interface("System", "IDisposable")?
    ///     .build()?;
    ///
    /// // Create a custom interface
    /// let custom_interface = TypeBuilder::new(registry)
    ///     .interface("MyNamespace", "IMyInterface")?
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// [`TypeError`]: crate::Error::TypeError
    pub fn interface(mut self, namespace: &str, name: &str) -> Result<Self> {
        self.current_type = Some(self.registry.get_or_create_type(&CompleteTypeSpec {
            token_init: self.token_init.take(),
            flavor: CilFlavor::Interface,
            namespace: namespace.to_string(),
            name: name.to_string(),
            source: self.source.clone(),
            generic_args: None,
            base_type: None,
            flags: None,
        })?);
        Ok(self)
    }

    /// Creates a pointer type to the current type.
    ///
    /// This method transforms the current type into an unmanaged pointer type.
    /// Pointer types are used for unsafe operations and interop scenarios where
    /// direct memory access is required. The resulting type represents a pointer
    /// to the base type (e.g., `int*` for a pointer to `int`).
    ///
    /// ## Returns
    ///
    /// The builder instance for method chaining, or an error if the pointer
    /// type cannot be created.
    ///
    /// ## Errors
    ///
    /// Returns [`TypeError`] if:
    /// - No current type is set (must call a base type method first)
    /// - The pointer type cannot be created in the registry
    ///
    /// ## Example
    ///
    /// ```rust
    /// # use dotscope::metadata::typesystem::{TypeBuilder, TypeRegistry, CilPrimitiveKind};
    /// # use dotscope::metadata::identity::{AssemblyIdentity, AssemblyVersion};
    /// # use std::sync::Arc;
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let identity = AssemblyIdentity::new("TestAssembly", AssemblyVersion::new(1, 0, 0, 0), None, None, None);
    /// # let registry = Arc::new(TypeRegistry::new(identity)?);
    /// // Create int* (pointer to int)
    /// let int_ptr = TypeBuilder::new(registry.clone())
    ///     .primitive(CilPrimitiveKind::I4)?
    ///     .pointer()?
    ///     .build()?;
    ///
    /// // Create char** (pointer to pointer to char)
    /// let char_ptr_ptr = TypeBuilder::new(registry)
    ///     .primitive(CilPrimitiveKind::Char)?
    ///     .pointer()?
    ///     .pointer()?
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// ## Safety
    ///
    /// Pointer types are inherently unsafe and should only be used when necessary
    /// for interop or performance-critical scenarios.
    ///
    /// [`TypeError`]: crate::Error::TypeError
    pub fn pointer(mut self) -> Result<Self> {
        if let Some(base_type) = self.current_type.take() {
            let ptr_type = self.registry.get_or_create_type(&CompleteTypeSpec {
                token_init: self.token_init.take(),
                flavor: CilFlavor::Pointer,
                namespace: base_type.namespace.clone(),
                name: format!("{}*", base_type.name),
                source: self.source.clone(),
                generic_args: None,
                base_type: Some(base_type),
                flags: None,
            })?;

            self.current_type = Some(ptr_type);
        }
        Ok(self)
    }

    /// Create a by-reference version of the current type
    ///
    /// # Errors
    /// Returns an error if no current type is set or if the by-reference type cannot be created.
    pub fn by_ref(mut self) -> Result<Self> {
        if let Some(base_type) = self.current_type.take() {
            let name = format!("{}&", base_type.name);
            let namespace = base_type.namespace.clone();

            let ref_type = self.registry.get_or_create_type(&CompleteTypeSpec {
                token_init: self.token_init.take(),
                flavor: CilFlavor::ByRef,
                namespace: namespace.clone(),
                name,
                source: self.source.clone(),
                generic_args: None,
                base_type: None,
                flags: None,
            })?;

            ref_type
                .base
                .set(base_type.into())
                .map_err(|_| malformed_error!("ByRef type base already set"))?;
            self.current_type = Some(ref_type);
        }
        Ok(self)
    }

    /// Create a pinned version of the current type
    ///
    /// # Errors
    /// Returns an error if no current type is set or if the pinned type cannot be created.
    pub fn pinned(mut self) -> Result<Self> {
        if let Some(base_type) = self.current_type.take() {
            let name = format!("pinned {}", base_type.name);
            let namespace = base_type.namespace.clone();

            let pinned_type = self.registry.get_or_create_type(&CompleteTypeSpec {
                token_init: self.token_init.take(),
                flavor: CilFlavor::Pinned,
                namespace: namespace.clone(),
                name,
                source: self.source.clone(),
                generic_args: None,
                base_type: None,
                flags: None,
            })?;

            pinned_type
                .base
                .set(base_type.into())
                .map_err(|_| malformed_error!("Pinned type base already set"))?;
            self.current_type = Some(pinned_type);
        }
        Ok(self)
    }

    /// Creates a single-dimensional array type of the current type.
    ///
    /// This method transforms the current type into a single-dimensional array type
    /// with zero-based indexing (e.g., `int[]` for an array of integers). The array
    /// uses the standard .NET array semantics with automatic bounds checking.
    ///
    /// ## Returns
    ///
    /// The builder instance for method chaining, or an error if the array
    /// type cannot be created.
    ///
    /// ## Errors
    ///
    /// Returns [`TypeError`] if:
    /// - No current type is set (must call a base type method first)
    /// - The array type cannot be created in the registry
    ///
    /// ## Example
    ///
    /// ```rust
    /// # use dotscope::metadata::typesystem::{TypeBuilder, TypeRegistry, CilPrimitiveKind};
    /// # use dotscope::metadata::identity::{AssemblyIdentity, AssemblyVersion};
    /// # use std::sync::Arc;
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let identity = AssemblyIdentity::new("TestAssembly", AssemblyVersion::new(1, 0, 0, 0), None, None, None);
    /// # let registry = Arc::new(TypeRegistry::new(identity)?);
    /// // Create int[] (array of integers)
    /// let int_array = TypeBuilder::new(registry.clone())
    ///     .primitive(CilPrimitiveKind::I4)?
    ///     .array()?
    ///     .build()?;
    ///
    /// // Create string[] (array of strings)
    /// let string_array = TypeBuilder::new(registry.clone())
    ///     .class("System", "String")?
    ///     .array()?
    ///     .build()?;
    ///
    /// // Create int[][] (array of arrays of integers)
    /// let nested_array = TypeBuilder::new(registry)
    ///     .primitive(CilPrimitiveKind::I4)?
    ///     .array()?
    ///     .array()?
    ///     .build()?;
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// ## Notes
    ///
    /// - Single-dimensional arrays are the most common array type in .NET
    /// - They have zero-based indexing and automatic bounds checking
    /// - For multi-dimensional arrays, use [`multi_dimensional_array()`](Self::multi_dimensional_array)
    ///
    /// [`TypeError`]: crate::Error::TypeError
    pub fn array(mut self) -> Result<Self> {
        if let Some(base_type) = self.current_type.take() {
            let name = format!("{}[]", base_type.name);
            let namespace = base_type.namespace.clone();

            let array_type = self.registry.get_or_create_type(&CompleteTypeSpec {
                token_init: self.token_init.take(),
                flavor: CilFlavor::Array {
                    element_type: Box::new(base_type.flavor().clone()),
                    rank: 1,
                    dimensions: vec![],
                },
                namespace: namespace.clone(),
                name,
                source: self.source.clone(),
                generic_args: None,
                base_type: None,
                flags: None,
            })?;

            array_type
                .base
                .set(base_type.into())
                .map_err(|_| malformed_error!("Array type base already set"))?;
            self.current_type = Some(array_type);
        }
        Ok(self)
    }

    /// Create a multi-dimensional array of the current type
    ///
    /// ## Arguments
    /// * 'rank' - The dimensions for the array
    ///
    /// # Errors
    /// Returns an error if no current type is set or if the multi-dimensional array type cannot be created.
    pub fn multi_dimensional_array(mut self, rank: u32) -> Result<Self> {
        if let Some(base_type) = self.current_type.take() {
            let dimension_part = if rank <= 1 {
                "[]".to_string()
            } else {
                format!("[{}]", ",".repeat(rank as usize - 1))
            };

            let name = format!("{}{}", base_type.name, dimension_part);
            let namespace = base_type.namespace.clone();

            let array_type = self.registry.get_or_create_type(&CompleteTypeSpec {
                token_init: self.token_init.take(),
                flavor: CilFlavor::Array {
                    element_type: Box::new(base_type.flavor().clone()),
                    rank,
                    dimensions: vec![],
                },
                namespace: namespace.clone(),
                name,
                source: self.source.clone(),
                generic_args: None,
                base_type: None,
                flags: None,
            })?;

            array_type
                .base
                .set(base_type.into())
                .map_err(|_| malformed_error!("Multi-dimensional array type base already set"))?;
            self.current_type = Some(array_type);
        }
        Ok(self)
    }

    /// Create or set a function pointer type
    ///
    /// ## Arguments
    /// * 'signature' - Set the signature for the function pointer
    ///
    /// # Errors
    /// Returns an error if the function pointer type cannot be created.
    pub fn function_pointer(mut self, signature: SignatureMethod) -> Result<Self> {
        let name = Self::format_fnptr_name(&signature);

        let fn_ptr_type = self.registry.get_or_create_type(&CompleteTypeSpec {
            token_init: self.token_init.take(),
            flavor: CilFlavor::FnPtr { signature },
            namespace: String::new(),
            name,
            source: self.source.clone(),
            generic_args: None,
            base_type: None,
            flags: None,
        })?;

        self.current_type = Some(fn_ptr_type);
        Ok(self)
    }

    /// Add required modifier to the current type
    ///
    /// ## Arguments
    /// * `modifer_token` - Set the modifier token
    ///
    /// # Errors
    /// Returns an error if the modifier cannot be applied (currently always succeeds).
    pub fn required_modifier(self, modifier_token: Token) -> Result<Self> {
        if let Some(current) = &self.current_type {
            if let Some(modifier_type) = self.registry.get(&modifier_token) {
                current.modifiers.push(CilModifier {
                    required: true,
                    modifier: modifier_type.into(),
                });
            }
        }
        Ok(self)
    }

    /// Add optional modifier to the current type
    ///
    /// ## Arguments
    /// * `modifer_token` - Set the modifier token
    ///
    /// # Errors
    /// Returns an error if the modifier cannot be applied (currently always succeeds).
    pub fn optional_modifier(self, modifier_token: Token) -> Result<Self> {
        if let Some(current) = &self.current_type {
            if let Some(modifier_type) = self.registry.get(&modifier_token) {
                current.modifiers.push(CilModifier {
                    required: false,
                    modifier: modifier_type.into(),
                });
            }
        }
        Ok(self)
    }

    /// Specify a base type for the current type
    ///
    /// ## Arguments
    /// * `base_token` - Set the base of the type
    ///
    /// # Errors
    /// Returns an error if the base type is already set or if the base token cannot be resolved.
    pub fn extends(self, base_token: Token) -> Result<Self> {
        if let Some(current) = &self.current_type {
            // Get the base type
            if let Some(base_type) = self.registry.get(&base_token) {
                current
                    .base
                    .set(base_type.into())
                    .map_err(|_| malformed_error!("Base type already set"))?;
            }
        }
        Ok(self)
    }

    /// Create a generic instance of the current type
    ///
    /// ## Arguments
    /// * `arg_count`   - Argument count for the generic instance
    /// * `arg_builder` - Builder function for the arguments
    ///
    /// # Errors
    /// Returns an error if no current type is set, if the argument builder fails,
    /// or if the generic instance type cannot be created.
    pub fn generic_instance<F>(mut self, arg_count: usize, arg_builder: F) -> Result<Self>
    where
        F: FnOnce(Arc<TypeRegistry>) -> Result<Vec<CilTypeRc>>,
    {
        if let Some(base_type) = self.current_type.take() {
            let name = Self::format_generic_name(&base_type.name, arg_count);
            let namespace = base_type.namespace.clone();
            let generic_type = self.registry.get_or_create_type(&CompleteTypeSpec {
                token_init: self.token_init.take(),
                flavor: CilFlavor::GenericInstance,
                namespace: namespace.clone(),
                name,
                source: self.source.clone(),
                generic_args: None,
                base_type: None,
                flags: None,
            })?;

            let args = arg_builder(self.registry.clone())?;
            if !args.is_empty() {
                // For type-level generic instances, create MethodSpec instances that wrap the resolved types
                for (index, arg) in args.iter().enumerate() {
                    // Create a dummy method specification for the type argument
                    let rid = u32::try_from(index)
                        .map_err(|_| malformed_error!("Generic argument index too large"))?
                        + 1;
                    let token_value =
                        0x2B00_0000_u32
                            .checked_add(u32::try_from(index).map_err(|_| {
                                malformed_error!("Generic argument index too large")
                            })?)
                            .and_then(|v| v.checked_add(1))
                            .ok_or_else(|| malformed_error!("Token value overflow"))?;

                    let method_spec = Arc::new(MethodSpec {
                        rid,
                        token: Token::new(token_value),
                        offset: 0,
                        method: CilTypeReference::None,
                        instantiation: SignatureMethodSpec {
                            generic_args: vec![],
                        },
                        custom_attributes: Arc::new(boxcar::Vec::new()),
                        generic_args: {
                            let type_ref_list = Arc::new(boxcar::Vec::with_capacity(1));
                            type_ref_list.push(arg.clone().into());
                            type_ref_list
                        },
                    });
                    generic_type.generic_args.push(method_spec);
                }
            }

            generic_type
                .base
                .set(base_type.into())
                .map_err(|_| malformed_error!("Generic type base already set"))?;
            self.current_type = Some(generic_type);
        }
        Ok(self)
    }

    /// Formats a type name with generic arity marker.
    ///
    /// If the name doesn't already contain a backtick (`), appends the generic arity
    /// in the format `Name`N` where N is the number of type arguments.
    ///
    /// # Arguments
    /// * `base_name` - The original type name
    /// * `arg_count` - The number of generic type arguments
    ///
    /// # Returns
    /// The name with generic arity marker, or the original name if already present.
    ///
    /// # Examples
    /// - `"List"` with 1 arg becomes `"List`1"`
    /// - `"Dictionary"` with 2 args becomes `"Dictionary`2"`
    /// - `"List`1"` with 1 arg stays `"List`1"`
    fn format_generic_name(base_name: &str, arg_count: usize) -> String {
        if base_name.contains('`') {
            base_name.to_string()
        } else {
            format!("{base_name}`{arg_count}")
        }
    }

    /// Formats a stable name for function pointer types based on signature characteristics.
    ///
    /// Generates a deterministic name based on the function signature's calling convention,
    /// parameter count, and return type rather than relying on unstable pointer addresses.
    /// This produces reproducible names across runs and platforms.
    ///
    /// # Arguments
    /// * `signature` - The method signature to derive the name from
    ///
    /// # Returns
    /// A deterministic string like `FnPtr_stdcall_2_void` representing the signature.
    fn format_fnptr_name(signature: &SignatureMethod) -> String {
        let calling_convention = if signature.stdcall {
            "stdcall"
        } else if signature.cdecl {
            "cdecl"
        } else if signature.thiscall {
            "thiscall"
        } else if signature.fastcall {
            "fastcall"
        } else {
            "default"
        };

        let param_count = signature.params.len();
        let return_info = format!("{:?}", signature.return_type.base).replace(' ', "");

        // Truncate return_info to avoid extremely long names
        let return_short = if return_info.len() > 16 {
            &return_info[..16]
        } else {
            &return_info
        };

        format!("FnPtr_{calling_convention}_{param_count}_{return_short}")
    }

    /// Finalizes the type construction and returns the built type.
    ///
    /// This method completes the type building process and returns the constructed
    /// type specification. It consumes the builder and returns the final type that
    /// was created through the chain of builder method calls.
    ///
    /// ## Returns
    ///
    /// The constructed [`CilTypeRc`] representing the complete type specification,
    /// or an error if the type construction failed.
    ///
    /// ## Errors
    ///
    /// Returns [`TypeError`] if:
    /// - No type has been constructed (no base type method was called)
    /// - The type construction process failed at any step
    ///
    /// ## Example
    ///
    /// ```rust
    /// # use dotscope::metadata::typesystem::{TypeBuilder, TypeRegistry, CilPrimitiveKind};
    /// # use dotscope::metadata::identity::{AssemblyIdentity, AssemblyVersion};
    /// # use std::sync::Arc;
    /// # fn example() -> Result<(), Box<dyn std::error::Error>> {
    /// # let identity = AssemblyIdentity::new("TestAssembly", AssemblyVersion::new(1, 0, 0, 0), None, None, None);
    /// # let registry = Arc::new(TypeRegistry::new(identity)?);
    /// // Build a complete type specification
    /// let array_type = TypeBuilder::new(registry)
    ///     .primitive(CilPrimitiveKind::I4)?  // Start with int
    ///     .pointer()?                        // Make it int*
    ///     .array()?                         // Make it (int*)[]
    ///     .build()?;                        // Finalize
    ///
    /// // The type is now ready for use
    /// println!("Built type: {}.{}", array_type.namespace, array_type.name);
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// ## Notes
    ///
    /// - This method must be called to complete the type construction process
    /// - The builder is consumed by this method and cannot be reused
    /// - The returned type is registered in the type registry and can be retrieved later
    ///
    /// [`CilTypeRc`]: crate::metadata::typesystem::CilTypeRc
    /// [`TypeError`]: crate::Error::TypeError
    pub fn build(self) -> Result<CilTypeRc> {
        match self.current_type {
            Some(t) => Ok(t),
            None => Err(TypeError("Failed to build requested Type".to_string())),
        }
    }
}

#[cfg(test)]
mod tests {
    use std::sync::{Arc, OnceLock};

    use super::*;
    use crate::{
        metadata::{
            identity::AssemblyIdentity,
            signatures::{SignatureMethod, SignatureParameter, TypeSignature},
            tables::GenericParam,
            token::Token,
            typesystem::{CilFlavor, CilPrimitiveKind, TypeRegistry, TypeSource},
        },
        Error,
    };

    #[test]
    fn test_build_primitive() {
        let test_identity = AssemblyIdentity::parse("TestAssembly, Version=1.0.0.0").unwrap();
        let registry = Arc::new(TypeRegistry::new(test_identity).unwrap());

        let int_type = TypeBuilder::new(registry.clone())
            .primitive(CilPrimitiveKind::I4)
            .unwrap()
            .build()
            .unwrap();

        assert_eq!(int_type.name, "Int32");
        assert_eq!(int_type.namespace, "System");
        assert!(matches!(*int_type.flavor(), CilFlavor::I4));
    }

    #[test]
    fn test_build_pointer() {
        let test_identity = AssemblyIdentity::parse("TestAssembly, Version=1.0.0.0").unwrap();
        let registry = Arc::new(TypeRegistry::new(test_identity).unwrap());

        let int_ptr = TypeBuilder::new(registry.clone())
            .primitive(CilPrimitiveKind::I4)
            .unwrap()
            .pointer()
            .unwrap()
            .build()
            .unwrap();

        assert_eq!(int_ptr.name, "Int32*");
        assert!(matches!(*int_ptr.flavor(), CilFlavor::Pointer));

        let base_type = int_ptr.base.get().unwrap().upgrade().unwrap();
        assert_eq!(base_type.name, "Int32");
    }

    #[test]
    fn test_build_array() {
        let test_identity = AssemblyIdentity::parse("TestAssembly, Version=1.0.0.0").unwrap();
        let registry = Arc::new(TypeRegistry::new(test_identity).unwrap());

        let string_array = TypeBuilder::new(registry.clone())
            .primitive(CilPrimitiveKind::String)
            .unwrap()
            .array()
            .unwrap()
            .build()
            .unwrap();

        assert_eq!(string_array.name, "String[]");
        assert!(matches!(*string_array.flavor(), CilFlavor::Array { .. }));

        let base_type = string_array.base.get().unwrap().upgrade().unwrap();
        assert_eq!(base_type.name, "String");
    }

    #[test]
    fn test_build_multidimensional_array() {
        let test_identity = AssemblyIdentity::parse("TestAssembly, Version=1.0.0.0").unwrap();
        let registry = Arc::new(TypeRegistry::new(test_identity).unwrap());

        let int_2d_array = TypeBuilder::new(registry.clone())
            .primitive(CilPrimitiveKind::I4)
            .unwrap()
            .multi_dimensional_array(2)
            .unwrap()
            .build()
            .unwrap();

        assert_eq!(int_2d_array.name, "Int32[,]");

        if let CilFlavor::Array { rank, .. } = *int_2d_array.flavor() {
            assert_eq!(rank, 2);
        } else {
            panic!("Expected Array flavor");
        };
    }

    #[test]
    fn test_build_class() {
        let test_identity = AssemblyIdentity::parse("TestAssembly, Version=1.0.0.0").unwrap();
        let registry = Arc::new(TypeRegistry::new(test_identity).unwrap());

        let list_type = TypeBuilder::new(registry.clone())
            .class("System.Collections.Generic", "List`1")
            .unwrap()
            .build()
            .unwrap();

        assert_eq!(list_type.name, "List`1");
        assert_eq!(list_type.namespace, "System.Collections.Generic");
        assert!(matches!(*list_type.flavor(), CilFlavor::Class));
    }

    #[test]
    fn test_build_value_type() {
        let test_identity = AssemblyIdentity::parse("TestAssembly, Version=1.0.0.0").unwrap();
        let registry = Arc::new(TypeRegistry::new(test_identity).unwrap());

        let struct_type = TypeBuilder::new(registry.clone())
            .value_type("System", "DateTime")
            .unwrap()
            .build()
            .unwrap();

        assert_eq!(struct_type.name, "DateTime");
        assert_eq!(struct_type.namespace, "System");
        assert!(matches!(*struct_type.flavor(), CilFlavor::ValueType));
    }

    #[test]
    fn test_build_interface() {
        let test_identity = AssemblyIdentity::parse("TestAssembly, Version=1.0.0.0").unwrap();
        let registry = Arc::new(TypeRegistry::new(test_identity).unwrap());

        let interface_type = TypeBuilder::new(registry.clone())
            .interface("System.Collections.Generic", "IList`1")
            .unwrap()
            .build()
            .unwrap();

        assert_eq!(interface_type.name, "IList`1");
        assert_eq!(interface_type.namespace, "System.Collections.Generic");
        assert!(matches!(*interface_type.flavor(), CilFlavor::Interface));
    }

    #[test]
    fn test_build_generic_instance() {
        let test_identity = AssemblyIdentity::parse("TestAssembly, Version=1.0.0.0").unwrap();
        let registry = Arc::new(TypeRegistry::new(test_identity).unwrap());

        let list_type = TypeBuilder::new(registry.clone())
            .class("System.Collections.Generic", "List`1")
            .unwrap()
            .build()
            .unwrap();

        let generic_param = Arc::new(GenericParam {
            token: Token::new(0x2A000001),
            number: 0,
            flags: 0,
            owner: OnceLock::new(),
            name: "T".to_string(),
            constraints: Arc::new(boxcar::Vec::new()),
            rid: 0,
            offset: 0,
            custom_attributes: Arc::new(boxcar::Vec::new()),
        });

        list_type.generic_params.push(generic_param);

        let list_int_instance = TypeBuilder::new(registry.clone())
            .with_source(TypeSource::Unknown)
            .class("System.Collections.Generic", "List`1")
            .unwrap()
            .generic_instance(1, |registry| {
                // Get int type
                let int_type = registry.get_primitive(CilPrimitiveKind::I4).unwrap();
                Ok(vec![int_type])
            })
            .unwrap()
            .build()
            .unwrap();

        assert_eq!(list_int_instance.name, "List`1");
        assert!(matches!(
            *list_int_instance.flavor(),
            CilFlavor::GenericInstance
        ));

        assert_eq!(list_int_instance.generic_args.count(), 1);
        assert_eq!(
            list_int_instance.generic_args[0].generic_args[0]
                .name()
                .unwrap(),
            "Int32"
        );
    }

    #[test]
    fn test_build_byref() {
        let test_identity = AssemblyIdentity::parse("TestAssembly, Version=1.0.0.0").unwrap();
        let registry = Arc::new(TypeRegistry::new(test_identity).unwrap());

        let byref_type = TypeBuilder::new(registry.clone())
            .primitive(CilPrimitiveKind::I4)
            .unwrap()
            .by_ref()
            .unwrap()
            .build()
            .unwrap();

        assert_eq!(byref_type.name, "Int32&");
        assert!(matches!(*byref_type.flavor(), CilFlavor::ByRef));

        let base_type = byref_type.base.get().unwrap().upgrade().unwrap();
        assert_eq!(base_type.name, "Int32");
    }

    #[test]
    fn test_build_pinned() {
        let test_identity = AssemblyIdentity::parse("TestAssembly, Version=1.0.0.0").unwrap();
        let registry = Arc::new(TypeRegistry::new(test_identity).unwrap());

        let pinned_type = TypeBuilder::new(registry.clone())
            .primitive(CilPrimitiveKind::Object)
            .unwrap()
            .pinned()
            .unwrap()
            .build()
            .unwrap();

        assert_eq!(pinned_type.name, "pinned Object");
        assert!(matches!(*pinned_type.flavor(), CilFlavor::Pinned));

        let base_type = pinned_type.base.get().unwrap().upgrade().unwrap();
        assert_eq!(base_type.name, "Object");
    }

    #[test]
    fn test_build_function_pointer() {
        let test_identity = AssemblyIdentity::parse("TestAssembly, Version=1.0.0.0").unwrap();
        let registry = Arc::new(TypeRegistry::new(test_identity).unwrap());

        let signature = SignatureMethod {
            has_this: false,
            explicit_this: false,
            return_type: SignatureParameter {
                modifiers: Vec::new(),
                base: TypeSignature::Void,
                by_ref: false,
            },
            params: Vec::new(),
            default: false,
            vararg: false,
            cdecl: false,
            stdcall: true,
            thiscall: false,
            fastcall: false,
            param_count_generic: 0,
            param_count: 0,
            varargs: Vec::new(),
        };

        let fn_ptr = TypeBuilder::new(registry.clone())
            .function_pointer(signature)
            .unwrap()
            .build()
            .unwrap();

        // Name format changed from pointer-based to deterministic signature-based
        assert!(fn_ptr.name.starts_with("FnPtr_"));
        if let CilFlavor::FnPtr { signature: sig } = fn_ptr.flavor() {
            assert!(!sig.has_this);
            assert_eq!(sig.params.len(), 0);
        } else {
            panic!("Expected FnPtr flavor");
        };
    }

    #[test]
    fn test_with_source() {
        let test_identity = AssemblyIdentity::parse("TestAssembly, Version=1.0.0.0").unwrap();
        let registry = Arc::new(TypeRegistry::new(test_identity).unwrap());

        let source = TypeSource::AssemblyRef(Token::new(0x23000001));
        let int_type = TypeBuilder::new(registry.clone())
            .with_source(source)
            .primitive(CilPrimitiveKind::I4)
            .unwrap()
            .build()
            .unwrap();

        assert_eq!(int_type.name, "Int32");
    }

    #[test]
    fn test_with_token_init() {
        let test_identity = AssemblyIdentity::parse("TestAssembly, Version=1.0.0.0").unwrap();
        let registry = Arc::new(TypeRegistry::new(test_identity).unwrap());

        let token: Token = Token::new(0x01000999);
        let list_type = TypeBuilder::new(registry.clone())
            .with_token_init(token)
            .class("System.Collections.Generic", "List`1")
            .unwrap()
            .build()
            .unwrap();

        assert_eq!(list_type.name, "List`1");
        assert_eq!(list_type.namespace, "System.Collections.Generic");
        assert_eq!(list_type.token, token);
        assert!(matches!(*list_type.flavor(), CilFlavor::Class));
    }

    #[test]
    fn test_modifiers() {
        let test_identity = AssemblyIdentity::parse("TestAssembly, Version=1.0.0.0").unwrap();
        let registry = Arc::new(TypeRegistry::new(test_identity).unwrap());

        let in_attr_token = Token::new(0x01000888);
        let _ = registry
            .get_or_create_type(&CompleteTypeSpec {
                token_init: Some(in_attr_token),
                flavor: CilFlavor::Class,
                namespace: "System.Runtime.InteropServices".to_string(),
                name: "InAttribute".to_string(),
                source: TypeSource::Unknown,
                generic_args: None,
                base_type: None,
                flags: None,
            })
            .unwrap();

        let int_type = TypeBuilder::new(registry.clone())
            .primitive(CilPrimitiveKind::I4)
            .unwrap()
            .required_modifier(in_attr_token)
            .unwrap()
            .build()
            .unwrap();

        assert_eq!(int_type.modifiers.count(), 1);
        assert!(int_type.modifiers[0].required);
        assert_eq!(
            int_type.modifiers[0].modifier.name().unwrap(),
            "InAttribute"
        );

        let string_type = TypeBuilder::new(registry.clone())
            .primitive(CilPrimitiveKind::String)
            .unwrap()
            .optional_modifier(in_attr_token)
            .unwrap()
            .build()
            .unwrap();

        assert_eq!(string_type.modifiers.count(), 1);
        assert!(!string_type.modifiers[0].required);
    }

    #[test]
    fn test_extends() {
        let test_identity = AssemblyIdentity::parse("TestAssembly, Version=1.0.0.0").unwrap();
        let registry = Arc::new(TypeRegistry::new(test_identity).unwrap());

        let base_token = Token::new(0x01000777);
        let _ = registry
            .get_or_create_type(&CompleteTypeSpec {
                token_init: Some(base_token),
                flavor: CilFlavor::Class,
                namespace: "System".to_string(),
                name: "Exception".to_string(),
                source: TypeSource::Unknown,
                generic_args: None,
                base_type: None,
                flags: None,
            })
            .unwrap();

        let derived_type = TypeBuilder::new(registry.clone())
            .class("System.IO", "IOException")
            .unwrap()
            .extends(base_token)
            .unwrap()
            .build()
            .unwrap();

        let base_type = derived_type.base.get().unwrap().upgrade();
        assert!(base_type.is_some());
        let base_type = base_type.unwrap();
        assert_eq!(base_type.token, base_token);
        assert_eq!(base_type.name, "Exception");
    }

    #[test]
    fn test_build_failure() {
        let test_identity = AssemblyIdentity::parse("TestAssembly, Version=1.0.0.0").unwrap();
        let registry = Arc::new(TypeRegistry::new(test_identity).unwrap());

        let result = TypeBuilder::new(registry.clone()).build();
        assert!(result.is_err());
        match result {
            Err(Error::TypeError(_)) => (), // Expected error
            _ => panic!("Expected TypeError"),
        }
    }

    #[test]
    fn test_build_complex_chain() {
        let test_identity = AssemblyIdentity::parse("TestAssembly, Version=1.0.0.0").unwrap();
        let registry = Arc::new(TypeRegistry::new(test_identity).unwrap());

        // Build a complex type chain: string[][]*&
        let complex_type = TypeBuilder::new(registry.clone())
            .primitive(CilPrimitiveKind::String)
            .unwrap()
            .array()
            .unwrap() // string[]
            .array()
            .unwrap() // string[][]
            .pointer()
            .unwrap() // string[][]*
            .by_ref()
            .unwrap() // string[][]*&
            .build()
            .unwrap();

        assert_eq!(complex_type.name, "String[][]*&");
        assert!(matches!(*complex_type.flavor(), CilFlavor::ByRef));

        let pointer_type = complex_type.base.get().unwrap().upgrade().unwrap();
        assert_eq!(pointer_type.name, "String[][]*");
        assert!(matches!(*pointer_type.flavor(), CilFlavor::Pointer));

        let array2d_type = pointer_type.base.get().unwrap().upgrade().unwrap();
        assert_eq!(array2d_type.name, "String[][]");

        let array_type = array2d_type.base.get().unwrap().upgrade().unwrap();
        assert_eq!(array_type.name, "String[]");

        let string_type = array_type.base.get().unwrap().upgrade().unwrap();
        assert_eq!(string_type.name, "String");
    }

    #[test]
    fn test_generic_instance_with_multiple_args() {
        let test_identity = AssemblyIdentity::parse("TestAssembly, Version=1.0.0.0").unwrap();
        let registry = Arc::new(TypeRegistry::new(test_identity).unwrap());

        // Create Dictionary<TKey, TValue> type
        let dict_token = Token::new(0x01000555);
        let dict_type = registry
            .get_or_create_type(&CompleteTypeSpec {
                token_init: Some(dict_token),
                flavor: CilFlavor::Class,
                namespace: "System.Collections.Generic".to_string(),
                name: "Dictionary`2".to_string(),
                source: TypeSource::Unknown,
                generic_args: None,
                base_type: None,
                flags: None,
            })
            .unwrap();

        let key_param = Arc::new(GenericParam {
            token: Token::new(0x2A000002),
            number: 0,
            flags: 0,
            owner: OnceLock::new(),
            name: "TKey".to_string(),
            constraints: Arc::new(boxcar::Vec::new()),
            rid: 0,
            offset: 0,
            custom_attributes: Arc::new(boxcar::Vec::new()),
        });

        let value_param = Arc::new(GenericParam {
            token: Token::new(0x2A000003),
            number: 1,
            flags: 0,
            owner: OnceLock::new(),
            name: "TValue".to_string(),
            constraints: Arc::new(boxcar::Vec::new()),
            rid: 1,
            offset: 1,
            custom_attributes: Arc::new(boxcar::Vec::new()),
        });

        dict_type.generic_params.push(key_param);
        dict_type.generic_params.push(value_param);

        // Create a Dictionary<string, int> instance
        let dict_instance = TypeBuilder::new(registry.clone())
            .with_source(TypeSource::Unknown)
            .class("System.Collections.Generic", "Dictionary`2")
            .unwrap()
            .generic_instance(2, |registry| {
                let string_type = registry.get_primitive(CilPrimitiveKind::String).unwrap();
                let int_type = registry.get_primitive(CilPrimitiveKind::I4).unwrap();
                Ok(vec![string_type, int_type])
            })
            .unwrap()
            .build()
            .unwrap();

        assert_eq!(dict_instance.name, "Dictionary`2");
        assert!(matches!(
            *dict_instance.flavor(),
            CilFlavor::GenericInstance
        ));

        assert_eq!(dict_instance.generic_args.count(), 2);
        assert_eq!(
            dict_instance.generic_args[0].generic_args[0]
                .name()
                .unwrap(),
            "String"
        );
        assert_eq!(
            dict_instance.generic_args[1].generic_args[0]
                .name()
                .unwrap(),
            "Int32"
        );

        // With the simplified approach, we only store the resolved types
        // The order corresponds to the generic parameter order (0=TKey, 1=TValue)
        assert_eq!(
            dict_instance.generic_args[0].generic_args[0]
                .name()
                .unwrap(),
            "String"
        ); // TKey -> String
        assert_eq!(
            dict_instance.generic_args[1].generic_args[0]
                .name()
                .unwrap(),
            "Int32"
        ); // TValue -> Int32
    }
}