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
//! Method representation and analysis for .NET assemblies.
//!
//! This module provides comprehensive support for analyzing .NET methods, including
//! method metadata, IL code, exception handlers, and control flow structures.
//! It integrates closely with the disassembler to provide complete method analysis.
//!
//! # Architecture Overview
//!
//! The method analysis system uses a streamlined architecture centered around the
//! [`crate::metadata::method::Method`] struct with lazy-initialized basic blocks. Key design principles:
//!
//! - **Thread-safe lazy initialization**: Basic blocks are computed once and cached
//!   using `OnceLock<Vec<crate::assembly::BasicBlock>>` for efficient concurrent access
//! - **Zero-copy iteration**: The [`crate::metadata::method::InstructionIterator`] yields references to
//!   instructions without copying, enabling efficient analysis of large methods
//! - **Unified storage**: All instruction data is stored in basic blocks, eliminating
//!   redundant caching layers and simplifying the architecture
//!
//! # Key Components
//!
//! - [`crate::metadata::method::Method`] - Complete method representation with metadata and lazily-loaded IL code
//! - [`crate::metadata::method::MethodBody`] - Method body containing IL instructions and exception handlers
//! - [`crate::metadata::method::ExceptionHandler`] - Try/catch/finally exception handling regions
//! - [`crate::metadata::method::InstructionIterator`] - Efficient iterator over method instructions
//! - [`crate::metadata::method::MethodMap`] - Token-indexed collection of all methods in an assembly
//!
//! # Usage Patterns
//!
//! ## Basic Method Analysis
//!
//! ```rust,no_run
//! use dotscope::CilObject;
//! use std::path::Path;
//!
//! let assembly = CilObject::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
//!
//! for entry in assembly.methods().iter().take(10) {
//!     let method = entry.value();
//!     
//!     println!("Method: {} (Token: {:?})", method.name, method.token);
//!     println!("  Blocks: {}, Instructions: {}",
//!              method.block_count(), method.instruction_count());
//!     
//!     // Analyze control flow
//!     for (block_idx, block) in method.blocks() {
//!         println!("  Block {}: {} instructions at RVA 0x{:X}",
//!                  block_idx, block.instructions.len(), block.rva);
//!     }
//! }
//! # Ok::<(), dotscope::Error>(())
//! ```
//!
//! ## Instruction-Level Analysis
//!
//! ```rust,no_run
//! use dotscope::CilObject;
//! use std::path::Path;
//!
//! let assembly = CilObject::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
//!
//! for entry in assembly.methods().iter().take(5) {
//!     let method = entry.value();
//!     
//!     // Count different instruction types
//!     let mut call_count = 0;
//!     let mut branch_count = 0;
//!     
//!     for instruction in method.instructions() {
//!         match instruction.mnemonic {
//!             s if s.starts_with("call") => call_count += 1,
//!             s if s.contains("br") => branch_count += 1,
//!             _ => {}
//!         }
//!     }
//!     
//!     println!("{}: {} calls, {} branches", method.name, call_count, branch_count);
//! }
//! # Ok::<(), dotscope::Error>(())
//! ```
//!
//! # Thread Safety
//!
//! All method analysis operations are thread-safe:
//! - Methods can be safely shared across threads via `Arc<Method>`
//! - Basic block initialization uses `OnceLock` for thread-safe lazy loading
//! - Multiple threads can safely iterate over the same method simultaneously
//! - Iterator creation and consumption can happen concurrently
//!
//! # ECMA-335 References
//!
//! - §II.22.26 - MethodDef table (method metadata)
//! - §II.23.1.10 - MethodAttributes and MethodImplAttributes flags
//! - §II.25.4 - Method body format (tiny and fat headers)
//! - §II.25.4.6 - Exception handling clauses

mod body;
mod encode;
mod exceptions;
mod iter;
mod types;

use crossbeam_skiplist::SkipMap;
use std::sync::{atomic::AtomicU32, Arc, OnceLock, Weak};

pub use body::*;
pub use encode::encode_method_body_header;
pub use exceptions::*;
pub use iter::InstructionIterator;
pub use types::*;

use crate::{
    analysis::{ControlFlowGraph, SsaConverter, SsaExceptionHandler, SsaFunction, TypeContext},
    assembly::{self, BasicBlock, InstructionEncoder},
    file::File,
    metadata::{
        customattributes::CustomAttributeValueList,
        security::Security,
        signatures::{
            parse_local_var_signature, SignatureLocalVariable, SignatureMethod, TypeSignature,
        },
        streams::Blob,
        tables::{GenericParamList, MetadataTable, MethodSpecList, ParamList, StandAloneSigRaw},
        token::Token,
        typesystem::{CilModifier, CilTypeRc, CilTypeRef, TypeRegistry, TypeResolver},
    },
    utils::VisitedMap,
    CilObject, Result,
};

/// A map that holds the mapping of Token to parsed `Method`.
pub type MethodMap = SkipMap<Token, MethodRc>;
/// A vector that holds several parsed `Method`s.
pub type MethodList = Arc<boxcar::Vec<MethodRc>>;
/// A vector that holds `MethodRef` instances (weak references)
pub type MethodRefList = Arc<boxcar::Vec<MethodRef>>;
/// A reference-counted pointer to a `Method`.
pub type MethodRc = Arc<Method>;

/// Returns the name of the method definition for the given token, if it exists in the map.
///
/// This is a convenience function that performs a lookup in a [`MethodMap`] and extracts
/// the method name without requiring callers to deal with the `Entry` guard returned
/// by the underlying [`crossbeam_skiplist::SkipMap`].
///
/// # Arguments
///
/// * `map` - The method map to search in.
/// * `token` - The metadata token (table 0x06) identifying the method.
///
/// # Returns
///
/// The method name as a `String` if a method with the given token exists, `None` otherwise.
pub fn method_name_by_token(map: &MethodMap, token: &Token) -> Option<String> {
    map.get(token).map(|e| e.value().name.clone())
}

/// A smart reference to a Method that automatically handles weak references
/// to prevent circular reference memory leaks while providing a clean API.
///
/// `MethodRef` provides a safe way to reference methods without creating strong
/// reference cycles that could lead to memory leaks. This is particularly useful
/// when methods reference other methods (e.g., through inheritance or interfaces)
/// where circular dependencies might occur.
///
/// # Examples
///
/// ```rust,no_run
/// use dotscope::CilObject;
/// use std::path::Path;
///
/// let assembly = CilObject::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
///
/// // Create weak references to avoid circular dependencies
/// for entry in assembly.methods().iter().take(5) {
///     let method = entry.value();
///     let weak_ref = dotscope::metadata::method::MethodRef::new(&method);
///     
///     // Check if the reference is still valid
///     if weak_ref.is_valid() {
///         if let Some(name) = weak_ref.name() {
///             println!("Referenced method: {}", name);
///         }
///     }
/// }
/// # Ok::<(), dotscope::Error>(())
/// ```
#[derive(Clone, Debug)]
pub struct MethodRef {
    /// Weak reference to the actual method to avoid reference cycles
    weak_ref: Weak<Method>,
}

impl MethodRef {
    /// Create a new `MethodRef` from a strong reference.
    ///
    /// This method creates a weak reference to the provided method, allowing
    /// safe referencing without creating strong reference cycles.
    ///
    /// # Arguments
    ///
    /// * `strong_ref` - A strong reference (`Arc<Method>`) to the method
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::CilObject;
    /// use std::path::Path;
    ///
    /// let assembly = CilObject::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
    /// if let Some(entry) = assembly.methods().iter().next() {
    ///     let method = entry.value();
    ///     let method_ref = dotscope::metadata::method::MethodRef::new(&method);
    ///     println!("Created weak reference to method: {}", method.name);
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn new(strong_ref: &MethodRc) -> Self {
        Self {
            weak_ref: Arc::downgrade(strong_ref),
        }
    }

    /// Get a strong reference to the method, returning None if the method has been dropped.
    ///
    /// This method attempts to upgrade the weak reference to a strong reference.
    /// If the original method has been dropped, this returns `None`.
    ///
    /// # Returns
    ///
    /// - `Some(Arc<Method>)` if the method is still alive
    /// - `None` if the method has been dropped
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::CilObject;
    /// use std::path::Path;
    ///
    /// let assembly = CilObject::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
    /// if let Some(entry) = assembly.methods().iter().next() {
    ///     let method = entry.value();
    ///     let method_ref = dotscope::metadata::method::MethodRef::new(&method);
    ///     
    ///     // Later, try to access the method
    ///     if let Some(method) = method_ref.upgrade() {
    ///         println!("Method is still available: {}", method.name);
    ///     } else {
    ///         println!("Method has been dropped");
    ///     }
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    #[must_use]
    pub fn upgrade(&self) -> Option<MethodRc> {
        self.weak_ref.upgrade()
    }

    /// Get a strong reference to the method, panicking if the method has been dropped.
    ///
    /// Use this when you're certain the method should still exist. This provides
    /// a convenient way to access the method without handling the `Option` case.
    ///
    /// # Arguments
    ///
    /// * `msg` - Error message to display if the method has been dropped
    ///
    /// # Panics
    ///
    /// Panics if the method has been dropped and the weak reference cannot be upgraded.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::CilObject;
    /// use std::path::Path;
    ///
    /// let assembly = CilObject::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
    /// if let Some(entry) = assembly.methods().iter().next() {
    ///     let method = entry.value();
    ///     let method_ref = dotscope::metadata::method::MethodRef::new(&method);
    ///     
    ///     // Use expect when you're certain the method should exist
    ///     let method = method_ref.expect("Method should still be available");
    ///     println!("Accessed method: {}", method.name);
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    #[must_use]
    pub fn expect(&self, msg: &str) -> MethodRc {
        self.weak_ref.upgrade().expect(msg)
    }

    /// Check if the referenced method is still alive.
    ///
    /// This provides a quick way to test if the weak reference can still be
    /// upgraded to a strong reference without actually performing the upgrade.
    ///
    /// # Returns
    ///
    /// `true` if the method is still alive, `false` if it has been dropped
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::CilObject;
    /// use std::path::Path;
    ///
    /// let assembly = CilObject::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
    /// let mut method_refs = Vec::new();
    ///
    /// // Collect weak references
    /// for entry in assembly.methods().iter().take(10) {
    ///     let method = entry.value();
    ///     method_refs.push(dotscope::metadata::method::MethodRef::new(&method));
    /// }
    ///
    /// // Check which references are still valid
    /// let valid_count = method_refs.iter().filter(|r| r.is_valid()).count();
    /// println!("{} out of {} method references are still valid",
    ///          valid_count, method_refs.len());
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    #[must_use]
    pub fn is_valid(&self) -> bool {
        self.weak_ref.strong_count() > 0
    }

    /// Get the token of the referenced method (if still alive).
    ///
    /// This is a convenience method that upgrades the reference and extracts
    /// the method token in a single operation.
    ///
    /// # Returns
    ///
    /// - `Some(Token)` if the method is still alive
    /// - `None` if the method has been dropped
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::CilObject;
    /// use std::path::Path;
    ///
    /// let assembly = CilObject::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
    /// if let Some(entry) = assembly.methods().iter().next() {
    ///     let method = entry.value();
    ///     let method_ref = dotscope::metadata::method::MethodRef::new(&method);
    ///     
    ///     if let Some(token) = method_ref.token() {
    ///         println!("Method token: {:?}", token);
    ///     }
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    #[must_use]
    pub fn token(&self) -> Option<Token> {
        self.upgrade().map(|m| m.token)
    }

    /// Get the name of the referenced method (if still alive).
    ///
    /// This is a convenience method that upgrades the reference and extracts
    /// the method name in a single operation.
    ///
    /// # Returns
    ///
    /// - `Some(String)` containing the method name if the method is still alive
    /// - `None` if the method has been dropped
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::CilObject;
    /// use std::path::Path;
    ///
    /// let assembly = CilObject::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
    /// let mut method_names = Vec::new();
    ///
    /// for entry in assembly.methods().iter().take(5) {
    ///     let method = entry.value();
    ///     let method_ref = dotscope::metadata::method::MethodRef::new(&method);
    ///     
    ///     if let Some(name) = method_ref.name() {
    ///         method_names.push(name);
    ///     }
    /// }
    ///
    /// println!("Collected {} method names", method_names.len());
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    #[must_use]
    pub fn name(&self) -> Option<String> {
        self.upgrade().map(|m| m.name.clone())
    }

    /// Check if the referenced method is a constructor (.ctor or .cctor).
    ///
    /// This is a convenience method that upgrades the reference and checks
    /// if the method is a constructor in a single operation.
    ///
    /// # Returns
    ///
    /// `true` if the method is still alive and is a constructor, `false` otherwise
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::CilObject;
    /// use std::path::Path;
    ///
    /// let assembly = CilObject::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
    /// let mut constructor_count = 0;
    ///
    /// for entry in assembly.methods().iter() {
    ///     let method = entry.value();
    ///     let method_ref = dotscope::metadata::method::MethodRef::new(&method);
    ///     
    ///     if method_ref.is_constructor() {
    ///         constructor_count += 1;
    ///     }
    /// }
    ///
    /// println!("Found {} constructors", constructor_count);
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    #[must_use]
    pub fn is_constructor(&self) -> bool {
        if let Some(method) = self.upgrade() {
            method.is_constructor()
        } else {
            false
        }
    }
}

impl From<MethodRc> for MethodRef {
    fn from(strong_ref: MethodRc) -> Self {
        Self::new(&strong_ref)
    }
}

/// Represents all the information about a CIL method.
///
/// The `Method` struct contains all metadata, code, and analysis results for a single .NET method.
/// It includes method attributes, parameters, generic arguments, IL code, exception handlers, and analysis results.
///
/// # Invariants
///
/// The following invariants should be maintained for a valid `Method`:
///
/// - **Token/RID consistency**: `token.value() == (0x06000000 | rid)` - The token must match the row ID
/// - **RVA validity**: If `rva.is_some()` and the method is not runtime-provided, `body` should be set
/// - **Parameter correlation**: After [`Method::parse()`] is called, `params` entries have correlated signatures
/// - **Block dependency**: `blocks` depends on `body` being set (decoding requires body data)
///
/// # Initialization Sequence
///
/// Methods go through several initialization phases:
///
/// 1. **Basic construction** - Created from `MethodDef` table row with metadata fields populated
/// 2. **[`Method::parse()`]** - Loads method body, local variables, and applies parameter signatures
/// 3. **`decode_method()`** - Disassembles IL bytecode and builds basic blocks
///
/// After phase 1, the method has metadata but no IL code. After phase 2, the body and local variables
/// are available. After phase 3, instructions can be iterated via [`Method::instructions()`].
///
/// # Thread Safety
///
/// The struct uses [`OnceLock`] for lazy-initialized fields (`body`, `blocks`, `overrides`, `security`)
/// which provides thread-safe one-time initialization. The `flags_pinvoke` field uses [`AtomicU32`]
/// because it's populated from a separate table after the method may already be shared.
pub struct Method {
    /// The row this method has in the `MetadataTable`
    pub rid: u32,
    /// The token of this method
    pub token: Token,
    /// The offset in the `MetadataTable`
    pub meta_offset: usize,
    /// This methods name
    pub name: String,
    /// `MethodImplAttributes`, §II.23.1.10
    pub impl_code_type: MethodImplCodeType,
    /// `MethodImplAttributes`, §II.23.1.10
    pub impl_management: MethodImplManagement,
    /// `MethodImplAttributes`, §II.23.1.10
    pub impl_options: MethodImplOptions,
    /// `MethodAttributes`, §II.23.1.10
    pub flags_access: MethodAccessFlags,
    /// `MethodAttributes`, §II.23.1.10
    pub flags_vtable: MethodVtableFlags,
    /// `MethodAttributes`, §II.23.1.10
    pub flags_modifiers: MethodModifiers,
    /// P/Invoke mapping flags from the `ImplMap` table, §II.23.1.8.
    pub flags_pinvoke: AtomicU32,
    /// The parameters (from `Param` table, enhanced with information from the `SignatureMethod`)
    /// sequence 0, is the return value (if there is a count 0).
    pub params: ParamList,
    /// The vararg parameters of this method
    pub varargs: Arc<boxcar::Vec<VarArg>>,
    /// All generic parameters this type has (type information, not the instantiated version)
    pub generic_params: GenericParamList,
    /// `MethodSpec` instances that provide generic instantiations for this method
    pub generic_args: MethodSpecList,
    /// The signature of this method
    pub signature: SignatureMethod,
    /// The RVA of this method
    pub rva: Option<u32>,
    /// The `MethodBody`
    pub body: OnceLock<MethodBody>,
    /// The local variables
    pub local_vars: Arc<boxcar::Vec<LocalVariable>>,
    /// Overridden method if this is an override
    /// (from `MethodImpl` table where `MethodBody` points to this method)
    pub overrides: OnceLock<MethodRef>,
    /// Implemented interface methods
    /// (from `MethodImpl` table entries for this type)
    pub interface_impls: MethodRefList,
    /// The .NET CIL Security Information (if present)
    pub security: OnceLock<Security>,
    /// The basic blocks of this method, lazily initialized
    pub blocks: OnceLock<Vec<BasicBlock>>,
    /// Custom attributes attached to this method
    pub custom_attributes: CustomAttributeValueList,
    /// The type that declares this method (lazy-loaded).
    ///
    /// Contains a weak reference to the [`crate::metadata::typesystem::CilType`] that owns this method.
    /// This is set during TypeDef loading after the owning type is constructed.
    /// Use [`CilTypeRef::upgrade()`] to obtain a strong reference when needed.
    pub declaring_type: OnceLock<CilTypeRef>,
}

impl Method {
    /// Returns an iterator over all instructions in this method.
    ///
    /// Instructions are yielded in execution order across all basic blocks, providing
    /// a linear view of the method's IL code. This method handles uninitialized state
    /// gracefully by returning an empty iterator if blocks haven't been decoded yet.
    ///
    /// The iterator implements efficient traversal without copying instruction data,
    /// making it suitable for analysis of large methods. Each instruction maintains
    /// its original metadata including RVA, operands, and flow control information.
    ///
    /// # Thread Safety
    ///
    /// This method is thread-safe and can be called concurrently. If the method hasn't
    /// been disassembled yet, all threads will receive an empty iterator.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::CilObject;
    /// use std::path::Path;
    ///
    /// let assembly = CilObject::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
    /// for entry in assembly.methods().iter().take(3) {
    ///     let method = entry.value();
    ///     println!("Method: {} ({} instructions)",
    ///              method.name, method.instruction_count());
    ///
    ///     for (i, instruction) in method.instructions().enumerate() {
    ///         println!("  [{}] {} {:?}", i, instruction.mnemonic, instruction.operand);
    ///         if i >= 10 { break; } // Limit output for readability
    ///     }
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn instructions(&self) -> InstructionIterator<'_> {
        if let Some(blocks) = self.blocks.get() {
            InstructionIterator::new(blocks.as_slice())
        } else {
            InstructionIterator::new(&[])
        }
    }

    /// Returns an iterator over all basic blocks containing the instructions.
    ///
    /// This method provides access to the control flow structure of the method by yielding
    /// each basic block along with its sequential index. Basic blocks represent straight-line
    /// sequences of instructions with a single entry point and single exit point.
    ///
    /// The iterator yields tuples of `(block_index, &BasicBlock)` where `block_index` is the
    /// zero-based position in the blocks vector. Returns an empty iterator if the method
    /// hasn't been disassembled yet.
    ///
    /// # Thread Safety
    ///
    /// This method is thread-safe and handles the `OnceLock` access pattern internally.
    /// Multiple threads can safely iterate over blocks simultaneously.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::CilObject;
    /// use std::path::Path;
    ///
    /// let assembly = CilObject::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
    /// for entry in assembly.methods().iter().take(3) {
    ///     let method = entry.value();
    ///     println!("Method: {} has {} basic blocks",
    ///              method.name, method.block_count());
    ///     
    ///     for (block_index, block) in method.blocks() {
    ///         println!("  Block {}: RVA 0x{:X}, {} instructions, {} exceptions",
    ///                 block_index, block.rva, block.instructions.len(), block.exceptions.len());
    ///         
    ///         // Show control flow information
    ///         if !block.instructions.is_empty() {
    ///             let last_instr = &block.instructions[block.instructions.len() - 1];
    ///             println!("    Ends with: {} (flow: {:?})",
    ///                     last_instr.mnemonic, last_instr.flow_type);
    ///         }
    ///     }
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    ///
    /// # Control Flow Analysis
    ///
    /// Each basic block contains:
    /// - Sequential instructions with no internal jumps
    /// - Exception handler associations
    /// - RVA and offset information for debugging
    /// - Flow control termination (branch, return, throw, etc.)
    pub fn blocks(&self) -> Box<dyn Iterator<Item = (usize, &BasicBlock)> + '_> {
        if let Some(blocks) = self.blocks.get() {
            Box::new(blocks.iter().enumerate())
        } else {
            Box::new([].iter().enumerate())
        }
    }

    /// Returns the number of basic blocks in this method.
    ///
    /// This provides an efficient way to get the block count without iterating through
    /// all blocks. Returns 0 if the method hasn't been disassembled yet or contains
    /// no executable code.
    ///
    /// # Thread Safety
    ///
    /// This method is thread-safe and handles the `OnceLock` access pattern internally.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::CilObject;
    /// use std::path::Path;
    ///
    /// let assembly = CilObject::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
    /// for entry in assembly.methods().iter().take(10) {
    ///     let method = entry.value();
    ///     let block_count = method.block_count();
    ///     let instr_count = method.instruction_count();
    ///     
    ///     println!("Method: {} - {} blocks, {} instructions (avg {:.1} instr/block)",
    ///              method.name, block_count, instr_count,
    ///              if block_count > 0 { instr_count as f64 / block_count as f64 } else { 0.0 });
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn block_count(&self) -> usize {
        if let Some(blocks) = self.blocks.get() {
            blocks.len()
        } else {
            0
        }
    }

    /// Returns the total number of instructions across all basic blocks.
    ///
    /// This method efficiently calculates the total instruction count by summing
    /// the length of instruction vectors in each basic block. This is more efficient
    /// than calling `method.instructions().count()` as it avoids creating and
    /// consuming the iterator.
    ///
    /// Returns 0 if the method hasn't been disassembled yet or contains no executable code.
    ///
    /// # Thread Safety
    ///
    /// This method is thread-safe and handles the `OnceLock` access pattern internally.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::CilObject;
    /// use std::path::Path;
    ///
    /// let assembly = CilObject::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
    /// let mut total_instructions = 0;
    /// let mut method_count = 0;
    ///
    /// for entry in assembly.methods().iter() {
    ///     let method = entry.value();
    ///     let count = method.instruction_count();
    ///     total_instructions += count;
    ///     method_count += 1;
    ///     
    ///     if count > 100 {
    ///         println!("Large method: {} with {} instructions", method.name, count);
    ///     }
    /// }
    ///
    /// println!("Assembly has {} methods with {} total instructions",
    ///          method_count, total_instructions);
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn instruction_count(&self) -> usize {
        if let Some(blocks) = self.blocks.get() {
            blocks.iter().map(|block| block.instructions.len()).sum()
        } else {
            0
        }
    }

    /// Returns true if the method has IL code.
    ///
    /// This checks the `MethodImplCodeType::IL` flag in the method's implementation
    /// attributes to determine if the method contains Common Intermediate Language (CIL)
    /// instructions that can be disassembled and analyzed.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::CilObject;
    /// use std::path::Path;
    ///
    /// let assembly = CilObject::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
    /// for entry in assembly.methods().iter().take(10) {
    ///     let method = entry.value();
    ///     if method.is_code_il() {
    ///         println!("Method '{}' contains IL code", method.name);
    ///     }
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn is_code_il(&self) -> bool {
        self.impl_code_type.contains(MethodImplCodeType::IL)
    }

    /// Returns true if the method has native code (P/Invoke).
    ///
    /// This checks the `MethodImplCodeType::NATIVE` flag to determine if the method
    /// is implemented in native code rather than IL. This is typical for P/Invoke
    /// methods that call into unmanaged libraries.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::CilObject;
    /// use std::path::Path;
    ///
    /// let assembly = CilObject::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
    /// let native_methods: Vec<_> = assembly.methods().iter()
    ///     .filter(|entry| entry.value().is_code_native())
    ///     .map(|entry| entry.value().name.clone())
    ///     .collect();
    ///
    /// println!("Found {} native methods", native_methods.len());
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn is_code_native(&self) -> bool {
        self.impl_code_type.contains(MethodImplCodeType::NATIVE)
    }

    /// Returns true if the method has optimized IL code.
    ///
    /// This checks the `MethodImplCodeType::OPTIL` flag to determine if the method
    /// contains optimized Common Intermediate Language that may have been transformed
    /// by the runtime or tools for better performance.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::CilObject;
    /// use std::path::Path;
    ///
    /// let assembly = CilObject::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
    /// for entry in assembly.methods().iter() {
    ///     let method = entry.value();
    ///     if method.is_code_opt_il() {
    ///         println!("Method '{}' has optimized IL code", method.name);
    ///     }
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn is_code_opt_il(&self) -> bool {
        self.impl_code_type.contains(MethodImplCodeType::OPTIL)
    }

    /// Returns true if the method is implemented in the runtime.
    ///
    /// This checks the `MethodImplCodeType::RUNTIME` flag to determine if the method
    /// is implemented directly by the .NET runtime rather than containing user code.
    /// This is common for intrinsic methods and runtime-provided functionality.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::CilObject;
    /// use std::path::Path;
    ///
    /// let assembly = CilObject::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
    /// let runtime_methods: Vec<_> = assembly.methods().iter()
    ///     .filter(|entry| entry.value().is_code_runtime())
    ///     .map(|entry| entry.value().name.clone())
    ///     .collect();
    ///
    /// println!("Found {} runtime-implemented methods", runtime_methods.len());
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn is_code_runtime(&self) -> bool {
        self.impl_code_type.contains(MethodImplCodeType::RUNTIME)
    }

    /// Returns true if the method is unmanaged.
    ///
    /// This checks the `MethodImplManagement::UNMANAGED` flag to determine if the
    /// method runs outside the managed execution environment, typically for P/Invoke
    /// methods or COM interop scenarios.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::CilObject;
    /// use std::path::Path;
    ///
    /// let assembly = CilObject::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
    /// for entry in assembly.methods().iter() {
    ///     let method = entry.value();
    ///     if method.is_code_unmanaged() {
    ///         println!("Unmanaged method: {}", method.name);
    ///     }
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn is_code_unmanaged(&self) -> bool {
        self.impl_management
            .contains(MethodImplManagement::UNMANAGED)
    }

    /// Returns true if the method is a forward reference (used in merge scenarios).
    ///
    /// This checks the `MethodImplOptions::FORWARD_REF` flag to determine if the
    /// method is declared but not yet defined, which can occur during incremental
    /// compilation or when working with incomplete assemblies.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::CilObject;
    /// use std::path::Path;
    ///
    /// let assembly = CilObject::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
    /// let forward_refs: Vec<_> = assembly.methods().iter()
    ///     .filter(|entry| entry.value().is_forward_ref())
    ///     .map(|entry| entry.value().name.clone())
    ///     .collect();
    ///
    /// if !forward_refs.is_empty() {
    ///     println!("Found {} forward reference methods", forward_refs.len());
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn is_forward_ref(&self) -> bool {
        self.impl_options.contains(MethodImplOptions::FORWARD_REF)
    }

    /// Returns true if the method is synchronized.
    ///
    /// This checks the `MethodImplOptions::SYNCHRONIZED` flag to determine if the
    /// method automatically acquires a lock before execution, providing thread-safe
    /// access to the method body. This is equivalent to marking a method with the
    /// `synchronized` keyword in some languages.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::CilObject;
    /// use std::path::Path;
    ///
    /// let assembly = CilObject::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
    /// for entry in assembly.methods().iter() {
    ///     let method = entry.value();
    ///     if method.is_synchronized() {
    ///         println!("Synchronized method: {}", method.name);
    ///     }
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn is_synchronized(&self) -> bool {
        self.impl_options.contains(MethodImplOptions::SYNCHRONIZED)
    }

    /// Returns true if the method preserves signature for P/Invoke.
    ///
    /// This checks the `MethodImplOptions::PRESERVE_SIG` flag to determine if the
    /// method signature should be preserved exactly as declared when calling into
    /// unmanaged code, rather than applying standard .NET marshalling transformations.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::CilObject;
    /// use std::path::Path;
    ///
    /// let assembly = CilObject::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
    /// for entry in assembly.methods().iter() {
    ///     let method = entry.value();
    ///     if method.is_pinvoke() {
    ///         println!("P/Invoke method with preserved signature: {}", method.name);
    ///     }
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn is_pinvoke(&self) -> bool {
        self.impl_options.contains(MethodImplOptions::PRESERVE_SIG)
    }

    /// Returns true if the method is an internal call.
    ///
    /// This checks the `MethodImplOptions::INTERNAL_CALL` flag to determine if the
    /// method is implemented internally by the runtime with special handling for
    /// parameter type checking and validation.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::CilObject;
    /// use std::path::Path;
    ///
    /// let assembly = CilObject::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
    /// let internal_methods: Vec<_> = assembly.methods().iter()
    ///     .filter(|entry| entry.value().is_internal_call())
    ///     .map(|entry| entry.value().name.clone())
    ///     .collect();
    ///
    /// println!("Found {} internal call methods", internal_methods.len());
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn is_internal_call(&self) -> bool {
        self.impl_options.contains(MethodImplOptions::INTERNAL_CALL)
    }

    /// Returns true if the method implementation is forwarded through P/Invoke.
    ///
    /// This checks the `MethodImplOptions::MAX_METHOD_IMPL_VAL` flag to determine
    /// if the method implementation is forwarded to an external library through
    /// the Platform Invoke (P/Invoke) mechanism.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::CilObject;
    /// use std::path::Path;
    ///
    /// let assembly = CilObject::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
    /// for entry in assembly.methods().iter() {
    ///     let method = entry.value();
    ///     if method.is_forwarded_pinvoke() {
    ///         println!("Forwarded P/Invoke method: {}", method.name);
    ///     }
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    #[must_use]
    pub fn is_forwarded_pinvoke(&self) -> bool {
        self.impl_options
            .contains(MethodImplOptions::MAX_METHOD_IMPL_VAL)
    }

    /// Returns true if the method is a constructor (.ctor or .cctor).
    #[must_use]
    pub fn is_constructor(&self) -> bool {
        self.name.starts_with(".ctor") || self.name.starts_with(".cctor")
    }

    /// Returns true if the method is an instance constructor (.ctor).
    #[must_use]
    pub fn is_ctor(&self) -> bool {
        self.name == ".ctor"
    }

    /// Returns true if the method is a static constructor (.cctor).
    #[must_use]
    pub fn is_cctor(&self) -> bool {
        self.name == ".cctor"
    }

    /// Returns true if the method has a parsed body.
    #[must_use]
    pub fn has_body(&self) -> bool {
        self.body.get().is_some()
    }

    /// Returns true if the method is static.
    #[must_use]
    pub fn is_static(&self) -> bool {
        self.flags_modifiers.contains(MethodModifiers::STATIC)
    }

    /// Returns true if the method is virtual.
    #[must_use]
    pub fn is_virtual(&self) -> bool {
        self.flags_modifiers.contains(MethodModifiers::VIRTUAL)
    }

    /// Returns true if the method is abstract.
    #[must_use]
    pub fn is_abstract(&self) -> bool {
        self.flags_modifiers.contains(MethodModifiers::ABSTRACT)
    }

    /// Returns true if the method has public access.
    #[must_use]
    pub fn is_public(&self) -> bool {
        self.flags_access == MethodAccessFlags::PUBLIC
    }

    /// Returns the declaring type as a strong reference, if available.
    ///
    /// This upgrades the internal weak reference to the declaring type,
    /// returning `None` if the type has been dropped or was never set.
    #[must_use]
    pub fn declaring_type_rc(&self) -> Option<CilTypeRc> {
        self.declaring_type.get().and_then(CilTypeRef::upgrade)
    }

    /// Returns the fully-qualified name of the declaring type, if available.
    #[must_use]
    pub fn declaring_type_fullname(&self) -> Option<String> {
        self.declaring_type_rc().map(|t| t.fullname())
    }

    /// Returns the fully-qualified method name in `"DeclaringType::MethodName"` format.
    ///
    /// If the declaring type is available and has a non-empty fullname, returns
    /// `"Namespace.TypeName::MethodName"`. Otherwise returns just the method name.
    #[must_use]
    pub fn fullname(&self) -> String {
        match self.declaring_type_fullname() {
            Some(type_name) if !type_name.is_empty() => format!("{}::{}", type_name, self.name),
            _ => self.name.clone(),
        }
    }

    /// Builds and returns the control flow graph for this method.
    ///
    /// The CFG is constructed from the method's basic blocks, providing graph-based
    /// access to control flow with support for dominator computation, loop detection,
    /// and various traversal algorithms.
    ///
    /// The returned CFG borrows the method's blocks (zero-copy). If you need an
    /// owned CFG that outlives the method, use [`into_owned()`](ControlFlowGraph::into_owned)
    /// on the result.
    ///
    /// # Returns
    ///
    /// A [`ControlFlowGraph`] for this method, or `None` if:
    /// - The method hasn't been disassembled yet
    /// - The method has no basic blocks (e.g., abstract or native methods)
    /// - CFG construction fails
    ///
    /// # Thread Safety
    ///
    /// This method is thread-safe. The CFG is built from a snapshot of the
    /// method's blocks at call time.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::CilObject;
    /// use std::path::Path;
    ///
    /// let assembly = CilObject::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
    ///
    /// for entry in assembly.methods().iter().take(5) {
    ///     let method = entry.value();
    ///     if let Some(cfg) = method.cfg() {
    ///         println!("Method: {} has {} blocks, {} loops",
    ///                  method.name, cfg.block_count(), cfg.loops().len());
    ///
    ///         // Access dominators
    ///         let dominators = cfg.dominators();
    ///         println!("  Entry dominates all: {}",
    ///                  cfg.node_ids().all(|n| cfg.dominates(cfg.entry(), n)));
    ///     }
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    #[must_use]
    pub fn cfg(&self) -> Option<ControlFlowGraph<'_>> {
        let blocks = self.blocks.get()?;
        if blocks.is_empty() {
            return None;
        }
        ControlFlowGraph::from_blocks_ref(blocks).ok()
    }

    /// Parse provided data, and extract additional information from the binary. e.g. Disassembly,
    /// method body, local variables, exception handlers, etc.
    ///
    /// # Arguments
    /// * `file`    - The input file
    /// * `blobs`   - The processed Blobs
    /// * `sigs`    - The table of signatures
    /// * `types`   - The type registry
    ///
    /// # Errors
    /// Returns an error if parsing fails or if referenced types/signatures cannot be resolved.
    pub fn parse(
        &self,
        file: &File,
        blobs: &Blob,
        sigs: Option<&MetadataTable<StandAloneSigRaw>>,
        types: &Arc<TypeRegistry>,
        shared_visited: Arc<VisitedMap>,
    ) -> Result<()> {
        // Native and runtime methods don't have CIL method bodies - their RVA
        // points to x86/x64 machine code or runtime-provided implementations,
        // not to a CIL method header. Skip body parsing and IL decoding for these.
        let has_il_body = !self.is_code_native() && !self.is_code_runtime();
        if has_il_body {
            if let Some(rva) = self.rva {
                let body = self.parse_method_body(file, blobs, sigs, types, rva)?;
                self.body.set(body).ok();
            }
        }

        self.resolve_parameter_signatures(types)?;
        self.parse_varargs(types)?;

        if has_il_body {
            assembly::decode_method(self, file, shared_visited)?;
        }
        Ok(())
    }

    /// Parses the method body including local variables and exception handlers.
    ///
    /// # Arguments
    /// * `file` - The input file
    /// * `blobs` - The blob heap
    /// * `sigs` - The standalone signatures table
    /// * `types` - The type registry
    /// * `rva` - The relative virtual address of the method
    ///
    /// # Errors
    /// Returns an error if the method body cannot be parsed or local variables cannot be resolved.
    fn parse_method_body(
        &self,
        file: &File,
        blobs: &Blob,
        sigs: Option<&MetadataTable<StandAloneSigRaw>>,
        types: &Arc<TypeRegistry>,
        rva: u32,
    ) -> Result<MethodBody> {
        let method_offset = file.rva_to_offset(rva as usize)?;
        if method_offset == 0 || method_offset >= file.data().len() {
            return Err(malformed_error!(
                "Method offset is invalid - {}",
                method_offset
            ));
        }

        let mut body = MethodBody::from(&file.data()[method_offset..])?;
        if body.local_var_sig_token != 0 {
            self.parse_local_variables(&body, blobs, sigs, types)?;
        }

        Self::resolve_exception_handlers(&mut body, types)?;
        Ok(body)
    }

    /// Parses local variable signatures and populates the local_vars collection.
    ///
    /// # Arguments
    /// * `body` - The method body containing the local var signature token
    /// * `blobs` - The blob heap
    /// * `sigs` - The standalone signatures table
    /// * `types` - The type registry
    ///
    /// # Errors
    /// Returns an error if the signature cannot be resolved or types cannot be found.
    fn parse_local_variables(
        &self,
        body: &MethodBody,
        blobs: &Blob,
        sigs: Option<&MetadataTable<StandAloneSigRaw>>,
        types: &Arc<TypeRegistry>,
    ) -> Result<()> {
        let Some(sigs_table) = sigs else {
            return Ok(());
        };

        let local_var_sig_data = match sigs_table.get(body.local_var_sig_token & 0x00FF_FFFF) {
            Some(var_sig_row) => blobs.get(var_sig_row.signature as usize)?,
            None => {
                return Err(malformed_error!(
                    "Failed to resolve local variable signature - token 0x{:08X}",
                    body.local_var_sig_token
                ))
            }
        };

        let mut resolver = TypeResolver::new(types.clone());
        let local_var_sig = parse_local_var_signature(local_var_sig_data)?;

        for local_var in &local_var_sig.locals {
            let mut modifiers = Vec::with_capacity(local_var.modifiers.len());
            for var_mod in &local_var.modifiers {
                match types.get(&var_mod.modifier_type) {
                    Some(var_mod_type) => modifiers.push(CilModifier {
                        required: var_mod.is_required,
                        modifier: var_mod_type.into(),
                    }),
                    None => {
                        return Err(malformed_error!(
                            "Failed to resolve local variable modifier type - token 0x{:08X}",
                            var_mod.modifier_type.value()
                        ))
                    }
                }
            }

            self.local_vars.push(LocalVariable {
                modifiers,
                is_byref: local_var.is_byref,
                is_pinned: local_var.is_pinned,
                base: resolver.resolve(&local_var.base)?.into(),
            });
        }

        Ok(())
    }

    /// Resolves exception handler types for catch blocks.
    ///
    /// For EXCEPTION handlers, this resolves the type token stored in `filter_offset`
    /// to the actual type reference and clears the offset field.
    ///
    /// # Arguments
    /// * `body` - The method body with exception handlers to resolve
    /// * `types` - The type registry
    ///
    /// # Errors
    /// Returns an error if an exception type cannot be resolved.
    fn resolve_exception_handlers(body: &mut MethodBody, types: &Arc<TypeRegistry>) -> Result<()> {
        for (index, exception_handler) in body.exception_handlers.iter_mut().enumerate() {
            if exception_handler.flags == ExceptionHandlerFlags::EXCEPTION {
                let type_token = Token::new(exception_handler.filter_offset);
                let Some(handler_type) = types.get(&type_token) else {
                    return Err(malformed_error!(
                        "Failed to resolve exception handler {} type - token 0x{:08X}",
                        index,
                        exception_handler.filter_offset
                    ));
                };

                exception_handler.handler = Some(handler_type);
                exception_handler.filter_offset = 0;
            }
        }

        Ok(())
    }

    /// Resolves parameter signatures from the method signature.
    ///
    /// Maps each parameter from the Param table to its corresponding type
    /// information from the method signature.
    ///
    /// # Arguments
    /// * `types` - The type registry
    ///
    /// # Errors
    /// Returns an error if a parameter signature cannot be applied.
    fn resolve_parameter_signatures(&self, types: &Arc<TypeRegistry>) -> Result<()> {
        let method_param_count = Some(self.signature.params.len());

        for (_, parameter) in self.params.iter() {
            if parameter.sequence == 0 {
                // Sequence 0 is the return value
                parameter.apply_signature(
                    &self.signature.return_type,
                    types.clone(),
                    method_param_count,
                )?;
            } else {
                // Regular parameters (1-indexed in metadata)
                let index = (parameter.sequence - 1) as usize;
                if let Some(param_signature) = self.signature.params.get(index) {
                    parameter.apply_signature(
                        param_signature,
                        types.clone(),
                        method_param_count,
                    )?;
                }
            }
        }

        Ok(())
    }

    /// Parses vararg (variable argument) parameters from the method signature.
    ///
    /// # Arguments
    /// * `types` - The type registry
    ///
    /// # Errors
    /// Returns an error if a vararg modifier type cannot be resolved.
    fn parse_varargs(&self, types: &Arc<TypeRegistry>) -> Result<()> {
        for vararg in &self.signature.varargs {
            let modifiers = Arc::new(boxcar::Vec::with_capacity(vararg.modifiers.len()));
            for modifier in &vararg.modifiers {
                match types.get(&modifier.modifier_type) {
                    Some(new_mod) => _ = modifiers.push(new_mod.into()),
                    None => {
                        return Err(malformed_error!(
                            "Failed to resolve vararg modifier type - token 0x{:08X}",
                            modifier.modifier_type.value()
                        ))
                    }
                }
            }

            let mut resolver = TypeResolver::new(types.clone());
            self.varargs.push(VarArg {
                modifiers,
                by_ref: vararg.by_ref,
                base: resolver.resolve(&vararg.base)?.into(),
            });
        }

        Ok(())
    }

    /// Checks if this method appears to be an event handler based on its signature.
    ///
    /// Event handlers typically follow a specific pattern:
    /// - Name starts with "On" or ends with "Handler", "_Click", "_Load", "_Changed"
    /// - Takes exactly 2 parameters (sender and event args)
    /// - Returns void
    ///
    /// This heuristic is useful for deobfuscation to identify methods that are likely
    /// entry points or callbacks that should be preserved.
    ///
    /// # Returns
    ///
    /// `true` if the method matches the event handler pattern.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::CilObject;
    /// use std::path::Path;
    ///
    /// let assembly = CilObject::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
    /// for entry in assembly.methods().iter() {
    ///     let method = entry.value();
    ///     if method.is_event_handler() {
    ///         println!("Event handler: {}", method.name);
    ///     }
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    #[must_use]
    pub fn is_event_handler(&self) -> bool {
        // Check for typical event handler patterns:
        // 1. Name patterns (OnX, X_Handler, etc.)
        let has_handler_name = self.name.starts_with("On")
            || self.name.ends_with("Handler")
            || self.name.ends_with("_Click")
            || self.name.ends_with("_Load")
            || self.name.ends_with("_Changed")
            || self.name.contains('_');

        // 2. Parameter count (typically 2: sender + event args)
        let has_two_params = self.signature.params.len() == 2;

        // 3. Void return type is typical but not required
        let is_void = matches!(self.signature.return_type.base, TypeSignature::Void);

        // A method is likely an event handler if it has the naming pattern
        // and the right parameter count
        has_handler_name && has_two_params && is_void
    }

    /// Builds and returns the SSA (Static Single Assignment) form for this method.
    ///
    /// SSA form is a program representation where each variable is assigned exactly
    /// once and defined before it is used. This is useful for dataflow analysis,
    /// optimization, and deobfuscation.
    ///
    /// The SSA is built from the method's control flow graph, using the method's
    /// parameter count and local variable count to properly set up the function.
    ///
    /// # Arguments
    ///
    /// * `assembly` - The [`CilObject`] containing this method for resolving method
    ///   signatures in call instructions. This enables correct argument tracking for
    ///   call/callvirt/newobj instructions.
    ///
    /// # Returns
    ///
    /// An [`SsaFunction`] representing this method in SSA form, or `None` if:
    /// - The method has no control flow graph
    /// - SSA construction fails
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::CilObject;
    /// use std::path::Path;
    ///
    /// let assembly = CilObject::from_path(Path::new("tests/samples/WindowsBase.dll"))?;
    /// for entry in assembly.methods().iter().take(5) {
    ///     let method = entry.value();
    ///     if let Some(ssa) = method.ssa(&assembly) {
    ///         println!("Method {} has {} SSA blocks",
    ///                  method.name, ssa.block_count());
    ///     }
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    #[must_use]
    pub fn ssa(&self, assembly: &CilObject) -> Option<SsaFunction> {
        let blocks = self.blocks.get()?;

        // Get CFG from method
        let cfg = self.cfg()?;

        // Compute argument and local counts
        let num_args = self.signature.params.len() + usize::from(self.signature.has_this);
        let num_locals = self.local_vars.count();

        // Create type context for type lookup during SSA construction
        let type_context = TypeContext::new(self, assembly);

        // Build SSA from CFG with type context (also sets original local types)
        let mut ssa = SsaConverter::build(&cfg, num_args, num_locals, Some(&type_context)).ok()?;

        // Populate exception handlers from method body
        if let Some(body) = self.body.get() {
            if !body.exception_handlers.is_empty() {
                // Exception handler offsets are relative to method body start.
                // Block offsets are absolute file offsets. Get base offset from first block.
                let base_offset = blocks.first().map_or(0, |b| b.offset);

                let ssa_handlers: Vec<SsaExceptionHandler> = body
                    .exception_handlers
                    .iter()
                    .enumerate()
                    .map(|(handler_idx, eh)| {
                        // Map offsets to block indices (add base_offset to convert relative to absolute)
                        let try_start_block = Self::find_block_at_offset(
                            blocks,
                            base_offset + eh.try_offset as usize,
                        );
                        let try_end_block = Self::find_block_at_offset(
                            blocks,
                            base_offset + (eh.try_offset + eh.try_length) as usize,
                        );

                        // For handler blocks, use the handler_entry info from decoder if available
                        let handler_start_block =
                            Self::find_handler_entry_block(blocks, handler_idx).or_else(|| {
                                Self::find_block_at_offset(
                                    blocks,
                                    base_offset + eh.handler_offset as usize,
                                )
                            });
                        let handler_end_block = Self::find_block_at_offset(
                            blocks,
                            base_offset + (eh.handler_offset + eh.handler_length) as usize,
                        );

                        let filter_start_block = if eh.flags == ExceptionHandlerFlags::FILTER {
                            Self::find_block_at_offset(
                                blocks,
                                base_offset + eh.filter_offset as usize,
                            )
                        } else {
                            None
                        };

                        // Get the class token for catch handlers
                        let class_token_or_filter = if eh.flags == ExceptionHandlerFlags::EXCEPTION
                        {
                            eh.handler.as_ref().map_or(0, |t| t.token.value())
                        } else if eh.flags == ExceptionHandlerFlags::FILTER {
                            eh.filter_offset
                        } else {
                            0
                        };

                        SsaExceptionHandler {
                            flags: eh.flags,
                            try_offset: eh.try_offset,
                            try_length: eh.try_length,
                            handler_offset: eh.handler_offset,
                            handler_length: eh.handler_length,
                            class_token_or_filter,
                            try_start_block,
                            try_end_block,
                            handler_start_block,
                            handler_end_block,
                            filter_start_block,
                        }
                    })
                    .collect();

                ssa.set_exception_handlers(ssa_handlers);
            }
        }

        Some(ssa)
    }

    /// Finds the block index that starts at or contains the given offset.
    fn find_block_at_offset(blocks: &[BasicBlock], offset: usize) -> Option<usize> {
        // First try exact match (block starting at this offset)
        if let Some(idx) = blocks.iter().position(|b| b.offset == offset) {
            return Some(idx);
        }

        // If no exact match, find block containing the offset
        blocks
            .iter()
            .position(|b| offset >= b.offset && offset < b.offset + b.size)
    }

    /// Finds the block that is marked as an entry point for the given handler index.
    fn find_handler_entry_block(blocks: &[BasicBlock], handler_index: usize) -> Option<usize> {
        blocks.iter().position(|b| {
            b.handler_entry
                .as_ref()
                .is_some_and(|info| info.handler_index == handler_index)
        })
    }

    /// Extracts the local variable types in signature format for code generation.
    ///
    /// This converts the resolved `LocalVariable` types back to `SignatureLocalVariable`
    /// format, preserving the modifier semantics (required vs optional) that are needed
    /// for correct signature encoding.
    ///
    /// # Returns
    ///
    /// `Some(Vec<SignatureLocalVariable>)` if all local variables could be converted,
    /// `None` if the method has no locals or conversion failed.
    #[must_use]
    pub fn get_local_type_signatures(&self) -> Option<Vec<SignatureLocalVariable>> {
        if self.local_vars.is_empty() {
            return None;
        }

        // Convert each LocalVariable to SignatureLocalVariable
        // Note: boxcar::Vec::iter() yields (index, &value) tuples
        self.local_vars
            .iter()
            .map(|(_, local)| local.to_signature_local())
            .collect()
    }

    /// Encodes the method body to a byte vector.
    ///
    /// This method serializes the complete method body including:
    /// - Method header (tiny or fat format as appropriate)
    /// - All CIL instructions from basic blocks
    /// - Exception handler sections (if any)
    ///
    /// The output format is compatible with ECMA-335 II.25.4 and can be
    /// directly written to a PE file's .text section.
    ///
    /// # Returns
    ///
    /// Returns `Ok(Vec<u8>)` containing the complete encoded method body,
    /// or `Err` if the method has no body or encoding fails.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The method has no body (abstract, native, or runtime methods)
    /// - Instruction encoding fails
    /// - Exception handler encoding fails
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::CilObject;
    /// use std::path::Path;
    ///
    /// let assembly = CilObject::from_path(Path::new("test.dll"))?;
    /// for entry in assembly.methods().iter() {
    ///     let method = entry.value();
    ///     if let Ok(bytes) = method.encode_body() {
    ///         println!("Method {} encoded to {} bytes", method.name, bytes.len());
    ///     }
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn encode_body(&self) -> Result<Vec<u8>> {
        // Get the method body - if no body, this is an abstract/native/runtime method
        let body = self
            .body
            .get()
            .ok_or_else(|| malformed_error!("Method {} has no body to encode", self.name))?;

        // Get the basic blocks containing instructions
        let blocks = self
            .blocks
            .get()
            .ok_or_else(|| malformed_error!("Method {} has no decoded blocks", self.name))?;

        // Encode all instructions using InstructionEncoder
        let mut encoder = InstructionEncoder::new();

        for block in blocks {
            for instruction in &block.instructions {
                // Convert Operand to Option<Operand> for the encoder
                let operand = match &instruction.operand {
                    crate::assembly::Operand::None => None,
                    op => Some(op.clone()),
                };
                encoder.emit_instruction(instruction.mnemonic, operand)?;
            }
        }

        // Finalize to get the IL bytecode and max stack
        let (il_code, max_stack, _) = encoder.finalize()?;

        // Determine if we have exception handlers
        let has_exceptions = !body.exception_handlers.is_empty();

        // Calculate IL code size, ensuring it fits in u32
        let il_code_size = u32::try_from(il_code.len())
            .map_err(|_| malformed_error!("IL code size {} exceeds u32 range", il_code.len()))?;

        // Encode the method header
        let header = encode_method_body_header(
            il_code_size,
            max_stack,
            body.local_var_sig_token,
            has_exceptions,
            body.is_init_local,
        )?;

        // Build the complete method body
        let mut result = header;
        result.extend_from_slice(&il_code);

        // If fat format with exceptions, align to 4 bytes and add exception handlers
        if has_exceptions {
            // Align to 4-byte boundary
            let padding = (4 - (result.len() % 4)) % 4;
            result.extend(std::iter::repeat_n(0u8, padding));

            // Encode and append exception handlers
            let exception_data = encode_exception_handlers(&body.exception_handlers)?;
            result.extend_from_slice(&exception_data);
        }

        Ok(result)
    }

    /// Returns the total encoded size of this method body in bytes.
    ///
    /// This calculates the size without actually encoding, useful for
    /// layout planning. The size includes header, IL code, alignment
    /// padding, and exception handler sections.
    ///
    /// # Returns
    ///
    /// Returns `Some(size)` if the method has a body, `None` otherwise.
    #[must_use]
    pub fn encoded_size(&self) -> Option<usize> {
        let body = self.body.get()?;
        let blocks = self.blocks.get()?;

        // Calculate IL code size from instructions
        let mut code_size = 0usize;
        for block in blocks {
            for instruction in &block.instructions {
                // instruction.size is u64, safely convert to usize
                code_size += usize::try_from(instruction.size).ok()?;
            }
        }

        // Determine header size
        let has_exceptions = !body.exception_handlers.is_empty();
        let has_locals = body.local_var_sig_token != 0;
        let needs_fat = code_size > 63 || body.max_stack > 8 || has_locals || has_exceptions;

        let header_size = if needs_fat { 12 } else { 1 };

        let mut total = header_size + code_size;

        // Add exception handler section size if needed
        if has_exceptions {
            // Align to 4 bytes
            total = (total + 3) & !3;

            // Calculate exception section size
            let handler_count = body.exception_handlers.len();
            // Check if we need fat format for exception handlers
            let needs_fat_exceptions = handler_count > 20
                || body.exception_handlers.iter().any(|h| {
                    h.try_offset > 0xFFFF
                        || h.try_length > 0xFF
                        || h.handler_offset > 0xFFFF
                        || h.handler_length > 0xFF
                });

            if needs_fat_exceptions {
                // Fat format: 4-byte header + 24 bytes per handler
                total += 4 + handler_count * 24;
            } else {
                // Small format: 4-byte header + 12 bytes per handler
                total += 4 + handler_count * 12;
            }
        }

        Some(total)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::assembly::{
        BasicBlock, FlowType, Instruction, InstructionCategory, Operand, StackBehavior,
    };
    use crate::test::builders::MethodBuilder;

    #[test]
    fn test_instructions_iterator_empty_method() {
        // Create a method with no basic blocks
        let blocks = Vec::new();
        let method = create_test_method(blocks);

        let mut instruction_count = 0;
        for _instruction in method.instructions() {
            instruction_count += 1;
        }

        assert_eq!(instruction_count, 0);
        assert_eq!(method.instruction_count(), 0);
    }

    #[test]
    fn test_instructions_iterator_single_block() {
        // Create a method with one basic block containing multiple instructions
        let block = BasicBlock {
            id: 0,
            rva: 0x1000,
            offset: 0,
            size: 10,
            instructions: vec![
                create_test_instruction(0x00, "nop"),     // nop
                create_test_instruction(0x02, "ldarg.0"), // ldarg.0
                create_test_instruction(0x2A, "ret"),     // ret
            ],
            predecessors: vec![],
            successors: vec![],
            exceptions: vec![],
            handler_entry: None,
            exception_successors: vec![],
        };

        let blocks = vec![block];
        let method = create_test_method(blocks);

        let instructions: Vec<_> = method.instructions().collect();
        assert_eq!(instructions.len(), 3);
        assert_eq!(method.instruction_count(), 3);

        // Verify the instructions are returned in order
        assert_eq!(instructions[0].mnemonic, "nop");
        assert_eq!(instructions[1].mnemonic, "ldarg.0");
        assert_eq!(instructions[2].mnemonic, "ret");
    }

    #[test]
    fn test_instructions_iterator_multiple_blocks() {
        // Create a method with multiple basic blocks
        let block1 = BasicBlock {
            id: 0,
            rva: 0x1000,
            offset: 0,
            size: 5,
            instructions: vec![
                create_test_instruction(0x02, "ldarg.0"),
                create_test_instruction(0x03, "ldarg.1"),
            ],
            predecessors: vec![],
            successors: vec![1],
            exceptions: vec![],
            handler_entry: None,
            exception_successors: vec![],
        };

        let block2 = BasicBlock {
            id: 1,
            rva: 0x1010,
            offset: 5,
            size: 5,
            instructions: vec![
                create_test_instruction(0x58, "add"),
                create_test_instruction(0x2A, "ret"),
            ],
            predecessors: vec![0],
            successors: vec![],
            exceptions: vec![],
            handler_entry: None,
            exception_successors: vec![],
        };

        let blocks = vec![block1, block2];
        let method = create_test_method(blocks);

        let instructions: Vec<_> = method.instructions().collect();
        assert_eq!(instructions.len(), 4);
        assert_eq!(method.instruction_count(), 4);

        // Verify the instructions are returned in block order
        assert_eq!(instructions[0].mnemonic, "ldarg.0");
        assert_eq!(instructions[1].mnemonic, "ldarg.1");
        assert_eq!(instructions[2].mnemonic, "add");
        assert_eq!(instructions[3].mnemonic, "ret");
    }

    #[test]
    fn test_instruction_iterator_size_hint() {
        let block = BasicBlock {
            id: 0,
            rva: 0x1000,
            offset: 0,
            size: 3,
            instructions: vec![
                create_test_instruction(0x00, "nop"),
                create_test_instruction(0x00, "nop"),
                create_test_instruction(0x2A, "ret"),
            ],
            predecessors: vec![],
            successors: vec![],
            exceptions: vec![],
            handler_entry: None,
            exception_successors: vec![],
        };

        let blocks = vec![block];
        let method = create_test_method(blocks);
        let mut iter = method.instructions();

        // Initial size hint should be (3, Some(3))
        assert_eq!(iter.size_hint(), (3, Some(3)));

        // After consuming one instruction
        iter.next();
        assert_eq!(iter.size_hint(), (2, Some(2)));

        // After consuming all instructions
        iter.next();
        iter.next();
        assert_eq!(iter.size_hint(), (0, Some(0)));
    }

    // Helper function to create a test method with the given blocks
    fn create_test_method(blocks: Vec<BasicBlock>) -> MethodRc {
        let method = MethodBuilder::new().with_name("TestMethod").build();

        // Set the blocks in the method (this is test-specific setup)
        method.blocks.set(blocks).ok();

        method
    }

    // Helper function to create a test instruction
    fn create_test_instruction(opcode: u8, mnemonic: &'static str) -> Instruction {
        Instruction {
            rva: 0x1000,
            offset: 0,
            size: 1,
            opcode,
            prefix: 0,
            mnemonic,
            category: InstructionCategory::Misc,
            flow_type: FlowType::Sequential,
            operand: Operand::None,
            stack_behavior: StackBehavior {
                pops: 0,
                pushes: 0,
                net_effect: 0,
            },
            branch_targets: vec![],
        }
    }

    // Helper function to create an empty basic block
    fn create_empty_block(id: usize) -> BasicBlock {
        BasicBlock {
            id,
            rva: 0x1000 + (id as u64 * 0x10),
            offset: id * 10,
            size: 0,
            instructions: vec![],
            predecessors: vec![],
            successors: vec![],
            exceptions: vec![],
            handler_entry: None,
            exception_successors: vec![],
        }
    }

    #[test]
    fn test_instructions_iterator_with_empty_blocks() {
        // Test that the iterator handles empty blocks correctly (MTH-H001 fix verification)
        let block1 = create_empty_block(0);
        let block2 = BasicBlock {
            id: 1,
            rva: 0x1010,
            offset: 10,
            size: 3,
            instructions: vec![
                create_test_instruction(0x00, "nop"),
                create_test_instruction(0x2A, "ret"),
            ],
            predecessors: vec![],
            successors: vec![],
            exceptions: vec![],
            handler_entry: None,
            exception_successors: vec![],
        };
        let block3 = create_empty_block(2);

        let blocks = vec![block1, block2, block3];
        let method = create_test_method(blocks);

        let instructions: Vec<_> = method.instructions().collect();
        assert_eq!(instructions.len(), 2);
        assert_eq!(instructions[0].mnemonic, "nop");
        assert_eq!(instructions[1].mnemonic, "ret");
    }

    #[test]
    fn test_instructions_iterator_many_empty_blocks() {
        // Stress test: many consecutive empty blocks should not cause stack overflow
        // This verifies the MTH-H001 fix (recursive -> iterative)
        let mut blocks: Vec<BasicBlock> = (0..100).map(create_empty_block).collect();

        // Add one block with instructions at the end
        blocks.push(BasicBlock {
            id: 100,
            rva: 0x2000,
            offset: 1000,
            size: 1,
            instructions: vec![create_test_instruction(0x2A, "ret")],
            predecessors: vec![],
            successors: vec![],
            exceptions: vec![],
            handler_entry: None,
            exception_successors: vec![],
        });

        let method = create_test_method(blocks);

        let instructions: Vec<_> = method.instructions().collect();
        assert_eq!(instructions.len(), 1);
        assert_eq!(instructions[0].mnemonic, "ret");
    }

    #[test]
    fn test_instructions_iterator_all_empty_blocks() {
        // Edge case: all blocks are empty
        let blocks: Vec<BasicBlock> = (0..10).map(create_empty_block).collect();
        let method = create_test_method(blocks);

        let instructions: Vec<_> = method.instructions().collect();
        assert_eq!(instructions.len(), 0);
        assert_eq!(method.instruction_count(), 0);
    }

    #[test]
    fn test_method_ref_basic_operations() {
        let method = MethodBuilder::new().with_name("TestMethod").build();

        let method_ref = MethodRef::new(&method);

        // Test is_valid
        assert!(method_ref.is_valid());

        // Test upgrade
        let upgraded = method_ref.upgrade();
        assert!(upgraded.is_some());
        assert_eq!(upgraded.unwrap().name, "TestMethod");

        // Test token - uses the default token from MethodBuilder (rid=1 => 0x06000001)
        assert_eq!(method_ref.token(), Some(Token::new(0x06000001)));

        // Test name
        assert_eq!(method_ref.name(), Some("TestMethod".to_string()));
    }

    #[test]
    fn test_method_ref_after_drop() {
        let method_ref = {
            let method = MethodBuilder::new().with_name("TemporaryMethod").build();
            MethodRef::new(&method)
            // method is dropped here
        };

        // After the method is dropped, MethodRef should return None/false
        assert!(!method_ref.is_valid());
        assert!(method_ref.upgrade().is_none());
        assert!(method_ref.token().is_none());
        assert!(method_ref.name().is_none());
    }

    #[test]
    fn test_method_is_constructor() {
        let ctor = MethodBuilder::new().with_name(".ctor").build();
        let cctor = MethodBuilder::new().with_name(".cctor").build();
        let regular = MethodBuilder::new().with_name("DoSomething").build();

        assert!(ctor.is_constructor());
        assert!(cctor.is_constructor());
        assert!(!regular.is_constructor());
    }

    #[test]
    fn test_is_forwarded_pinvoke() {
        // Test that the renamed method works correctly
        let method = MethodBuilder::new().with_name("TestMethod").build();

        // Default method should not have forwarded pinvoke flag
        assert!(!method.is_forwarded_pinvoke());
    }
}