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
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
//! Binary signature parser implementation for .NET metadata signatures.
//!
//! This module provides the core parsing engine for all .NET signature types according to
//! the ECMA-335 specification. The parser handles the binary blob format used to encode
//! type information, method signatures, and other metadata elements in .NET assemblies.
//!
//! # Parser Architecture
//!
//! The signature parser is built around a single [`SignatureParser`] struct that maintains
//! parsing state and provides methods for extracting different signature types from binary
//! data. The parser uses an iterative stack-based approach to handle complex nested types while
//! maintaining protection against malformed data and excessive nesting depth.
//!
//! ## Core Components
//!
//! - **Binary Reader**: Low-level byte stream processing with compressed integer support
//! - **Type Parser**: Iterative type signature parsing with nesting depth limiting
//! - **Custom Modifier Handler**: Support for modreq/modopt type annotations
//! - **Token Resolution**: Compressed metadata token decoding
//! - **Error Recovery**: Comprehensive error reporting with context information
//!
//! # Supported Signature Types
//!
//! ## Method Signatures (`MethodDefSig`, `MethodRefSig`, `StandAloneMethodSig`)
//! - Standard managed calling conventions (DEFAULT, HASTHIS, `EXPLICIT_THIS`)
//! - Platform invoke calling conventions (C, STDCALL, THISCALL, FASTCALL)
//! - Variable argument signatures (VARARG with sentinel markers)
//! - Generic method signatures with type parameter counts
//! - Parameter lists with byref and custom modifiers
//!
//! ## Field Signatures
//! - Simple field type declarations
//! - Custom modifiers (modreq/modopt) for interop scenarios
//! - Complex field types including arrays, pointers, and generic instantiations
//!
//! ## Property Signatures  
//! - Instance and static property declarations
//! - Indexed properties with parameter lists
//! - Custom modifiers on property types and parameters
//!
//! ## Local Variable Signatures
//! - Method local variable type lists
//! - Pinned variables for unsafe code and interop
//! - `ByRef` locals for reference semantics
//! - `TypedByRef` for reflection scenarios
//!
//! ## Type Specification Signatures
//! - Generic type instantiations (List<T>, Dictionary<K,V>)
//! - Complex array types with bounds and dimensions
//! - Pointer and managed reference types
//! - Function pointer signatures
//!
//! ## Method Specification Signatures
//! - Generic method instantiation type arguments
//! - Type argument lists for method calls
//! - Constraint validation support
//!
//! # Binary Format Details
//!
//! ## Element Type Encoding
//! Primitive types are encoded as single bytes according to ECMA-335:
//! ```text
//! 0x01: VOID       0x08: I4         0x0E: STRING
//! 0x02: BOOLEAN    0x09: U4         0x0F: PTR
//! 0x03: CHAR       0x0A: I8         0x10: BYREF
//! 0x04: I1         0x0B: U8         0x11: VALUETYPE
//! 0x05: U1         0x0C: R4         0x12: CLASS
//! 0x06: I2         0x0D: R8         0x13: VAR
//! 0x07: U2         0x1C: OBJECT     0x1E: MVAR
//! ```
//!
//! ## Calling Convention Flags
//! Method signatures start with calling convention bytes:
//! ```text
//! 0x00: DEFAULT      0x20: HASTHIS
//! 0x01: C            0x40: EXPLICITTHIS  
//! 0x02: STDCALL      0x10: GENERIC
//! 0x03: THISCALL     0x05: VARARG
//! 0x04: FASTCALL
//! ```
//!
//! ## Compressed Integer Encoding
//! Counts and indices use variable-length encoding:
//! - 0x00-0x7F: Single byte (0-127)
//! - 0x80-0xBF: Two bytes (128-16383)
//! - 0xC0-0xFF: Four bytes (16384+)
//!
//! # Security and Safety
//!
//! ## Nesting Depth Protection
//! The parser includes protection against stack overflow from malformed signatures:
//! - Maximum nesting depth of 10,000 levels using iterative parsing
//! - Explicit stack-based processing prevents call stack exhaustion
//! - Early termination on depth limit exceeded
//! - Clear error reporting for nesting depth limits
//!
//! ## Buffer Boundary Checking
//! All data access includes bounds checking:
//! - No unchecked array access or pointer arithmetic
//! - Graceful handling of truncated signature data
//! - Clear error messages for malformed input
//!
//! ## Error Handling
//! Comprehensive error reporting for analysis scenarios:
//! - Specific error types for different failure modes
//! - Context information including byte positions
//! - Recovery suggestions for common issues
//!
//! # References
//!
//! - **ECMA-335, Partition II, Section 23.2**: Blobs and signature formats
//! - **ECMA-335, Partition II, Section 23.1**: Metadata validation rules
//! - **`CoreCLR` sigparse.cpp**: Reference implementation patterns
//! - **.NET Runtime Documentation**: Implementation notes and edge cases

use crate::{
    file::parser::Parser,
    metadata::{
        signatures::{
            CustomModifier, SignatureArray, SignatureField, SignatureLocalVariable,
            SignatureLocalVariables, SignatureMethod, SignatureMethodSpec, SignatureParameter,
            SignaturePointer, SignatureProperty, SignatureSzArray, SignatureTypeSpec,
            TypeSignature,
        },
        typesystem::{ArrayDimensions, ELEMENT_TYPE},
    },
    Error::DepthLimitExceeded,
    Result,
};

/// Signature marker bytes as defined in ECMA-335 II.23.2.
///
/// These constants identify the signature type at the start of a signature blob.
/// Note: These overlap numerically with ELEMENT_TYPE but have different semantic meaning
/// in the context of signature headers vs type encoding.
#[allow(non_snake_case)]
pub mod SIGNATURE_HEADER {
    /// Field signature header (ECMA-335 II.23.2.4)
    pub const FIELD: u8 = 0x06;
    /// Local variable signature header (ECMA-335 II.23.2.6)
    pub const LOCAL_SIG: u8 = 0x07;
    /// Property signature header flag (ECMA-335 II.23.2.5)
    pub const PROPERTY: u8 = 0x08;
    /// Method specification signature header (ECMA-335 II.23.2.15)
    pub const GENRICINST: u8 = 0x0A;
}

/// Calling convention flags as defined in ECMA-335 II.23.2.1 for **method signature encoding**.
///
/// These constants are used to decode the calling convention byte in method signatures
/// stored in the blob heap. The low 4 bits (0x0F mask) encode the calling convention kind,
/// while the high bits encode flags like HASTHIS, EXPLICITTHIS, and GENERIC.
///
/// **Important**: These are distinct from [`crate::metadata::tables::PInvokeAttributes`] constants,
/// which use a different encoding (0x0100-0x0500 range) for P/Invoke calling conventions in the
/// ImplMap metadata table. This module is for signature parsing, not P/Invoke metadata.
#[allow(non_snake_case)]
pub mod CALLING_CONVENTION {
    /// Default managed calling convention
    pub const DEFAULT: u8 = 0x00;
    /// C-style calling convention (cdecl)
    pub const C: u8 = 0x01;
    /// Standard calling convention (stdcall)
    pub const STDCALL: u8 = 0x02;
    /// This calling convention (thiscall)
    pub const THISCALL: u8 = 0x03;
    /// Fast calling convention (fastcall)
    pub const FASTCALL: u8 = 0x04;
    /// Variable argument calling convention
    pub const VARARG: u8 = 0x05;

    /// Mask for extracting the calling convention kind from the convention byte
    pub const KIND_MASK: u8 = 0x0F;
    /// Flag indicating method has generic parameters
    pub const GENERIC: u8 = 0x10;
    /// Flag indicating method has implicit 'this' parameter
    pub const HASTHIS: u8 = 0x20;
    /// Flag indicating 'this' parameter is explicitly in the signature
    pub const EXPLICITTHIS: u8 = 0x40;
}

/// Maximum nesting depth for signature parsing to prevent stack overflow.
///
/// This limit protects against malformed signatures that could cause excessive memory usage
/// through circular type references or deeply nested generic types. The iterative parser
/// uses an explicit stack which is tracked against this limit.
///
/// The limit of 10,000 levels accommodates even the most complex real-world .NET assemblies
/// with deep generic hierarchies while still preventing resource exhaustion.
const MAX_NESTING_DEPTH: usize = 1000;

/// Maximum number of array dimensions allowed in a signature.
///
/// .NET supports multi-dimensional arrays, but reasonable limits prevent memory exhaustion
/// attacks. 32 dimensions is far beyond any practical use case.
const MAX_ARRAY_DIMENSIONS: u32 = 32;

/// Maximum number of parameters in a method or property signature.
///
/// Most methods have fewer than 10 parameters. 1024 accommodates extreme edge cases
/// while preventing allocation bombs from malformed signatures.
const MAX_SIGNATURE_PARAMS: u32 = 1024;

/// Maximum number of generic type arguments.
///
/// Generic instantiations like List<T> rarely exceed a handful of type arguments.
/// 256 provides headroom for complex scenarios while preventing abuse.
const MAX_GENERIC_ARGS: u32 = 256;

/// Maximum number of local variables in a method.
///
/// While some generated code may have many locals, 65536 is a reasonable upper bound
/// that prevents allocation attacks while supporting legitimate complex methods.
const MAX_LOCAL_VARIABLES: u32 = 65536;

/// Binary signature parser for all .NET metadata signature types according to ECMA-335.
///
/// `SignatureParser` provides a stateful parser for extracting type information from the
/// binary blob format used in .NET assembly metadata. The parser handles all signature
/// types defined in ECMA-335 and includes protection against malformed data, infinite
/// recursion, and buffer overruns.
///
/// # Parser State
///
/// The parser maintains internal state during parsing operations:
/// - **Binary Position**: Current read position in the signature blob
/// - **Recursion Depth**: Current nesting level for recursive type parsing
/// - **Error Context**: Information for meaningful error reporting
///
/// # Thread Safety
///
/// `SignatureParser` is not thread-safe and should not be shared across threads.
/// Create separate parser instances for concurrent signature parsing operations.
///
/// # Usage Pattern
///
/// The parser is designed for single-use parsing of individual signatures. Do not
/// reuse parser instances for multiple signatures as this may lead to incorrect
/// results due to retained internal state.
///
/// # Examples
///
/// ## Basic Method Signature Parsing
///
/// ```rust
/// use dotscope::metadata::signatures::SignatureParser;
///
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// // Parse a simple instance method: void Method(int param)
/// let signature_data = &[
///     0x20, // HASTHIS calling convention
///     0x01, // 1 parameter
///     0x01, // VOID return type  
///     0x08, // I4 (int) parameter type
/// ];
///
/// let mut parser = SignatureParser::new(signature_data);
/// let method_sig = parser.parse_method_signature()?;
///
/// assert!(method_sig.has_this);
/// assert_eq!(method_sig.params.len(), 1);
/// println!("Method has {} parameters", method_sig.params.len());
/// # Ok(())
/// # }
/// ```
///
/// ## Complex Type Parsing
///
/// ```rust
/// use dotscope::metadata::signatures::{SignatureParser, TypeSignature};
///
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// // Parse a generic type instantiation: List<string>
/// let type_data = &[
///     0x15, // GENERICINST  
///     0x12, 0x42, // CLASS token reference
///     0x01, // 1 type argument
///     0x0E, // STRING type argument
/// ];
///
/// let mut parser = SignatureParser::new(type_data);
/// let type_sig = parser.parse_type_spec_signature()?;
///
/// if let TypeSignature::GenericInst(_, args) = &type_sig.base {
///     println!("Generic type with {} arguments", args.len());
/// }
/// # Ok(())
/// # }
/// ```
///
/// ## Field Signature with Custom Modifiers
///
/// ```rust
/// use dotscope::metadata::signatures::SignatureParser;
///
/// # fn example() -> Result<(), Box<dyn std::error::Error>> {
/// // Parse a field with modifiers: modreq(IsConst) int field
/// let field_data = &[
///     0x06, // FIELD signature marker
///     0x1F, 0x42, // CMOD_REQD with token
///     0x08, // I4 (int) field type
/// ];
///
/// let mut parser = SignatureParser::new(field_data);
/// let field_sig = parser.parse_field_signature()?;
///
/// println!("Field has {} custom modifiers", field_sig.modifiers.len());
/// # Ok(())
/// # }
/// ```
///
/// # Error Handling
///
/// The parser provides detailed error information for various failure scenarios:
///
/// ## Malformed Signature Data
/// - Invalid signature headers or magic bytes
/// - Truncated signature data or unexpected end of stream
/// - Unknown element types or calling conventions
///
/// ## Recursion Limits
/// - Protection against stack overflow from circular references
/// - Clear error messages indicating recursion depth exceeded
/// - Safe termination of parsing operations
///
/// ## Format Violations
/// - ECMA-335 compliance validation
/// - Type consistency checking
/// - Proper error context for debugging
///
/// # Performance Considerations
///
/// - **Linear Parsing**: O(n) time complexity where n is signature length
/// - **Memory Efficiency**: Minimal heap allocation during parsing
/// - **Error Recovery**: Fast failure with detailed error information
/// - **Caching**: Consider caching parsed results for frequently accessed signatures
///
/// # ECMA-335 Compliance
///
/// The parser implements the complete ECMA-335 signature specification:
/// - **Partition II, Section 23.2**: Binary blob and signature formats
/// - **Partition II, Section 7**: Type system fundamentals
/// - **Partition I, Section 8**: Common Type System (CTS) integration
/// - **All signature types**: Method, Field, Property, `LocalVar`, `TypeSpec`, `MethodSpec`
pub struct SignatureParser<'a> {
    /// Binary data parser for reading signature bytes
    parser: Parser<'a>,
}

impl<'a> SignatureParser<'a> {
    /// Create a new signature parser for the given binary signature data.
    ///
    /// Initializes a new parser instance with the provided signature blob data.
    /// The parser starts at the beginning of the data and maintains internal
    /// state for tracking parsing progress and recursion depth.
    ///
    /// # Parameters
    /// - `data`: Binary signature data from a .NET assembly's blob heap
    ///
    /// # Returns
    /// A new `SignatureParser` instance ready for parsing operations.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::metadata::signatures::SignatureParser;
    ///
    /// // Create parser for a simple method signature
    /// let signature_data = &[0x00, 0x00, 0x01]; // DEFAULT, 0 params, VOID
    /// let parser = SignatureParser::new(signature_data);
    /// ```
    ///
    /// # Important Notes
    ///
    /// - **Single Use**: Do not reuse parser instances for multiple signatures
    /// - **Thread Safety**: Not thread-safe, create separate instances for concurrent use
    /// - **Data Lifetime**: Parser borrows the input data, ensure it remains valid
    /// - **State Management**: Parser maintains internal state, reset not supported
    #[must_use]
    pub fn new(data: &'a [u8]) -> Self {
        SignatureParser {
            parser: Parser::new(data),
        }
    }

    /// Parse a single type signature from the current position in the signature blob.
    ///
    /// This is the core type parsing method that handles all .NET type encodings
    /// according to ECMA-335. It uses recursive descent to parse complex nested
    /// types while maintaining protection against infinite recursion.
    ///
    /// # Type Categories Supported
    ///
    /// ## Primitive Types
    /// - **Void**: `void` (`ELEMENT_TYPE_VOID`)
    /// - **Integers**: `bool`, `char`, `sbyte`, `byte`, `short`, `ushort`, `int`, `uint`, `long`, `ulong`
    /// - **Floating Point**: `float`, `double`
    /// - **Reference Types**: `string`, `object`
    /// - **Platform Types**: `IntPtr`, `UIntPtr`
    ///
    /// ## Complex Types
    /// - **Arrays**: Single and multi-dimensional arrays with bounds
    /// - **Pointers**: Unmanaged pointer types (`T*`)
    /// - **References**: Managed references (`ref T`, `out T`)
    /// - **Generic Types**: Open and closed generic type instantiations
    /// - **Function Pointers**: Delegate and function pointer signatures
    ///
    /// ## Metadata References
    /// - **Class Types**: Reference types from TypeDef/TypeRef tables
    /// - **Value Types**: Value types from TypeDef/TypeRef tables  
    /// - **Generic Parameters**: Type (`T`) and method (`M`) generic parameters
    /// - **Custom Modifiers**: Required and optional custom modifiers
    ///
    /// # Nesting Depth Protection
    ///
    /// The parser uses explicit stack-based processing to prevent call stack overflow from malformed
    /// signatures. The maximum nesting depth is [`MAX_NESTING_DEPTH`] levels.
    ///
    /// # Returns
    /// A [`crate::metadata::signatures::TypeSignature`] representing the parsed type information.
    ///
    /// # Errors
    /// - [`crate::error::Error::DepthLimitExceeded`]: Maximum nesting depth exceeded
    /// - [`crate::Error::Malformed`]: Invalid element type or malformed signature data
    /// - [`crate::error::Error::OutOfBounds`]: Truncated signature data
    ///
    /// # Implementation Notes
    ///
    /// This method implements the complete ECMA-335 type encoding specification
    /// using an iterative stack-based approach. Custom modifiers are parsed inline
    /// and associated with the appropriate type elements.
    fn parse_type(&mut self) -> Result<TypeSignature> {
        /// Work items for the iterative parsing stack
        enum WorkItem {
            /// Parse a type signature and push result
            ParseType,
            /// Seek parser to a specific position
            Seek(usize),
            /// Build PTR from modifiers and base type on stack
            BuildPtr(Vec<CustomModifier>),
            /// Build BYREF from base type on stack
            BuildByRef,
            /// Build ARRAY - needs elem_type, rank, dimensions on stack
            BuildArray {
                rank: u32,
                dimensions: Vec<ArrayDimensions>,
            },
            /// Build GENERICINST - needs base_type and N type_args on stack
            BuildGenericInst { arg_count: u32 },
            /// Build SZARRAY from modifiers and base type on stack
            BuildSzArray(Vec<CustomModifier>),
            /// Build PINNED from base type on stack
            BuildPinned,
        }

        let mut work_stack: Vec<WorkItem> = Vec::new();
        let mut result_stack: Vec<TypeSignature> = Vec::new();

        // Start with parsing the root type
        work_stack.push(WorkItem::ParseType);

        while let Some(work) = work_stack.pop() {
            // Check nesting depth limit
            if work_stack.len() + result_stack.len() > MAX_NESTING_DEPTH {
                return Err(DepthLimitExceeded(MAX_NESTING_DEPTH));
            }

            match work {
                WorkItem::Seek(pos) => {
                    self.parser.seek(pos)?;
                }
                WorkItem::ParseType => {
                    let current_byte = self.parser.read_le::<u8>()?;
                    match current_byte {
                        ELEMENT_TYPE::VOID => result_stack.push(TypeSignature::Void),
                        ELEMENT_TYPE::BOOLEAN => result_stack.push(TypeSignature::Boolean),
                        ELEMENT_TYPE::CHAR => result_stack.push(TypeSignature::Char),
                        ELEMENT_TYPE::I1 => result_stack.push(TypeSignature::I1),
                        ELEMENT_TYPE::U1 => result_stack.push(TypeSignature::U1),
                        ELEMENT_TYPE::I2 => result_stack.push(TypeSignature::I2),
                        ELEMENT_TYPE::U2 => result_stack.push(TypeSignature::U2),
                        ELEMENT_TYPE::I4 => result_stack.push(TypeSignature::I4),
                        ELEMENT_TYPE::U4 => result_stack.push(TypeSignature::U4),
                        ELEMENT_TYPE::I8 => result_stack.push(TypeSignature::I8),
                        ELEMENT_TYPE::U8 => result_stack.push(TypeSignature::U8),
                        ELEMENT_TYPE::R4 => result_stack.push(TypeSignature::R4),
                        ELEMENT_TYPE::R8 => result_stack.push(TypeSignature::R8),
                        ELEMENT_TYPE::STRING => result_stack.push(TypeSignature::String),
                        ELEMENT_TYPE::VALUETYPE => {
                            let token = self.parser.read_compressed_token()?;
                            result_stack.push(TypeSignature::ValueType(token));
                        }
                        ELEMENT_TYPE::CLASS => {
                            let token = self.parser.read_compressed_token()?;
                            result_stack.push(TypeSignature::Class(token));
                        }
                        ELEMENT_TYPE::VAR => {
                            let index = self.parser.read_compressed_uint()?;
                            result_stack.push(TypeSignature::GenericParamType(index));
                        }
                        ELEMENT_TYPE::TYPEDBYREF => result_stack.push(TypeSignature::TypedByRef),
                        ELEMENT_TYPE::I => result_stack.push(TypeSignature::I),
                        ELEMENT_TYPE::U => result_stack.push(TypeSignature::U),
                        ELEMENT_TYPE::FNPTR => {
                            let method_sig = self.parse_method_signature()?;
                            result_stack.push(TypeSignature::FnPtr(Box::new(method_sig)));
                        }
                        ELEMENT_TYPE::OBJECT => result_stack.push(TypeSignature::Object),
                        ELEMENT_TYPE::MVAR => {
                            let index = self.parser.read_compressed_uint()?;
                            result_stack.push(TypeSignature::GenericParamMethod(index));
                        }
                        ELEMENT_TYPE::INTERNAL => result_stack.push(TypeSignature::Internal),
                        ELEMENT_TYPE::MODIFIER => result_stack.push(TypeSignature::Modifier),
                        ELEMENT_TYPE::SENTINEL => result_stack.push(TypeSignature::Sentinel),
                        ELEMENT_TYPE::END => {
                            // END (0x00) marks the end of a list in signatures (ECMA-335 II.23.2).
                            // We treat it as Void to handle padding/terminator bytes gracefully.
                            result_stack.push(TypeSignature::Void);
                        }
                        ELEMENT_TYPE::PTR => {
                            let modifiers = self.parse_custom_mods()?;
                            work_stack.push(WorkItem::BuildPtr(modifiers));
                            work_stack.push(WorkItem::ParseType);
                        }
                        ELEMENT_TYPE::BYREF => {
                            work_stack.push(WorkItem::BuildByRef);
                            work_stack.push(WorkItem::ParseType);
                        }
                        ELEMENT_TYPE::ARRAY => {
                            // Skip element type to read array metadata
                            let elem_pos = self.parser.pos();
                            self.parse_type_simple()?; // Skip element type

                            // Read array metadata
                            let rank = self.parser.read_compressed_uint()?;
                            let num_sizes = self.parser.read_compressed_uint()?;
                            if num_sizes > MAX_ARRAY_DIMENSIONS {
                                return Err(malformed_error!(
                                    "Array signature has too many dimensions: {} (max: {})",
                                    num_sizes,
                                    MAX_ARRAY_DIMENSIONS
                                ));
                            }

                            let mut dimensions: Vec<ArrayDimensions> =
                                Vec::with_capacity(num_sizes as usize);
                            for _ in 0..num_sizes {
                                dimensions.push(ArrayDimensions {
                                    size: Some(self.parser.read_compressed_uint()?),
                                    lower_bound: None,
                                });
                            }

                            let num_lo_bounds = self.parser.read_compressed_uint()?;

                            // Validate that lower bound count doesn't exceed dimensions
                            // ECMA-335 II.23.2.13: NumLoBouns can be greater than NumSizes
                            // but each lower bound should correspond to a rank dimension
                            if num_lo_bounds > rank {
                                return Err(malformed_error!(
                                    "Array signature has more lower bounds ({}) than dimensions (rank {})",
                                    num_lo_bounds,
                                    rank
                                ));
                            }

                            // Extend dimensions array if needed for lower bounds
                            while dimensions.len() < num_lo_bounds as usize {
                                dimensions.push(ArrayDimensions {
                                    size: None,
                                    lower_bound: None,
                                });
                            }

                            for i in 0..num_lo_bounds {
                                if let Some(dimension) = dimensions.get_mut(i as usize) {
                                    dimension.lower_bound =
                                        Some(self.parser.read_compressed_uint()?);
                                }
                            }

                            // Reset position to parse element type properly
                            self.parser.seek(elem_pos)?;

                            // Schedule: build array after parsing element type
                            work_stack.push(WorkItem::BuildArray { rank, dimensions });
                            work_stack.push(WorkItem::ParseType);
                        }
                        ELEMENT_TYPE::GENERICINST => {
                            let peek_byte = self.parser.peek_byte()?;
                            if peek_byte != 0x12 && peek_byte != 0x11 {
                                return Err(malformed_error!(
                                    "GENERICINST - Next byte is not TYPE_CLASS or TYPE_VALUE - {}",
                                    peek_byte
                                ));
                            }

                            // Save position, parse base type to skip it, read arg_count
                            let base_pos = self.parser.pos();
                            self.parse_type_simple()?;
                            let arg_count = self.parser.read_compressed_uint()?;
                            if arg_count > MAX_GENERIC_ARGS {
                                return Err(malformed_error!(
                                    "Generic instantiation has too many type arguments: {} (max: {})",
                                    arg_count,
                                    MAX_GENERIC_ARGS
                                ));
                            }

                            let args_pos = self.parser.pos();

                            // Reset to base to parse it properly
                            self.parser.seek(base_pos)?;

                            work_stack.push(WorkItem::BuildGenericInst { arg_count });
                            // Parse type args in reverse order
                            for _ in 0..arg_count {
                                work_stack.push(WorkItem::ParseType);
                            }
                            // Seek to args position before parsing type args
                            work_stack.push(WorkItem::Seek(args_pos));
                            // Parse base type first
                            work_stack.push(WorkItem::ParseType);
                        }
                        ELEMENT_TYPE::SZARRAY => {
                            let modifiers = self.parse_custom_mods()?;
                            work_stack.push(WorkItem::BuildSzArray(modifiers));
                            work_stack.push(WorkItem::ParseType);
                        }
                        ELEMENT_TYPE::CMOD_REQD => {
                            // We consumed the CMOD_REQD byte, go back so parse_custom_mods can handle it
                            self.parser.seek(self.parser.pos() - 1)?;
                            let modifiers = self.parse_custom_mods()?;
                            result_stack.push(TypeSignature::ModifiedRequired(modifiers));
                        }
                        ELEMENT_TYPE::CMOD_OPT => {
                            // We consumed the CMOD_OPT byte, go back so parse_custom_mods can handle it
                            self.parser.seek(self.parser.pos() - 1)?;
                            let modifiers = self.parse_custom_mods()?;
                            result_stack.push(TypeSignature::ModifiedOptional(modifiers));
                        }
                        ELEMENT_TYPE::PINNED => {
                            work_stack.push(WorkItem::BuildPinned);
                            work_stack.push(WorkItem::ParseType);
                        }
                        _ => {
                            return Err(malformed_error!(
                                "Unsupported ELEMENT_TYPE - {}",
                                current_byte
                            ));
                        }
                    }
                }
                WorkItem::BuildPtr(modifiers) => {
                    let base_type = result_stack
                        .pop()
                        .ok_or_else(|| malformed_error!("Missing base type for PTR"))?;
                    result_stack.push(TypeSignature::Ptr(SignaturePointer {
                        modifiers,
                        base: Box::new(base_type),
                    }));
                }
                WorkItem::BuildByRef => {
                    let base_type = result_stack
                        .pop()
                        .ok_or_else(|| malformed_error!("Missing base type for BYREF"))?;
                    result_stack.push(TypeSignature::ByRef(Box::new(base_type)));
                }
                WorkItem::BuildArray { rank, dimensions } => {
                    let elem_type = result_stack
                        .pop()
                        .ok_or_else(|| malformed_error!("Missing element type for ARRAY"))?;
                    result_stack.push(TypeSignature::Array(SignatureArray {
                        base: Box::new(elem_type),
                        rank,
                        dimensions,
                    }));
                }
                WorkItem::BuildGenericInst { arg_count } => {
                    // Stack has: base_type, arg1, arg2, ..., argN (top is argN)
                    // We need to pop argN...arg1 in reverse, then base_type
                    if result_stack.len() < (arg_count as usize + 1) {
                        return Err(malformed_error!(
                            "Insufficient types on stack for GENERICINST"
                        ));
                    }

                    // Pop type args in reverse order (argN, argN-1, ..., arg1)
                    let mut type_args = Vec::with_capacity(arg_count as usize);
                    for _ in 0..arg_count {
                        type_args.push(
                            result_stack.pop().ok_or_else(|| {
                                malformed_error!("Missing type arg for GENERICINST")
                            })?,
                        );
                    }
                    type_args.reverse(); // Reverse to get correct order (arg1, arg2, ..., argN)

                    let base_type = result_stack
                        .pop()
                        .ok_or_else(|| malformed_error!("Missing base type for GENERICINST"))?;

                    result_stack.push(TypeSignature::GenericInst(Box::new(base_type), type_args));
                }
                WorkItem::BuildSzArray(modifiers) => {
                    let base_type = result_stack
                        .pop()
                        .ok_or_else(|| malformed_error!("Missing base type for SZARRAY"))?;
                    result_stack.push(TypeSignature::SzArray(SignatureSzArray {
                        modifiers,
                        base: Box::new(base_type),
                    }));
                }
                WorkItem::BuildPinned => {
                    let base_type = result_stack
                        .pop()
                        .ok_or_else(|| malformed_error!("Missing base type for PINNED"))?;
                    result_stack.push(TypeSignature::Pinned(Box::new(base_type)));
                }
            }
        }

        if result_stack.len() != 1 {
            return Err(malformed_error!(
                "Internal error: expected 1 type on stack, got {}",
                result_stack.len()
            ));
        }

        result_stack
            .pop()
            .ok_or_else(|| malformed_error!("internal: result stack empty after validation"))
    }

    /// Helper method to parse a type signature without building the result (for lookahead).
    /// This is used to skip over types when we need to read metadata that comes after them.
    fn parse_type_simple(&mut self) -> Result<()> {
        let current_byte = self.parser.read_le::<u8>()?;
        match current_byte {
            ELEMENT_TYPE::VOID
            | ELEMENT_TYPE::BOOLEAN
            | ELEMENT_TYPE::CHAR
            | ELEMENT_TYPE::I1
            | ELEMENT_TYPE::U1
            | ELEMENT_TYPE::I2
            | ELEMENT_TYPE::U2
            | ELEMENT_TYPE::I4
            | ELEMENT_TYPE::U4
            | ELEMENT_TYPE::I8
            | ELEMENT_TYPE::U8
            | ELEMENT_TYPE::R4
            | ELEMENT_TYPE::R8
            | ELEMENT_TYPE::STRING
            | ELEMENT_TYPE::TYPEDBYREF
            | ELEMENT_TYPE::I
            | ELEMENT_TYPE::U
            | ELEMENT_TYPE::OBJECT
            | ELEMENT_TYPE::INTERNAL
            | ELEMENT_TYPE::MODIFIER
            | ELEMENT_TYPE::SENTINEL
            | ELEMENT_TYPE::END => Ok(()),
            ELEMENT_TYPE::VALUETYPE | ELEMENT_TYPE::CLASS => {
                self.parser.read_compressed_token()?;
                Ok(())
            }
            ELEMENT_TYPE::VAR | ELEMENT_TYPE::MVAR => {
                self.parser.read_compressed_uint()?;
                Ok(())
            }
            ELEMENT_TYPE::PTR | ELEMENT_TYPE::SZARRAY => {
                let _ = self.parse_custom_mods()?;
                self.parse_type_simple()
            }
            ELEMENT_TYPE::BYREF | ELEMENT_TYPE::PINNED => self.parse_type_simple(),
            ELEMENT_TYPE::ARRAY => {
                self.parse_type_simple()?;
                let _rank = self.parser.read_compressed_uint()?;
                let num_sizes = self.parser.read_compressed_uint()?;
                for _ in 0..num_sizes {
                    self.parser.read_compressed_uint()?;
                }
                let num_lo_bounds = self.parser.read_compressed_uint()?;
                for _ in 0..num_lo_bounds {
                    self.parser.read_compressed_uint()?;
                }
                Ok(())
            }
            ELEMENT_TYPE::GENERICINST => {
                self.parse_type_simple()?;
                let arg_count = self.parser.read_compressed_uint()?;
                for _ in 0..arg_count {
                    self.parse_type_simple()?;
                }
                Ok(())
            }
            ELEMENT_TYPE::FNPTR => {
                let _ = self.parse_method_signature()?;
                Ok(())
            }
            ELEMENT_TYPE::CMOD_REQD | ELEMENT_TYPE::CMOD_OPT => {
                self.parser.seek(self.parser.pos() - 1)?;
                let _ = self.parse_custom_mods()?;
                Ok(())
            }
            _ => Err(malformed_error!(
                "Unsupported ELEMENT_TYPE in simple parse - {}",
                current_byte
            )),
        }
    }

    /// Parse custom modifiers (modreq/modopt) from the current signature position.
    ///
    /// Custom modifiers provide additional type information for advanced scenarios such as
    /// C++/CLI interop, const/volatile semantics, and platform-specific type constraints.
    /// This method parses a sequence of modifier tokens that appear before type information.
    ///
    /// # Modifier Types
    ///
    /// ## Required Modifiers (modreq)
    /// - **`CMOD_REQD` (0x1F)**: Required for type identity and compatibility
    /// - **Usage**: Platform interop, const fields, security annotations
    /// - **Impact**: Affects type identity for assignment and method resolution
    ///
    /// ## Optional Modifiers (modopt)  
    /// - **`CMOD_OPT` (0x20)**: Optional hints that don't affect type identity
    /// - **Usage**: Optimization hints, debugging information, tool annotations
    /// - **Impact**: Preserved for metadata consumers but don't affect runtime behavior
    ///
    /// # Binary Format
    ///
    /// Custom modifiers are encoded as:
    /// ```text
    /// [ModifierType] [CompressedToken]
    /// ```
    /// Where `ModifierType` is 0x1F (required) or 0x20 (optional), followed by
    /// a compressed metadata token referencing the modifier type.
    ///
    /// # Examples
    ///
    /// ```text
    /// 0x1F 0x42      // modreq(TypeRef:0x1B000010)  
    /// 0x20 0x35      // modopt(TypeRef:0x100000D)
    /// 0x1F 0x15      // modreq(TypeRef:0x1B000005)
    /// 0x08           // I4 (base type follows modifiers)
    /// ```
    ///
    /// # Returns
    /// A vector of [`crate::metadata::token::Token`] references to the modifier types.
    /// The vector is empty if no custom modifiers are present.
    ///
    /// # Errors
    /// - [`crate::Error::Malformed`]: Invalid compressed token encoding
    /// - [`crate::error::Error::OutOfBounds`]: Truncated modifier data
    ///
    /// # Performance Notes
    /// - Modifiers are relatively uncommon in most .NET code
    /// - Vector allocation is avoided when no modifiers are present
    /// - Parsing cost is linear in the number of modifiers
    fn parse_custom_mods(&mut self) -> Result<Vec<CustomModifier>> {
        let mut mods = Vec::new();

        while self.parser.has_more_data() {
            let is_required = match self.parser.peek_byte()? {
                0x20 => false,
                0x1F => true,
                _ => break,
            };

            self.parser.advance()?;

            let modifier_token = self.parser.read_compressed_token()?;
            mods.push(CustomModifier {
                is_required,
                modifier_type: modifier_token,
            });
        }

        Ok(mods)
    }

    /// Parse a method parameter or return type with custom modifiers and byref semantics.
    ///
    /// This method parses a single parameter specification that includes optional custom
    /// modifiers, byref semantics, and the parameter type. Parameters and return types
    /// share the same binary format in .NET signatures.
    ///
    /// # Parameter Format
    ///
    /// Parameters are encoded as:
    /// ```text
    /// [CustomModifier*] [BYREF?] [Type]
    /// ```
    ///
    /// ## Custom Modifiers
    /// Zero or more custom modifiers (modreq/modopt) that apply to the parameter type.
    /// These provide additional type information for interop and advanced scenarios.
    ///
    /// ## `ByRef` Semantics
    /// - **BYREF (0x10)**: Indicates reference parameter semantics (`ref`, `out`, `in`)
    /// - **Reference Types**: Creates a reference to the reference (double indirection)
    /// - **Value Types**: Passes by reference instead of by value
    /// - **Null References**: `ByRef` parameters cannot be null references
    ///
    /// ## Parameter Types
    /// Any valid .NET type including primitives, classes, value types, arrays,
    /// generic instantiations, and complex nested types.
    ///
    /// # Examples
    ///
    /// ## Simple Value Parameter
    /// ```text
    /// 0x08           // I4 (int parameter)
    /// ```
    ///
    /// ## Reference Parameter
    /// ```text
    /// 0x10 0x08      // BYREF I4 (ref int parameter)
    /// ```
    ///
    /// ## Parameter with Custom Modifiers
    /// ```text
    /// 0x1F 0x42      // modreq(IsConst)
    /// 0x20 0x35      // modopt(Hint)  
    /// 0x10           // BYREF
    /// 0x0E           // STRING (ref string with modifiers)
    /// ```
    ///
    /// # Returns
    /// A [`crate::metadata::signatures::SignatureParameter`] containing:
    /// - Custom modifier tokens
    /// - `ByRef` flag for reference semantics
    /// - Complete type signature information
    ///
    /// # Errors
    /// - [`crate::Error::Malformed`]: Invalid parameter encoding
    /// - [`crate::Error::DepthLimitExceeded`]: Parameter type parsing exceeds nesting depth limit
    /// - [`crate::error::Error::OutOfBounds`]: Truncated parameter data
    ///
    /// # Usage Notes
    ///
    /// This method is used for both method parameters and return types since they
    /// share the same binary encoding format. The calling context determines the
    /// semantic interpretation of the parsed parameter information.
    fn parse_param(&mut self) -> Result<SignatureParameter> {
        let custom_mods = self.parse_custom_mods()?;

        let mut by_ref = false;
        if self.parser.peek_byte()? == 0x10 {
            self.parser.advance()?;
            by_ref = true;
        }

        Ok(SignatureParameter {
            modifiers: custom_mods,
            by_ref,
            base: self.parse_type()?,
        })
    }

    /// Parse a complete method signature from the signature blob.
    ///
    /// Parses method signatures for method definitions, method references, and standalone
    /// method signatures according to ECMA-335 specification. Method signatures encode
    /// calling conventions, parameter types, return types, and generic information.
    ///
    /// # Method Signature Format
    ///
    /// Method signatures follow this binary structure:
    /// ```text
    /// [CallingConvention] [GenericParamCount?] [ParamCount] [ReturnType] [Param1] [Param2] ...
    /// ```
    ///
    /// ## Calling Convention Byte
    /// The first byte encodes calling convention and method flags:
    /// ```text
    /// Bit 0-3: Calling convention
    ///   0x00: DEFAULT (standard managed)
    ///   0x01: C (cdecl for P/Invoke)
    ///   0x02: STDCALL (stdcall for P/Invoke)  
    ///   0x03: THISCALL (thiscall for P/Invoke)
    ///   0x04: FASTCALL (fastcall for P/Invoke)
    ///   0x05: VARARG (variable arguments)
    ///
    /// Bit 4: GENERIC (0x10) - method has generic parameters
    /// Bit 5: HASTHIS (0x20) - method has implicit 'this' parameter
    /// Bit 6: EXPLICITTHIS (0x40) - 'this' parameter is explicit
    /// ```
    ///
    /// ## Generic Parameter Count
    /// If GENERIC flag is set, the next compressed integer specifies the number
    /// of generic type parameters for the method.
    ///
    /// ## Parameter Processing
    /// Parameters are parsed sequentially, with special handling for:
    /// - **Return Type**: Always the first parameter parsed
    /// - **Regular Parameters**: Method parameters in declaration order  
    /// - **SENTINEL (0x41)**: Marks transition to variable arguments
    /// - **Variable Arguments**: Additional parameters for VARARG methods
    ///
    /// # Supported Method Types
    ///
    /// ## Instance Methods
    /// ```csharp
    /// public int Method(string param)  // HASTHIS, 1 param, I4 return, STRING param
    /// ```
    ///
    /// ## Static Methods
    /// ```csharp
    /// public static void Method()      // DEFAULT, 0 params, VOID return
    /// ```
    ///
    /// ## Generic Methods
    /// ```csharp
    /// public T Method<T>(T item)       // HASTHIS | GENERIC, 1 generic param, 1 param
    /// ```
    ///
    /// ## Variable Argument Methods
    /// ```csharp
    /// public void Method(int a, __arglist)  // VARARG with sentinel
    /// ```
    ///
    /// ## Platform Invoke Methods
    /// ```csharp
    /// [DllImport("kernel32")]
    /// public static extern int GetLastError();  // Various calling conventions
    /// ```
    ///
    /// # Examples
    ///
    /// ## Simple Static Method
    /// ```text
    /// 0x00           // DEFAULT calling convention
    /// 0x00           // 0 parameters
    /// 0x01           // VOID return type
    /// ```
    ///
    /// ## Instance Method with Parameters
    /// ```text
    /// 0x20           // HASTHIS calling convention
    /// 0x02           // 2 parameters
    /// 0x08           // I4 (int) return type
    /// 0x0E           // STRING first parameter
    /// 0x10 0x08      // BYREF I4 second parameter (ref int)
    /// ```
    ///
    /// ## Generic Method
    /// ```text
    /// 0x30           // HASTHIS | GENERIC
    /// 0x01           // 1 generic parameter (T)
    /// 0x01           // 1 method parameter
    /// 0x13 0x00      // VAR 0 return type (T)
    /// 0x13 0x00      // VAR 0 parameter type (T)
    /// ```
    ///
    /// # Returns
    /// A [`crate::metadata::signatures::SignatureMethod`] containing:
    /// - Calling convention flags and generic parameter count
    /// - Return type information with custom modifiers
    /// - Parameter list with types and modifiers
    /// - Variable argument list (if applicable)
    ///
    /// # Errors
    /// - [`crate::Error::Malformed`]: Invalid calling convention or parameter encoding
    /// - [`crate::Error::DepthLimitExceeded`]: Parameter type parsing exceeds nesting depth limit
    /// - [`crate::error::Error::OutOfBounds`]: Truncated signature data
    ///
    /// # Performance Notes
    /// - Parameter vectors are pre-allocated based on parameter count
    /// - Calling convention flags are decoded using bitwise operations
    /// - Generic parameter count is only parsed when GENERIC flag is set
    ///
    /// # ECMA-335 References
    /// - **Partition II, Section 23.2.1**: `MethodDefSig`
    /// - **Partition II, Section 23.2.2**: `MethodRefSig`
    /// - **Partition II, Section 23.2.3**: `StandAloneMethodSig`
    /// - **Partition I, Section 14.3**: Calling conventions
    ///
    /// # Implementation Notes
    /// This method uses `parse_method_parameters` internally to handle the complex
    /// logic of parsing fixed parameters and optional varargs separated by SENTINEL.
    pub fn parse_method_signature(&mut self) -> Result<SignatureMethod> {
        let convention_byte = self.parser.read_le::<u8>()?;

        // Extract the calling convention kind from the low 4 bits (mask 0x0F)
        // ECMA-335 II.23.2.1: The low 4 bits encode the calling convention
        let calling_convention_kind = convention_byte & CALLING_CONVENTION::KIND_MASK;

        let mut method = SignatureMethod {
            has_this: convention_byte & CALLING_CONVENTION::HASTHIS != 0,
            explicit_this: convention_byte & CALLING_CONVENTION::EXPLICITTHIS != 0,
            default: calling_convention_kind == CALLING_CONVENTION::DEFAULT,
            vararg: calling_convention_kind == CALLING_CONVENTION::VARARG,
            cdecl: calling_convention_kind == CALLING_CONVENTION::C,
            stdcall: calling_convention_kind == CALLING_CONVENTION::STDCALL,
            thiscall: calling_convention_kind == CALLING_CONVENTION::THISCALL,
            fastcall: calling_convention_kind == CALLING_CONVENTION::FASTCALL,
            param_count_generic: if convention_byte & CALLING_CONVENTION::GENERIC != 0 {
                let gen_count = self.parser.read_compressed_uint()?;
                if gen_count > MAX_GENERIC_ARGS {
                    return Err(malformed_error!(
                        "Method signature has too many generic parameters: {} (max: {})",
                        gen_count,
                        MAX_GENERIC_ARGS
                    ));
                }
                gen_count
            } else {
                0
            },
            param_count: {
                let p_count = self.parser.read_compressed_uint()?;
                if p_count > MAX_SIGNATURE_PARAMS {
                    return Err(malformed_error!(
                        "Method signature has too many parameters: {} (max: {})",
                        p_count,
                        MAX_SIGNATURE_PARAMS
                    ));
                }
                p_count
            },
            return_type: self.parse_param()?,
            params: Vec::new(),
            varargs: Vec::new(),
        };

        // Parse fixed parameters and varargs using the helper method
        let (params, varargs) = self.parse_method_parameters(method.param_count)?;
        method.params = params;
        method.varargs = varargs;

        Ok(method)
    }

    /// Parse method parameters, handling both fixed parameters and optional varargs.
    ///
    /// This helper method encapsulates the complex logic of parsing method parameters,
    /// including detection of the SENTINEL marker that separates fixed parameters from
    /// variable arguments in vararg methods.
    ///
    /// # Parameters
    /// - `param_count`: The declared number of fixed parameters in the signature
    ///
    /// # Returns
    /// A tuple containing:
    /// - `Vec<SignatureParameter>`: Fixed parameters
    /// - `Vec<SignatureParameter>`: Variable arguments (empty if not a vararg method)
    ///
    /// # ECMA-335 Reference
    /// According to ECMA-335 II.23.2.1:
    /// - `param_count` only includes fixed parameters, not varargs
    /// - SENTINEL (0x41) separates fixed parameters from varargs
    /// - Varargs continue until END (0x00) or end of data
    fn parse_method_parameters(
        &mut self,
        param_count: u32,
    ) -> Result<(Vec<SignatureParameter>, Vec<SignatureParameter>)> {
        let mut params = Vec::with_capacity(param_count as usize);
        let mut varargs = Vec::new();

        // Parse fixed parameters, watching for SENTINEL marker
        let mut hit_sentinel = false;
        for _ in 0..param_count {
            if self.parser.peek_byte()? == ELEMENT_TYPE::SENTINEL {
                // SENTINEL indicates fixed params are over, vararg list follows
                self.parser.advance()?;
                hit_sentinel = true;
                break;
            }
            params.push(self.parse_param()?);
        }

        // Parse varargs if SENTINEL was encountered
        if hit_sentinel {
            while self.parser.has_more_data() && self.parser.peek_byte()? != ELEMENT_TYPE::END {
                if varargs.len() >= MAX_SIGNATURE_PARAMS as usize {
                    return Err(malformed_error!(
                        "Method signature has too many varargs: {} (max: {})",
                        varargs.len(),
                        MAX_SIGNATURE_PARAMS
                    ));
                }
                varargs.push(self.parse_param()?);
            }
        }

        Ok((params, varargs))
    }

    /// Parse a field signature from the signature blob according to ECMA-335 II.23.2.4.
    ///
    /// Field signatures define the type information for fields in .NET types, including
    /// custom modifiers for advanced scenarios like interop, const semantics, and
    /// platform-specific type constraints.
    ///
    /// # Field Signature Format
    ///
    /// Field signatures follow this binary structure:
    /// ```text
    /// [FIELD] [CustomModifier*] [Type]
    /// ```
    ///
    /// ## Field Signature Header
    /// - **FIELD (0x06)**: Required signature type marker
    /// - **Validation**: Parser verifies the signature starts with 0x06
    /// - **Purpose**: Distinguishes field signatures from other signature types
    ///
    /// ## Custom Modifiers
    /// Zero or more custom modifiers that provide additional type information:
    /// - **modreq**: Required modifiers that affect type identity
    /// - **modopt**: Optional modifiers that provide hints
    /// - **Common Uses**: `volatile`, `const`, interop constraints
    ///
    /// ## Field Types
    /// Any valid .NET type including:
    /// - **Primitive Types**: `int`, `string`, `bool`, etc.
    /// - **Reference Types**: Classes and interfaces  
    /// - **Value Types**: Structs and enums
    /// - **Array Types**: Single and multi-dimensional arrays
    /// - **Generic Types**: Open and closed generic instantiations
    /// - **Pointer Types**: Unmanaged pointers for unsafe scenarios
    ///
    /// # Common Field Scenarios
    ///
    /// ## Simple Field Types
    /// ```csharp
    /// public int counter;           // I4 field
    /// public string name;           // STRING field  
    /// public List<int> items;       // Generic instantiation field
    /// ```
    ///
    /// ## Array Fields
    /// ```csharp
    /// public int[] numbers;         // SZARRAY I4 field
    /// public string[,] matrix;      // ARRAY STRING field with rank 2
    /// ```
    ///
    /// ## Fields with Custom Modifiers
    /// ```csharp
    /// public volatile int flag;     // modreq(IsVolatile) I4 field
    /// public const string Name;     // modreq(IsConst) STRING field
    /// ```
    ///
    /// ## Unsafe Pointer Fields
    /// ```csharp
    /// public unsafe int* ptr;       // PTR I4 field
    /// public unsafe void* handle;   // PTR VOID field
    /// ```
    ///
    /// # Binary Examples
    ///
    /// ## Simple Integer Field
    /// ```text
    /// 0x06           // FIELD signature marker
    /// 0x08           // I4 (int) field type
    /// ```
    ///
    /// ## String Array Field
    /// ```text
    /// 0x06           // FIELD signature marker
    /// 0x1D           // SZARRAY (single-dimensional array)
    /// 0x0E           // STRING element type
    /// ```
    ///
    /// ## Field with Required Modifier
    /// ```text
    /// 0x06           // FIELD signature marker
    /// 0x1F 0x42      // modreq(TypeRef token)
    /// 0x08           // I4 field type with modifier
    /// ```
    ///
    /// ## Generic Field Type
    /// ```text
    /// 0x06           // FIELD signature marker
    /// 0x15           // GENERICINST
    /// 0x12 0x35      // CLASS List<T> token
    /// 0x01           // 1 type argument
    /// 0x08           // I4 type argument (List<int>)
    /// ```
    ///
    /// # Returns
    /// A [`crate::metadata::signatures::SignatureField`] containing:
    /// - Custom modifier token list
    /// - Complete field type information
    /// - Type constraints and annotations
    ///
    /// # Errors
    /// - [`crate::Error::Malformed`]: Invalid field signature header (not 0x06)
    /// - [`crate::Error::DepthLimitExceeded`]: Field type parsing exceeds nesting depth limit
    /// - [`crate::error::Error::OutOfBounds`]: Truncated field signature data
    ///
    /// # Custom Modifier Applications
    ///
    /// Custom modifiers on fields are commonly used for:
    /// - **volatile**: Memory barrier semantics for multithreading
    /// - **const**: Compile-time constant field values
    /// - **Interop**: C++/CLI and platform-specific type constraints
    /// - **Security**: Type-based security and access control annotations
    ///
    /// # Performance Notes
    /// - Field signatures are typically simple and parse quickly
    /// - Custom modifiers add minimal overhead when present
    /// - Complex generic field types may require recursive parsing
    /// - Caching of parsed field signatures is recommended for hot paths
    ///
    /// # ECMA-335 Compliance
    /// This implementation follows ECMA-335 6th Edition, Partition II, Section 23.2.4
    /// for field signature encoding and supports all standard field type scenarios.
    pub fn parse_field_signature(&mut self) -> Result<SignatureField> {
        let head_byte = self.parser.read_le::<u8>()?;
        if head_byte != SIGNATURE_HEADER::FIELD {
            return Err(malformed_error!(
                "SignatureField - invalid start - {} (expected {})",
                head_byte,
                SIGNATURE_HEADER::FIELD
            ));
        }

        let custom_mods = self.parse_custom_mods()?;
        let type_sig = self.parse_type()?;

        Ok(SignatureField {
            modifiers: custom_mods,
            base: type_sig,
        })
    }

    /// Parse a property signature from the signature blob according to ECMA-335 II.23.2.5.
    ///
    /// Property signatures define the type and parameter information for properties,
    /// including simple properties, indexed properties (indexers), and properties
    /// with custom modifiers. Properties in .NET are implemented as methods but
    /// have their own signature format for metadata storage.
    ///
    /// # Property Signature Format
    ///
    /// Property signatures follow this binary structure:
    /// ```text
    /// [PropertyFlags] [ParamCount] [CustomModifier*] [PropertyType] [Param1] [Param2] ...
    /// ```
    ///
    /// ## Property Flags Byte
    /// The first byte encodes property characteristics:
    /// ```text
    /// Bit 3: PROPERTY (0x08) - Required property signature marker
    /// Bit 5: HASTHIS (0x20) - Property belongs to an instance (not static)
    /// Other bits: Reserved and should be zero
    /// ```
    ///
    /// ## Parameter Count
    /// Compressed integer indicating the number of indexer parameters:
    /// - **0**: Simple property (no indexer parameters)
    /// - **N > 0**: Indexed property with N indexer parameters
    ///
    /// ## Property Type
    /// The type of the property value, which can be any valid .NET type.
    /// Custom modifiers may precede the property type for advanced scenarios.
    ///
    /// ## Indexer Parameters
    /// For indexed properties, parameter specifications define the indexer signature.
    /// Each parameter includes type information and optional custom modifiers.
    ///
    /// # Property Categories
    ///
    /// ## Simple Properties
    /// Standard properties with getter and/or setter methods:
    /// ```csharp
    /// public int Count { get; set; }                    // Instance property
    /// public static string DefaultName { get; set; }   // Static property
    /// ```
    ///
    /// ## Indexed Properties (Indexers)
    /// Properties that accept parameters for indexed access:
    /// ```csharp
    /// public string this[int index] { get; set; }       // Single parameter indexer
    /// public T this[int x, int y] { get; set; }         // Multi-parameter indexer
    /// ```
    ///
    /// ## Properties with Custom Modifiers
    /// Properties with additional type constraints or annotations:
    /// ```csharp
    /// public volatile int Flag { get; set; }            // modreq(IsVolatile) property
    /// ```
    ///
    /// # Binary Examples
    ///
    /// ## Simple Instance Property
    /// ```text
    /// 0x28           // PROPERTY | HASTHIS
    /// 0x00           // 0 parameters (not indexed)
    /// 0x08           // I4 (int) property type
    /// ```
    ///
    /// ## Static String Property
    /// ```text
    /// 0x08           // PROPERTY (static, no HASTHIS)
    /// 0x00           // 0 parameters
    /// 0x0E           // STRING property type
    /// ```
    ///
    /// ## Single-Parameter Indexer
    /// ```text
    /// 0x28           // PROPERTY | HASTHIS
    /// 0x01           // 1 indexer parameter
    /// 0x0E           // STRING property type
    /// 0x08           // I4 indexer parameter type
    /// ```
    ///
    /// ## Multi-Parameter Indexer
    /// ```text
    /// 0x28           // PROPERTY | HASTHIS
    /// 0x02           // 2 indexer parameters
    /// 0x1C           // OBJECT property type
    /// 0x08           // I4 first parameter (int x)
    /// 0x08           // I4 second parameter (int y)
    /// ```
    ///
    /// ## Generic Property Type
    /// ```text
    /// 0x28           // PROPERTY | HASTHIS
    /// 0x00           // 0 parameters
    /// 0x15           // GENERICINST
    /// 0x12 0x42      // CLASS List<T> token
    /// 0x01           // 1 type argument
    /// 0x0E           // STRING type argument
    /// ```
    ///
    /// # Returns
    /// A [`crate::metadata::signatures::SignatureProperty`] containing:
    /// - Instance vs. static property indication
    /// - Property type with custom modifiers
    /// - Indexer parameter list (empty for simple properties)
    /// - Complete type and modifier information
    ///
    /// # Errors
    /// - [`crate::Error::Malformed`]: Invalid property signature header (missing PROPERTY bit)
    /// - [`crate::Error::DepthLimitExceeded`]: Property or parameter type parsing exceeds nesting depth limit
    /// - [`crate::error::Error::OutOfBounds`]: Truncated property signature data
    ///
    /// # Indexer Design Patterns
    ///
    /// ## Collection Indexers
    /// ```csharp
    /// public T this[int index] => items[index];         // Array-style access
    /// ```
    ///
    /// ## Dictionary-Style Indexers
    /// ```csharp
    /// public TValue this[TKey key] => dict[key];        // Key-value access
    /// ```
    ///
    /// ## Multi-Dimensional Indexers
    /// ```csharp
    /// public T this[int row, int col] => matrix[row, col];  // Matrix access
    /// ```
    ///
    /// # Performance Notes
    /// - Simple properties parse very quickly with minimal allocations
    /// - Indexed properties require parameter parsing which scales with parameter count
    /// - Generic property types may require recursive type parsing
    /// - Consider caching parsed property signatures for frequently accessed properties
    ///
    /// # Implementation Relationship
    /// Properties are implemented as methods in IL, but property signatures provide
    /// the high-level abstraction for metadata consumers. The actual getter/setter
    /// methods have their own method signatures that reference this property signature.
    ///
    /// # ECMA-335 Compliance
    /// This implementation follows ECMA-335 6th Edition, Partition II, Section 23.2.5
    /// for property signature encoding and supports all standard property scenarios.
    pub fn parse_property_signature(&mut self) -> Result<SignatureProperty> {
        let head_byte = self.parser.read_le::<u8>()?;
        if (head_byte & SIGNATURE_HEADER::PROPERTY) == 0 {
            return Err(malformed_error!(
                "SignatureProperty - invalid start - {} (expected PROPERTY bit {})",
                head_byte,
                SIGNATURE_HEADER::PROPERTY
            ));
        }

        let has_this = (head_byte & CALLING_CONVENTION::HASTHIS) != 0;

        let param_count = self.parser.read_compressed_uint()?;
        if param_count > MAX_SIGNATURE_PARAMS {
            return Err(malformed_error!(
                "Property signature has too many parameters: {} (max: {})",
                param_count,
                MAX_SIGNATURE_PARAMS
            ));
        }

        let custom_mods = self.parse_custom_mods()?;
        let type_sig = self.parse_type()?;

        let mut params = Vec::with_capacity(param_count as usize);
        for _ in 0..param_count {
            params.push(self.parse_param()?);
        }

        Ok(SignatureProperty {
            has_this,
            modifiers: custom_mods,
            base: type_sig,
            params,
        })
    }

    /// Parse a local variable signature from the signature blob according to ECMA-335 II.23.2.6.
    ///
    /// Local variable signatures define the types and constraints for all local variables
    /// within a method body. These signatures are used by the JIT compiler for type
    /// checking, memory management, and garbage collection root tracking.
    ///
    /// # Local Variable Signature Format
    ///
    /// Local variable signatures follow this binary structure:
    /// ```text
    /// [LOCAL_SIG] [Count] [LocalVar1] [LocalVar2] ...
    /// ```
    ///
    /// Each local variable specification can include:
    /// ```text
    /// [CustomModifier*] [PINNED?] [BYREF?] [Type]
    /// ```
    ///
    /// ## Local Variable Signature Header
    /// - **`LOCAL_SIG` (0x07)**: Required signature type marker
    /// - **Count**: Compressed integer specifying number of local variables
    /// - **Validation**: Parser verifies signature starts with 0x07
    ///
    /// ## Local Variable Constraints
    ///
    /// ### PINNED Constraint (0x45)
    /// - **Purpose**: Fixes variable location in memory for interop scenarios
    /// - **Usage**: P/Invoke calls, unsafe code, COM interop
    /// - **GC Impact**: Prevents garbage collector from moving the object
    /// - **Syntax**: `fixed` statement in C#, `pin_ptr` in C++/CLI
    ///
    /// ### BYREF Constraint (0x10)
    /// - **Purpose**: Creates reference semantics for local variables
    /// - **Usage**: `ref` locals, `out` parameters stored in locals
    /// - **Memory**: Variable stores address rather than value
    /// - **Restrictions**: Cannot be null, must point to valid memory
    ///
    /// ### TYPEDBYREF Special Type (0x16)
    /// - **Purpose**: Runtime type information for reflection scenarios
    /// - **Usage**: Advanced reflection, method argument handling
    /// - **Contents**: Type information and object reference pair
    /// - **Restrictions**: Cannot be used with other constraints
    ///
    /// # Local Variable Categories
    ///
    /// ## Simple Local Variables
    /// Standard local variables with primitive or reference types:
    /// ```csharp
    /// int counter;              // I4 local
    /// string message;           // STRING local  
    /// List<int> items;          // Generic instantiation local
    /// ```
    ///
    /// ## Reference Local Variables
    /// Local variables that store references to other variables:
    /// ```csharp
    /// ref int refValue = ref someField;     // BYREF I4 local
    /// ref readonly string refText;          // BYREF STRING local
    /// ```
    ///
    /// ## Pinned Local Variables  
    /// Local variables with fixed memory locations for unsafe scenarios:
    /// ```csharp
    /// fixed (byte* ptr = &array[0]) {       // PINNED PTR local
    ///     // ptr location is fixed during this scope
    /// }
    /// ```
    ///
    /// ## `TypedByRef` Locals
    /// Special locals for advanced reflection scenarios:
    /// ```csharp
    /// __makeref(variable);                  // TYPEDBYREF local
    /// ```
    ///
    /// # Binary Examples
    ///
    /// ## Simple Local Variables
    /// ```text
    /// 0x07           // LOCAL_SIG marker
    /// 0x02           // 2 local variables
    /// 0x08           // I4 (int) first local
    /// 0x0E           // STRING second local
    /// ```
    ///
    /// ## Reference and Pinned Locals
    /// ```text
    /// 0x07           // LOCAL_SIG marker
    /// 0x03           // 3 local variables
    /// 0x10 0x08      // BYREF I4 (ref int)
    /// 0x45 0x0F      // PINNED PTR (pinned pointer)
    /// 0x16           // TYPEDBYREF
    /// ```
    ///
    /// ## Locals with Custom Modifiers
    /// ```text
    /// 0x07           // LOCAL_SIG marker
    /// 0x01           // 1 local variable
    /// 0x1F 0x42      // modreq(IsVolatile)
    /// 0x45           // PINNED constraint
    /// 0x08           // I4 (volatile pinned int)
    /// ```
    ///
    /// ## Complex Generic Local
    /// ```text
    /// 0x07           // LOCAL_SIG marker
    /// 0x01           // 1 local variable
    /// 0x15           // GENERICINST
    /// 0x12 0x35      // CLASS Dictionary<,> token
    /// 0x02           // 2 type arguments
    /// 0x0E           // STRING (TKey)
    /// 0x1C           // OBJECT (TValue)
    /// ```
    ///
    /// # Returns
    /// A [`crate::metadata::signatures::SignatureLocalVariables`] containing:
    /// - Array of local variable specifications
    /// - Type information for each local
    /// - Constraint flags (pinned, byref) for each local
    /// - Custom modifier information
    ///
    /// # Errors
    /// - [`crate::Error::Malformed`]: Invalid local variable signature header (not 0x07)
    /// - [`crate::Error::DepthLimitExceeded`]: Local variable type parsing exceeds nesting depth limit
    /// - [`crate::error::Error::OutOfBounds`]: Truncated local variable signature data
    ///
    /// # Memory Management Implications
    ///
    /// ## Garbage Collection Roots
    /// Local variables containing reference types serve as GC roots:
    /// - **Reference Locals**: Prevent referenced objects from collection
    /// - **Pinned Locals**: Create fixed memory regions that GC cannot move
    /// - **Lifetime Tracking**: GC tracks local variable lifetimes for collection
    ///
    /// ## Interop Scenarios
    /// Pinned locals are essential for safe interop:
    /// - **P/Invoke**: Passing managed array pointers to native code
    /// - **COM Interop**: Fixed memory for COM interface calls
    /// - **Unsafe Code**: Direct memory manipulation with fixed addresses
    ///
    /// # Performance Considerations
    /// - **Pinned Locals**: Can impact GC performance due to memory fragmentation
    /// - **`ByRef` Locals**: Minimal overhead, similar to pointer operations
    /// - **Parsing Speed**: Linear in the number of local variables
    /// - **Memory Usage**: Efficient parsing with pre-allocated vectors
    ///
    /// # JIT Compiler Usage
    /// The JIT compiler uses local variable signatures for:
    /// - **Stack Frame Layout**: Determining local variable stack positions
    /// - **Type Safety**: Verifying type-safe access to local variables
    /// - **Optimization**: Register allocation and lifetime analysis
    /// - **Debugging Info**: Mapping IL locals to native debug information
    ///
    /// # ECMA-335 Compliance
    /// This implementation follows ECMA-335 6th Edition, Partition II, Section 23.2.6
    /// for local variable signature encoding and supports all standard local variable scenarios.
    pub fn parse_local_var_signature(&mut self) -> Result<SignatureLocalVariables> {
        let head_byte = self.parser.read_le::<u8>()?;
        if head_byte != SIGNATURE_HEADER::LOCAL_SIG {
            return Err(malformed_error!(
                "SignatureLocalVar - invalid start - {} (expected {})",
                head_byte,
                SIGNATURE_HEADER::LOCAL_SIG
            ));
        }

        let count = self.parser.read_compressed_uint()?;
        if count > MAX_LOCAL_VARIABLES {
            return Err(malformed_error!(
                "Local variable signature has too many locals: {} (max: {})",
                count,
                MAX_LOCAL_VARIABLES
            ));
        }

        let mut locals = Vec::with_capacity(count as usize);
        for _ in 0..count {
            locals.push(self.parse_single_local_variable()?);
        }

        Ok(SignatureLocalVariables { locals })
    }

    /// Parse a single local variable with its constraints and modifiers.
    ///
    /// This helper method handles the parsing of individual local variables according to
    /// ECMA-335 II.23.2.6. Local variables can have custom modifiers, PINNED constraints,
    /// and BYREF modifiers in a specific order.
    ///
    /// # Local Variable Grammar
    /// ```text
    /// LocalVarSig ::= LOCAL_SIG Count (TYPEDBYREF | ([CustomMod]* [Constraint]* [BYREF] Type))
    /// Constraint  ::= ELEMENT_TYPE_PINNED
    /// ```
    ///
    /// Note that unlike method parameters, local variable modifiers and constraints can be
    /// interleaved: custom_mod -> constraint -> custom_mod -> ...
    ///
    /// # Returns
    /// A `SignatureLocalVariable` containing:
    /// - Custom modifiers (modreq/modopt)
    /// - Whether the variable is pinned
    /// - Whether the variable is byref
    /// - The variable's type signature
    fn parse_single_local_variable(&mut self) -> Result<SignatureLocalVariable> {
        // TYPEDBYREF special case - no modifiers or constraints allowed
        if self.parser.peek_byte()? == ELEMENT_TYPE::TYPEDBYREF {
            self.parser.advance()?;
            return Ok(SignatureLocalVariable {
                modifiers: Vec::new(),
                is_byref: false,
                is_pinned: false,
                base: TypeSignature::TypedByRef,
            });
        }

        // Parse interleaved custom modifiers and constraints
        let (custom_mods, pinned) = self.parse_local_var_constraints()?;

        // Parse optional BYREF
        let by_ref = if self.parser.peek_byte()? == ELEMENT_TYPE::BYREF {
            self.parser.advance()?;
            true
        } else {
            false
        };

        // Parse the type
        let type_sig = self.parse_type()?;

        Ok(SignatureLocalVariable {
            modifiers: custom_mods,
            is_byref: by_ref,
            is_pinned: pinned,
            base: type_sig,
        })
    }

    /// Parse local variable constraints and custom modifiers.
    ///
    /// This helper method separates the concern of parsing the interleaved sequence of
    /// custom modifiers (CMOD_REQD/CMOD_OPT) and constraints (PINNED) that can appear
    /// before a local variable's type.
    ///
    /// # Returns
    /// A tuple containing:
    /// - `Vec<CustomModifier>`: The custom modifiers found
    /// - `bool`: Whether the PINNED constraint was present
    fn parse_local_var_constraints(&mut self) -> Result<(Vec<CustomModifier>, bool)> {
        let mut custom_mods = Vec::new();
        let mut pinned = false;

        while self.parser.has_more_data() {
            match self.parser.peek_byte()? {
                ELEMENT_TYPE::CMOD_REQD | ELEMENT_TYPE::CMOD_OPT => {
                    let is_required = self.parser.peek_byte()? == ELEMENT_TYPE::CMOD_REQD;
                    self.parser.advance()?;
                    let modifier_token = self.parser.read_compressed_token()?;
                    custom_mods.push(CustomModifier {
                        is_required,
                        modifier_type: modifier_token,
                    });
                }
                ELEMENT_TYPE::PINNED => {
                    // PINNED constraint (ELEMENT_TYPE_PINNED) - II.23.2.9
                    // This constraint applies to the entire local variable,
                    // not to individual custom modifiers.
                    self.parser.advance()?;
                    pinned = true;
                }
                _ => break,
            }
        }

        Ok((custom_mods, pinned))
    }

    /// Parse a type specification signature from the signature blob according to ECMA-335 II.23.2.14.
    ///
    /// Type specification signatures define complex type instantiations that cannot be represented
    /// directly in metadata tables. They are used for generic type instantiations, array types
    /// with complex bounds, function pointer types, and other constructed types.
    ///
    /// # Type Specification Format
    ///
    /// Type specifications contain a single type signature:
    /// ```text
    /// [Type]
    /// ```
    ///
    /// Unlike other signature types, type specifications do not have a signature header byte.
    /// They directly encode the type information using the standard type signature format.
    ///
    /// # Common Type Specification Uses
    ///
    /// ## Generic Type Instantiations
    /// ```csharp
    /// List<string>              // GENERICINST CLASS List<T> with STRING argument
    /// Dictionary<int, object>   // GENERICINST CLASS Dictionary<K,V> with I4, OBJECT arguments
    /// Nullable<DateTime>        // GENERICINST VALUETYPE Nullable<T> with DateTime argument
    /// ```
    ///
    /// ## Complex Array Types
    /// ```csharp
    /// int[,]                    // ARRAY I4 with rank 2
    /// string[,,]                // ARRAY STRING with rank 3  
    /// float[0..10, 0..5]        // ARRAY R4 with bounds and dimensions
    /// ```
    ///
    /// ## Function Pointer Types
    /// ```csharp
    /// delegate*<int, string>    // FNPTR with method signature
    /// delegate* unmanaged<void> // FNPTR with unmanaged calling convention
    /// ```
    ///
    /// ## Constructed Reference Types
    /// ```csharp
    /// string[]                  // SZARRAY STRING (single-dimensional array)
    /// int*                      // PTR I4 (unmanaged pointer)
    /// ref readonly DateTime     // BYREF with custom modifiers
    /// ```
    ///
    /// # Binary Examples
    ///
    /// ## Generic List of Strings
    /// ```text
    /// 0x15           // GENERICINST
    /// 0x12 0x42      // CLASS token (List<T>)
    /// 0x01           // 1 type argument
    /// 0x0E           // STRING type argument
    /// ```
    ///
    /// ## Two-Dimensional Array
    /// ```text
    /// 0x14           // ARRAY
    /// 0x08           // I4 element type
    /// 0x02           // rank = 2
    /// 0x00           // 0 size specifications
    /// 0x00           // 0 lower bound specifications
    /// ```
    ///
    /// ## Function Pointer
    /// ```text
    /// 0x1B           // FNPTR
    /// 0x00           // DEFAULT calling convention
    /// 0x01           // 1 parameter
    /// 0x01           // VOID return type
    /// 0x08           // I4 parameter type
    /// ```
    ///
    /// # Usage Context
    ///
    /// Type specifications are referenced from:
    /// - **`TypeSpec` Table**: Metadata table entries for constructed types
    /// - **Signature Blobs**: Complex type references in other signatures
    /// - **Custom Attributes**: Type arguments in attribute instantiations
    /// - **Generic Constraints**: Where clauses and type parameter bounds
    ///
    /// # Returns
    /// A [`crate::metadata::signatures::SignatureTypeSpec`] containing the complete
    /// type specification information ready for type system operations.
    ///
    /// # Errors
    /// - [`crate::Error::DepthLimitExceeded`]: Type parsing exceeds maximum nesting depth
    /// - [`crate::Error::Malformed`]: Invalid type encoding or format
    /// - [`crate::error::Error::OutOfBounds`]: Truncated type specification data
    ///
    /// # Performance Notes
    /// - Type specifications often involve complex recursive parsing
    /// - Generic instantiations with many type arguments require more processing
    /// - Consider caching parsed type specifications for frequently accessed types
    /// - Simple types (primitives, single classes) parse very quickly
    ///
    /// # Thread Safety
    /// This method is not thread-safe. Use separate parser instances for concurrent operations.
    ///
    /// # ECMA-335 References
    /// - **Partition II, Section 23.2.14**: `TypeSpec` signature format
    /// - **Partition II, Section 22.39**: `TypeSpec` metadata table
    /// - **Partition I, Section 8**: Type system and constructed types
    /// - **Partition II, Section 23.1.16**: Generic type instantiation validation
    pub fn parse_type_spec_signature(&mut self) -> Result<SignatureTypeSpec> {
        // First, parse any custom modifiers at the beginning
        let modifiers = self.parse_custom_mods()?;

        // Then parse the base type signature
        let base_type_sig = self.parse_type()?;

        // If we got a ModifiedRequired/Optional from parse_type, we need to handle it specially
        match base_type_sig {
            TypeSignature::ModifiedRequired(mod_modifiers)
            | TypeSignature::ModifiedOptional(mod_modifiers) => {
                // Combine the modifiers from parse_custom_mods() and from the ModifiedRequired
                let mut all_modifiers = modifiers;
                all_modifiers.extend(mod_modifiers);

                // Parse the base type that follows the modifiers
                let base_type = self.parse_type()?;

                Ok(SignatureTypeSpec {
                    modifiers: all_modifiers,
                    base: base_type,
                })
            }
            _ => {
                // No additional modifiers, just use what we found
                Ok(SignatureTypeSpec {
                    modifiers,
                    base: base_type_sig,
                })
            }
        }
    }

    /// Parse a method specification signature from the signature blob according to ECMA-335 II.23.2.15.
    ///
    /// Method specification signatures provide type arguments for generic method instantiations.
    /// They are used when calling generic methods with specific type parameters, allowing the
    /// runtime to create concrete method instances from generic method definitions.
    ///
    /// # Method Specification Format
    ///
    /// Method specifications follow this binary structure:
    /// ```text
    /// [GENRICINST] [GenericArgCount] [GenericArg1] [GenericArg2] ...
    /// ```
    ///
    /// ## Method Specification Header
    /// - **GENRICINST (0x0A)**: Required signature type marker for method specifications
    /// - **Validation**: Parser verifies the signature starts with 0x0A
    /// - **Purpose**: Distinguishes method specifications from other signature types
    ///
    /// ## Generic Argument Count
    /// A compressed integer specifying the number of type arguments provided for the
    /// generic method instantiation. This count must match the number of generic
    /// type parameters defined on the target generic method.
    ///
    /// ## Generic Type Arguments
    /// A sequence of complete type signatures, one for each generic type parameter.
    /// Each type argument can be any valid .NET type including:
    /// - **Primitive Types**: `int`, `string`, `bool`, etc.
    /// - **Reference Types**: Classes and interfaces
    /// - **Value Types**: Structs and enums  
    /// - **Constructed Types**: Arrays, generic instantiations, pointers
    /// - **Generic Parameters**: Other generic type or method parameters
    ///
    /// # Generic Method Instantiation Examples
    ///
    /// ## Simple Generic Method Call
    /// ```csharp
    /// // Generic method definition:
    /// public static T Create<T>() where T : new() => new T();
    ///
    /// // Method call with type argument:
    /// var instance = Create<string>();  // T = string
    /// ```
    ///
    /// ## Multiple Type Parameters
    /// ```csharp
    /// // Generic method definition:
    /// public static Dictionary<TKey, TValue> CreateDictionary<TKey, TValue>()
    ///     => new Dictionary<TKey, TValue>();
    ///
    /// // Method call with multiple type arguments:
    /// var dict = CreateDictionary<int, string>();  // TKey = int, TValue = string
    /// ```
    ///
    /// ## Complex Type Arguments
    /// ```csharp
    /// // Generic method definition:
    /// public static List<T[]> CreateArrayList<T>() => new List<T[]>();
    ///
    /// // Method call with array type argument:
    /// var arrays = CreateArrayList<DateTime>();  // T = DateTime, result = List<DateTime[]>
    /// ```
    ///
    /// ## Nested Generic Instantiations
    /// ```csharp
    /// // Generic method definition:
    /// public static T Process<T>(T input) => input;
    ///
    /// // Method call with generic type argument:
    /// var result = Process<List<int>>(myList);  // T = List<int>
    /// ```
    ///
    /// # Binary Format Examples
    ///
    /// ## Single Type Argument (string)
    /// ```text
    /// 0x0A           // GENRICINST method specification marker
    /// 0x01           // 1 generic type argument
    /// 0x0E           // STRING type argument
    /// ```
    ///
    /// ## Multiple Type Arguments (int, string)
    /// ```text
    /// 0x0A           // GENRICINST method specification marker  
    /// 0x02           // 2 generic type arguments
    /// 0x08           // I4 (int) first type argument
    /// 0x0E           // STRING second type argument
    /// ```
    ///
    /// ## Complex Type Argument (`List<DateTime>`)
    /// ```text
    /// 0x0A           // GENRICINST method specification marker
    /// 0x01           // 1 generic type argument
    /// 0x15           // GENERICINST (generic instantiation)
    /// 0x12 0x42      // CLASS token (List<T>)
    /// 0x01           // 1 type argument for List<T>
    /// 0x12 0x35      // CLASS token (DateTime)
    /// ```
    ///
    /// ## Generic Method Parameter as Argument
    /// ```text
    /// 0x0A           // GENRICINST method specification marker
    /// 0x01           // 1 generic type argument  
    /// 0x1E 0x00      // MVAR 0 (method generic parameter M0)
    /// ```
    ///
    /// # Usage Context
    ///
    /// Method specifications are used in:
    /// - **Method References**: Calls to generic methods from other assemblies
    /// - **Reflection Emit**: Dynamic method generation with generic type arguments
    /// - **Runtime Instantiation**: JIT compilation of generic method instances
    /// - **Metadata Analysis**: Type flow analysis and generic constraint validation
    ///
    /// # Type Argument Validation
    ///
    /// The runtime validates that provided type arguments satisfy the generic constraints
    /// defined on the target method:
    /// - **where T : class**: Reference type constraints
    /// - **where T : struct**: Value type constraints  
    /// - **where T : `new()`**: Default constructor constraints
    /// - **where T : `BaseClass`**: Base class constraints
    /// - **where T : `IInterface`**: Interface implementation constraints
    ///
    /// # Returns
    /// A [`crate::metadata::signatures::SignatureMethodSpec`] containing:
    /// - Complete list of type arguments for the generic method
    /// - Type signature information for each argument
    /// - Ready for runtime method instantiation
    ///
    /// # Errors
    /// - [`crate::Error::Malformed`]: Invalid method specification header (not 0x0A)
    /// - [`crate::Error::DepthLimitExceeded`]: Type argument parsing exceeds nesting depth limit
    /// - [`crate::error::Error::OutOfBounds`]: Truncated method specification data
    /// - [`crate::error::Error::Malformed`]: Mismatched type argument count
    ///
    /// # Performance Notes
    /// - Type argument parsing cost is linear in the number of arguments
    /// - Complex constructed type arguments require recursive parsing
    /// - Simple primitive type arguments parse very quickly
    /// - Consider caching method specifications for frequently called generic methods
    ///
    /// # Thread Safety
    /// This method is not thread-safe. Use separate parser instances for concurrent operations.
    ///
    /// # ECMA-335 References
    /// - **Partition II, Section 23.2.15**: `MethodSpec` signature format
    /// - **Partition II, Section 22.26**: `MethodSpec` metadata table
    /// - **Partition II, Section 9.4**: Generic method instantiation
    /// - **Partition I, Section 9.5.1**: Generic method constraints and validation
    pub fn parse_method_spec_signature(&mut self) -> Result<SignatureMethodSpec> {
        let head_byte = self.parser.read_le::<u8>()?;
        if head_byte != 0x0A {
            return Err(malformed_error!(
                "SignatureMethodSpec - invalid start - {}",
                head_byte
            ));
        }

        let arg_count = self.parser.read_compressed_uint()?;
        if arg_count > MAX_GENERIC_ARGS {
            return Err(malformed_error!(
                "Method specification has too many type arguments: {} (max: {})",
                arg_count,
                MAX_GENERIC_ARGS
            ));
        }

        let mut generic_args = Vec::with_capacity(arg_count as usize);
        for _ in 0..arg_count {
            generic_args.push(self.parse_type()?);
        }

        Ok(SignatureMethodSpec { generic_args })
    }
}

#[cfg(test)]
mod tests {
    use crate::prelude::Token;
    use crate::Error;

    use super::*;

    #[test]
    fn test_parse_primitive_types() {
        let test_cases = [
            (vec![0x01], TypeSignature::Void),
            (vec![0x02], TypeSignature::Boolean),
            (vec![0x03], TypeSignature::Char),
            (vec![0x04], TypeSignature::I1),
            (vec![0x05], TypeSignature::U1),
            (vec![0x06], TypeSignature::I2),
            (vec![0x07], TypeSignature::U2),
            (vec![0x08], TypeSignature::I4),
            (vec![0x09], TypeSignature::U4),
            (vec![0x0A], TypeSignature::I8),
            (vec![0x0B], TypeSignature::U8),
            (vec![0x0C], TypeSignature::R4),
            (vec![0x0D], TypeSignature::R8),
            (vec![0x0E], TypeSignature::String),
            (vec![0x1C], TypeSignature::Object),
            (vec![0x18], TypeSignature::I),
            (vec![0x19], TypeSignature::U),
        ];

        for (bytes, expected_type) in test_cases {
            let mut parser = SignatureParser::new(&bytes);
            let result = parser.parse_type().unwrap();
            assert_eq!(result, expected_type);
        }
    }

    #[test]
    fn test_parse_class_and_valuetype() {
        // Class type: Class token 0x10 in TypeRef
        let mut parser = SignatureParser::new(&[0x12, 0x42]);
        assert_eq!(
            parser.parse_type().unwrap(),
            TypeSignature::Class(Token::new(0x1B000010))
        );

        // Value type: Token 0xD in TypeRef
        let mut parser = SignatureParser::new(&[0x11, 0x35]);
        assert_eq!(
            parser.parse_type().unwrap(),
            TypeSignature::ValueType(Token::new(0x100000D))
        );

        // Generic parameter: Index 3
        let mut parser = SignatureParser::new(&[0x13, 0x03]);
        assert_eq!(
            parser.parse_type().unwrap(),
            TypeSignature::GenericParamType(0x03)
        );
    }

    #[test]
    fn test_parse_arrays() {
        // SzArray of Int32 (int[])
        let mut parser = SignatureParser::new(&[0x1D, 0x08]);
        let result = parser.parse_type().unwrap();

        assert!(matches!(result, TypeSignature::SzArray(_)));
        if let TypeSignature::SzArray(inner) = result {
            assert_eq!(*inner.base, TypeSignature::I4);
        }

        // Multi-dimensional array int[,] with rank 2, no sizes, no bounds
        let mut parser = SignatureParser::new(&[
            0x14, // ARRAY
            0x08, // I4 (element type)
            0x02, // rank 2
            0x00, // num_sizes 0
            0x00, // num_lo_bounds 0
        ]);

        let result = parser.parse_type().unwrap();
        assert!(matches!(result, TypeSignature::Array(_)));
        if let TypeSignature::Array(array) = result {
            assert_eq!(*array.base, TypeSignature::I4);
            assert_eq!(array.rank, 2);
            assert_eq!(array.dimensions.len(), 0)
        }

        // Multi-dimensional array int[2,3] with rank 2, with sizes
        let mut parser = SignatureParser::new(&[
            0x14, // ARRAY
            0x08, // I4 (element type)
            0x02, // rank 2
            0x02, // num_sizes 2
            0x02, // size 2
            0x03, // size 3
            0x00, // num_lo_bounds 0
        ]);

        let result = parser.parse_type().unwrap();
        assert!(matches!(result, TypeSignature::Array(_)));
        if let TypeSignature::Array(array) = result {
            assert_eq!(*array.base, TypeSignature::I4);
            assert_eq!(array.rank, 2);
            assert_eq!(array.dimensions.len(), 2);
            assert_eq!(array.dimensions[0].lower_bound, None);
            assert_eq!(array.dimensions[0].size, Some(2));
            assert_eq!(array.dimensions[1].lower_bound, None);
            assert_eq!(array.dimensions[1].size, Some(3));
        }
    }

    #[test]
    fn test_parse_pointers_and_byrefs() {
        // Pointer to Int32 (int*)
        let mut parser = SignatureParser::new(&[0x0F, 0x08]);
        let result = parser.parse_type().unwrap();

        assert!(matches!(result, TypeSignature::Ptr(_)));
        if let TypeSignature::Ptr(inner) = result {
            assert_eq!(*inner.base, TypeSignature::I4);
        }

        // ByRef to Int32 (ref int)
        let mut parser = SignatureParser::new(&[0x10, 0x08]);
        let result = parser.parse_type().unwrap();

        assert!(matches!(result, TypeSignature::ByRef(_)));
        if let TypeSignature::ByRef(inner) = result {
            assert_eq!(*inner, TypeSignature::I4);
        }
    }

    #[test]
    fn test_parse_generic_instance() {
        // Generic instance List<int>
        // Assume List is token 0x1B
        let mut parser = SignatureParser::new(&[
            0x15, // GENERICINST
            0x12, 0x49, // Class token for List
            0x01, // arg count
            0x08, // I4 type arg
        ]);

        let result = parser.parse_type().unwrap();

        assert!(matches!(result, TypeSignature::GenericInst(_, _)));
        if let TypeSignature::GenericInst(class, args) = result {
            assert!(matches!(*class, TypeSignature::Class(_)));
            assert_eq!(args.len(), 1);
            assert_eq!(args[0], TypeSignature::I4);
        }

        // Generic instance Dictionary<string, int>
        // Assume Dictionary is token 0x2A
        let mut parser = SignatureParser::new(&[
            0x15, // GENERICINST
            0x12, 0x2A, // Class token for Dictionary
            0x02, // 2 type args
            0x0E, // String type arg
            0x08, // I4 type arg
        ]);

        let result = parser.parse_type().unwrap();

        assert!(matches!(result, TypeSignature::GenericInst(_, _)));
        if let TypeSignature::GenericInst(class, args) = result {
            assert!(matches!(*class, TypeSignature::Class(_)));
            assert_eq!(args.len(), 2);
            assert_eq!(args[0], TypeSignature::String);
            assert_eq!(args[1], TypeSignature::I4);
        }
    }

    #[test]
    fn test_parse_custom_mods() {
        // Optional modifier (modopt) followed by required modifier (modreq)
        let mut parser = SignatureParser::new(&[
            0x20, 0x42, // CMOD_OPT, token 0x42
            0x1F, 0x49, // CMOD_REQD, token 0x49
            0x08, // I4 (to test we can still parse after the modifiers)
        ]);

        let mods = parser.parse_custom_mods().unwrap();
        assert_eq!(
            mods,
            vec![
                CustomModifier {
                    is_required: false,
                    modifier_type: Token::new(0x1B000010)
                },
                CustomModifier {
                    is_required: true,
                    modifier_type: Token::new(0x01000012)
                }
            ]
        );

        // Verify we can still parse the type after the modifiers
        let type_sig = parser.parse_type().unwrap();
        assert_eq!(type_sig, TypeSignature::I4);

        // Test empty modifiers
        let mut parser = SignatureParser::new(&[0x08]); // Just I4, no mods
        let mods = parser.parse_custom_mods().unwrap();
        assert!(mods.is_empty());
    }

    #[test]
    fn test_complex_signature() {
        // A complex method signature:
        // Dictionary<List<int>, string[]> Method<T>(ref T arg1, List<int>[] arg2)
        let mut parser = SignatureParser::new(&[
            0x30, // HASTHIS | GENERIC
            0x01, // 1 generic parameter
            0x02, // 2 parameters
            // Return type: Dictionary<List<int>, string[]>
            0x15, // GENERICINST
            0x12, 0x2A, // Class token for Dictionary
            0x02, // arg count
            // First type arg: List<int>
            0x15, // GENERICINST
            0x12, 0x49, // Class token for List
            0x01, // arg count
            0x08, // I4
            // Second type arg: string[]
            0x1D, // SZARRAY
            0x0E, // String
            // First parameter: ref T
            0x10, // BYREF
            0x13, 0x00, // GenericParam(0)
            // Second parameter: List<int>[]
            0x1D, // SZARRAY
            0x15, // GENERICINST
            0x12, 0x42, // Class token for List
            0x01, // arg count
            0x08, // I4
        ]);

        let result = parser.parse_method_signature().unwrap();

        // Test method general properties
        assert!(result.has_this);
        assert_eq!(result.param_count_generic, 1);
        assert_eq!(result.params.len(), 2);

        // Test return type (Dictionary<List<int>, string[]>)
        assert!(matches!(
            result.return_type.base,
            TypeSignature::GenericInst(_, _)
        ));

        // Test first parameter (ref T)
        assert!(result.params[0].by_ref);
        assert_eq!(result.params[0].base, TypeSignature::GenericParamType(0));

        // Test second parameter (List<int>[])
        assert!(!result.params[1].by_ref);
        assert!(matches!(result.params[1].base, TypeSignature::SzArray(_)));
    }

    #[test]
    fn test_error_handling() {
        // Test invalid method signature format
        let mut parser = SignatureParser::new(&[0xFF, 0x01]);
        assert!(matches!(
            parser.parse_method_signature(),
            Err(Error::OutOfBounds { .. })
        ));

        // Test invalid field signature format
        let mut parser = SignatureParser::new(&[0x07, 0x08]); // Should be 0x06 for FIELD
        assert!(parser.parse_field_signature().is_err());
    }
}