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
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
//! Mutable assembly representation for editing and modification operations.
//!
//! This module provides [`crate::cilassembly::CilAssembly`], a comprehensive editing layer for .NET assemblies
//! that enables type-safe, efficient modification of metadata tables, heap content, and
//! cross-references while maintaining ECMA-335 compliance.
//!
//! # Design Philosophy
//!
//! ## **Copy-on-Write Semantics**
//! - Original [`crate::metadata::cilassemblyview::CilAssemblyView`] remains immutable and unchanged
//! - Modifications are tracked separately in [`crate::cilassembly::changes::AssemblyChanges`]
//! - Changes are lazily allocated only when modifications are made
//! - Read operations efficiently merge original data with changes
//!
//! ## **Memory Efficiency**
//! - **Sparse Tracking**: Only modified tables/heaps consume memory
//! - **Lazy Initialization**: Change structures created on first modification
//! - **Efficient Storage**: Operations stored chronologically with timestamps
//! - **Memory Estimation**: Built-in memory usage tracking and reporting
//!
//! # Core Components
//!
//! ## **Change Tracking ([`crate::cilassembly::changes::AssemblyChanges`])**
//! Central structure that tracks all modifications:
//! ```text
//! AssemblyChanges
//! ├── string_heap_changes: Option<HeapChanges<String>>      // #Strings (UTF-8)
//! ├── blob_heap_changes: Option<HeapChanges<Vec<u8>>>       // #Blob (binary)
//! ├── guid_heap_changes: Option<HeapChanges<[u8; 16]>>      // #GUID (16-byte)
//! ├── userstring_heap_changes: Option<HeapChanges<String>>  // #US (UTF-16)
//! └── table_changes: HashMap<TableId, TableModifications>
//! ```
//!
//! ## **Table Modifications ([`crate::cilassembly::modifications::TableModifications`])**
//! Two strategies for tracking table changes:
//! - **Sparse**: Individual operations (Insert/Update/Delete) with timestamps
//! - **Replaced**: Complete table replacement for heavily modified tables
//!
//! ## **Operation Types ([`crate::cilassembly::operation::Operation`])**
//! - **Insert(rid, data)**: Add new row with specific RID
//! - **Update(rid, data)**: Modify existing row data  
//! - **Delete(rid)**: Mark row as deleted
//!
//! ## **Validation System**
//! - **Configurable Pipeline**: Multiple validation stages
//! - **Conflict Detection**: Identifies conflicting operations
//! - **Resolution Strategies**: Last-write-wins, merge, reject, etc.
//! - **Cross-Reference Validation**: Ensures referential integrity
//!
//! ## **Index Remapping**
//! - **Heap Index Management**: Tracks new heap indices
//! - **RID Remapping**: Maps original RIDs to final RIDs after consolidation
//! - **Cross-Reference Updates**: Updates all references during binary generation
//!
//! # Usage Patterns
//!
//! ## **Basic Heap Modification**
//! ```rust,no_run
//! # use dotscope::{CilAssemblyView, CilAssembly};
//! # let view = CilAssemblyView::from_mem(vec![])?;
//! let mut assembly = CilAssembly::new(view);
//!
//! // Heap operations return indices for cross-referencing
//! let string_idx = assembly.string_add("MyString")?;
//! let blob_idx = assembly.blob_add(&[0x01, 0x02, 0x03])?;
//! let guid_idx = assembly.guid_add(&[0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0,
//!                                    0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88])?;
//! let userstring_idx = assembly.userstring_add("User String Literal")?;
//! # Ok::<(), dotscope::Error>(())
//! ```
//!
//! ## **Table Row Operations**
//! ```rust,no_run
//! # use dotscope::{CilAssemblyView, CilAssembly, metadata::tables::{TableId, TableDataOwned}};
//! # let view = CilAssemblyView::from_mem(vec![])?;
//! let mut assembly = CilAssembly::new(view);
//!
//! // Low-level table modification
//! // let row_data = TableDataOwned::TypeDef(/* ... */);
//! // let rid = assembly.add_table_row(TableId::TypeDef, row_data)?;
//! # Ok::<(), dotscope::Error>(())
//! ```
//!
//! ## **Validation and Consistency**
//! ```rust,no_run
//! # use dotscope::{CilAssemblyView, CilAssembly};
//! # let view = CilAssemblyView::from_mem(vec![])?;
//! let mut assembly = CilAssembly::new(view);
//!
//! // Make modifications...
//!
//! // Write to file or memory
//! assembly.to_file("output.dll")?;
//! // Or: let bytes = assembly.to_memory()?;
//! # Ok::<(), dotscope::Error>(())
//! ```
//!
//! # Module Organization
//!
//! Following "one type per file" for maintainability:
//!
//! ## **Core Types**
//! - [`crate::cilassembly::CilAssembly`] - Main mutable assembly (this file)
//! - [`crate::cilassembly::changes::AssemblyChanges`] - Central change tracking
//! - [`crate::cilassembly::changes::heap::HeapChanges`] - Heap modification tracking
//! - [`crate::cilassembly::modifications::TableModifications`] - Table change strategies
//! - [`crate::cilassembly::operation::TableOperation`] - Timestamped operations
//! - [`crate::cilassembly::operation::Operation`] - Operation variants
//!
//! ## **Conflict Resolution ([`crate::cilassembly::resolver`])**
//! Conflict resolution for handling competing operations:
//! - [`crate::cilassembly::resolver::ConflictResolver`] - Conflict resolution strategies
//! - [`crate::cilassembly::resolver::LastWriteWinsResolver`] - Default timestamp-based resolver
//! - [`crate::cilassembly::resolver::Conflict`] & [`crate::cilassembly::resolver::Resolution`] - Conflict types and results
//!
//! # Examples
//!
//! ```rust,no_run
//! use dotscope::{CilAssemblyView, CilAssembly};
//! use std::path::Path;
//!
//! // Load and convert to mutable assembly
//! let view = CilAssemblyView::from_path(Path::new("assembly.dll"))?;
//! let mut assembly = CilAssembly::new(view);
//!
//! // Add a string to the heap
//! let string_index = assembly.string_add("Hello, World!")?;
//!
//! // Write modified assembly to new file
//! assembly.to_file(Path::new("modified.dll"))?;
//! # Ok::<(), dotscope::Error>(())
//! ```
use std::path::Path;

use crate::{
    file::File,
    metadata::{
        cilassemblyview::CilAssemblyView,
        exports::UnifiedExportContainer,
        imports::UnifiedImportContainer,
        signatures::{
            encode_field_signature, encode_local_var_signature, encode_method_signature,
            encode_property_signature, encode_typespec_signature, SignatureField,
            SignatureLocalVariables, SignatureMethod, SignatureProperty, SignatureTypeSpec,
        },
        tables::{AssemblyRefRaw, CodedIndex, CodedIndexType, TableDataOwned, TableId},
        token::Token,
    },
    CilObject, Result, ValidationConfig,
};

mod builders;
mod changes;
mod cleanup;
mod modifications;
mod operation;
mod resolver;
mod writer;

pub use builders::{
    ClassBuilder, EnumBuilder, EventBuilder, InterfaceBuilder, MethodBodyBuilder, MethodBuilder,
    PropertyBuilder,
};
pub use changes::{AssemblyChanges, ChangeRef, ChangeRefKind, ChangeRefRc, HeapChanges};
pub use cleanup::CleanupRequest;
pub use modifications::TableModifications;
pub use operation::{Operation, TableOperation};
pub use resolver::LastWriteWinsResolver;
pub use writer::GeneratorConfig;
pub(crate) use writer::ResolvePlaceholders;

use writer::PeGenerator;

/// A mutable view of a .NET assembly that tracks changes for editing operations.
///
/// `CilAssembly` provides an editing layer on top of [`crate::metadata::cilassemblyview::CilAssemblyView`], using
/// a copy-on-write strategy to track modifications while preserving the original
/// assembly data. Changes are stored separately and merged when writing to disk.
///
/// # Thread Safety
///
/// `CilAssembly` is **not thread-safe** by default. For concurrent access, wrap in
/// appropriate synchronization primitives.
pub struct CilAssembly {
    view: CilAssemblyView,
    changes: AssemblyChanges,
    pending_cleanup: cleanup::CleanupRequest,
}

impl CilAssembly {
    /// Creates a new mutable assembly from a read-only view.
    ///
    /// This consumes the `CilAssemblyView` and creates a mutable editing layer
    /// on top of it.
    ///
    /// # Arguments
    ///
    /// * `view` - The read-only assembly view to wrap
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::{CilAssemblyView, CilAssembly};
    /// use std::path::Path;
    ///
    /// let view = CilAssemblyView::from_path(Path::new("assembly.dll"))?;
    /// let assembly = CilAssembly::new(view);
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    #[must_use]
    pub fn new(view: CilAssemblyView) -> Self {
        Self {
            changes: AssemblyChanges::new(),
            view,
            pending_cleanup: cleanup::CleanupRequest::new(),
        }
    }

    /// Creates a new mutable assembly by loading from a file path.
    ///
    /// # Arguments
    ///
    /// * `path` - Path to the .NET assembly file to load
    ///
    /// # Returns
    ///
    /// Returns a `CilAssembly` ready for modification operations.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::CilAssembly;
    /// use std::path::Path;
    ///
    /// let mut assembly = CilAssembly::from_path(Path::new("assembly.dll"))?;
    ///
    /// // Now ready to modify
    /// let string_index = assembly.string_add("Hello, World!")?;
    /// assembly.to_file(Path::new("modified.dll"))?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if the file cannot be loaded or parsed as a valid
    /// .NET assembly.
    pub fn from_path<P: AsRef<Path>>(path: P) -> Result<Self> {
        let view = CilAssemblyView::from_path(path)?;
        Ok(Self::new(view))
    }

    /// Creates a new mutable assembly by loading from a byte vector.
    ///
    /// # Arguments
    ///
    /// * `bytes` - The raw bytes of the .NET assembly
    ///
    /// # Returns
    ///
    /// Returns a `CilAssembly` ready for modification operations.
    ///
    /// # Errors
    ///
    /// Returns an error if the bytes cannot be parsed as a valid .NET assembly.
    pub fn from_bytes(bytes: Vec<u8>) -> Result<Self> {
        let view = CilAssemblyView::from_mem(bytes)?;
        Ok(Self::new(view))
    }

    /// Creates a new mutable assembly by loading from a byte vector with custom validation.
    ///
    /// # Arguments
    ///
    /// * `bytes` - The raw bytes of the .NET assembly
    /// * `validation_config` - Validation configuration
    ///
    /// # Returns
    ///
    /// Returns a `CilAssembly` ready for modification operations.
    ///
    /// # Errors
    ///
    /// Returns an error if the bytes cannot be parsed as a valid .NET assembly.
    pub fn from_bytes_with_validation(
        bytes: Vec<u8>,
        validation_config: ValidationConfig,
    ) -> Result<Self> {
        let view = CilAssemblyView::from_mem_with_validation(bytes, validation_config)?;
        Ok(Self::new(view))
    }

    /// Adds a cleanup request to be executed before PE generation.
    ///
    /// Multiple cleanup requests can be added and will be merged together.
    /// The cleanup is executed once when `to_file()`, `to_memory()`, or similar
    /// generation methods are called.
    ///
    /// # Arguments
    ///
    /// * `request` - The cleanup request specifying what to remove
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use dotscope::CilAssembly;
    /// # use dotscope::metadata::token::Token;
    /// # let mut assembly = CilAssembly::from_path("input.dll")?;
    /// # let protection_type_token = Token::new(0x02000001);
    /// # let decryptor_method_token = Token::new(0x06000001);
    /// let mut request = dotscope::CleanupRequest::new();
    /// request.add_type(protection_type_token);
    /// request.add_method(decryptor_method_token);
    ///
    /// assembly.add_cleanup(&request);
    ///
    /// // Cleanup executes automatically during generation
    /// assembly.to_file("output.dll")?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn add_cleanup(&mut self, request: &cleanup::CleanupRequest) {
        self.pending_cleanup.merge(request);
    }

    /// Returns a reference to the pending cleanup request.
    ///
    /// This can be used to inspect what cleanup operations are queued.
    #[must_use]
    pub fn pending_cleanup(&self) -> &cleanup::CleanupRequest {
        &self.pending_cleanup
    }

    /// Executes pending cleanup, adding deletions to AssemblyChanges.
    ///
    /// This is called internally before PE generation. It can only be called
    /// once because row deletions cause RID shifting.
    ///
    /// # Returns
    ///
    /// Statistics about what was removed during cleanup.
    ///
    /// # Errors
    ///
    /// Returns an error if cleanup execution fails.
    fn finalize_for_generation(&mut self) -> Result<cleanup::CleanupStats> {
        if self.pending_cleanup.is_empty() {
            return Ok(cleanup::CleanupStats::new());
        }

        // Take ownership of the request (clears pending_cleanup and avoids borrow conflict)
        let request = std::mem::take(&mut self.pending_cleanup);

        // Execute cleanup ONCE - this adds all deletions to self.changes
        let stats = cleanup::execute_cleanup(self, &request)?;
        Ok(stats)
    }

    /// Adds a string to the string heap (#Strings) and returns its index.
    ///
    /// The string is appended to the string heap, maintaining the original
    /// heap structure. The returned index can be used to reference this
    /// string from metadata table rows.
    ///
    /// **Note**: Strings in the #Strings heap are UTF-8 encoded when written
    /// to the binary. This method stores the logical string value
    /// during the editing phase.
    ///
    /// # Arguments
    ///
    /// * `value` - The string to add to the heap
    ///
    /// # Returns
    ///
    /// Returns the heap index that can be used to reference this string.
    /// Indices are 1-based following ECMA-335 conventions.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use dotscope::{CilAssemblyView, CilAssembly};
    /// # use std::path::Path;
    /// # let view = CilAssemblyView::from_path(&Path::new("assembly.dll"))?;
    /// let mut assembly = CilAssembly::new(view);
    ///
    /// let hello_ref = assembly.string_add("Hello")?;
    /// let world_ref = assembly.string_add("World")?;
    ///
    /// // Each addition returns a unique reference
    /// assert_ne!(hello_ref, world_ref);
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Currently this function does not return errors, but the Result type is
    /// reserved for future enhancements that may require error handling.
    pub fn string_add(&mut self, value: &str) -> Result<ChangeRefRc> {
        let change_ref = self.changes.string_heap_changes.append(value.to_string());
        Ok(change_ref)
    }

    /// Adds a blob to the blob heap and returns its index.
    ///
    /// The blob data is appended to the blob heap, maintaining the original
    /// heap structure. The returned index can be used to reference this
    /// blob from metadata table rows.
    ///
    /// # Arguments
    ///
    /// * `data` - The blob data to add to the heap
    ///
    /// # Returns
    ///
    /// Returns the heap index that can be used to reference this blob.
    /// Indices are 1-based following ECMA-335 conventions.
    ///
    /// # Errors
    ///
    /// Returns an error if the blob cannot be added to the heap.
    pub fn blob_add(&mut self, data: &[u8]) -> Result<ChangeRefRc> {
        let change_ref = self.changes.blob_heap_changes.append(data.to_vec());
        Ok(change_ref)
    }

    /// Adds a GUID to the GUID heap and returns its index.
    ///
    /// The GUID is appended to the GUID heap, maintaining the original
    /// heap structure. The returned index can be used to reference this
    /// GUID from metadata table rows.
    ///
    /// # Arguments
    ///
    /// * `guid` - The 16-byte GUID to add to the heap
    ///
    /// # Returns
    ///
    /// Returns the heap index that can be used to reference this GUID.
    /// Indices are 1-based following ECMA-335 conventions.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use dotscope::{CilAssemblyView, CilAssembly};
    /// # use std::path::Path;
    /// # let view = CilAssemblyView::from_path(&Path::new("assembly.dll"))?;
    /// let mut assembly = CilAssembly::new(view);
    ///
    /// let guid = [0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0,
    ///             0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88];
    /// let guid_index = assembly.guid_add(&guid)?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if the GUID cannot be added to the heap.
    pub fn guid_add(&mut self, guid: &[u8; 16]) -> Result<ChangeRefRc> {
        let change_ref = self.changes.guid_heap_changes.append(*guid);
        Ok(change_ref)
    }

    /// Adds a user string to the user string heap (#US) and returns its index.
    ///
    /// The user string is appended to the user string heap (#US), maintaining
    /// the original heap structure. User strings are used for string literals
    /// in IL code (e.g., `ldstr` instruction operands) and are stored with
    /// length prefixes and UTF-16 encoding when written to the binary.
    ///
    /// **Note**: User strings in the #US heap are UTF-16 encoded with compressed
    /// length prefixes when written to the binary. This method calculates API
    /// indices based on final string sizes after considering modifications to
    /// ensure consistency with the writer and size calculation logic.
    ///
    /// # Arguments
    ///
    /// * `value` - The string to add to the user string heap
    ///
    /// # Returns
    ///
    /// Returns the heap index that can be used to reference this user string.
    /// Indices are 1-based following ECMA-335 conventions.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use dotscope::{CilAssemblyView, CilAssembly};
    /// # use std::path::Path;
    /// # let view = CilAssemblyView::from_path(&Path::new("assembly.dll"))?;
    /// let mut assembly = CilAssembly::new(view);
    ///
    /// let userstring_index = assembly.userstring_add("Hello, World!")?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if the user string cannot be added to the heap.
    pub fn userstring_add(&mut self, value: &str) -> Result<ChangeRefRc> {
        let change_ref = self
            .changes
            .userstring_heap_changes
            .append(value.to_string());
        Ok(change_ref)
    }

    /// Adds resource data to the CLR resources section and returns its offset.
    ///
    /// This stores the resource data in the CLR resources section (not the blob heap)
    /// with the proper .NET format: 4-byte little-endian length prefix followed by the data.
    /// The returned offset should be used as the `offset_field` in ManifestResource table entries.
    ///
    /// The offset is automatically adjusted to account for any existing resources in the
    /// original assembly, since new resources are appended after original ones.
    ///
    /// # Arguments
    ///
    /// * `data` - The raw resource data bytes to store
    ///
    /// # Returns
    ///
    /// Returns the offset within the resources section where this resource starts.
    /// This offset points to the length prefix, which is how ManifestResource.offset_field works.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use dotscope::{CilAssemblyView, CilAssembly};
    /// # use std::path::Path;
    /// # let view = CilAssemblyView::from_path(&Path::new("assembly.dll"))?;
    /// let mut assembly = CilAssembly::new(view);
    ///
    /// let resource_data = b"Hello, Resource!";
    /// let offset = assembly.resource_data_add(resource_data);
    /// // Use offset as ManifestResource.offset_field
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn resource_data_add(&mut self, data: &[u8]) -> u32 {
        // Get the offset within our new resource data buffer
        let new_offset = self.changes.store_resource_data(data);

        // Add the original resource size since new resources are appended after original ones
        // This ensures ManifestResource.offset_field points to the correct location
        let original_size = self.view.cor20header().resource_size;
        new_offset + original_size
    }

    /// Updates an existing string in the string heap at the specified index.
    ///
    /// This modifies the string at the given heap index. The reference handling
    /// is not needed for modifications since the index remains the same.
    ///
    /// # Arguments
    ///
    /// * `index` - The heap index to modify (1-based, following ECMA-335 conventions)
    /// * `new_value` - The new string value to store at that index
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` if the modification was successful.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use dotscope::{CilAssemblyView, CilAssembly};
    /// # use std::path::Path;
    /// # let view = CilAssemblyView::from_path(&Path::new("assembly.dll"))?;
    /// let mut assembly = CilAssembly::new(view);
    ///
    /// // Modify an existing string at index 42
    /// assembly.string_update(42, "Updated String")?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if the string cannot be updated.
    pub fn string_update(&mut self, index: u32, new_value: &str) -> Result<()> {
        self.changes
            .string_heap_changes
            .add_modification(index, new_value.to_string());
        Ok(())
    }

    /// Removes a string from the string heap at the specified index.
    ///
    /// This marks the string at the given heap index for removal.
    ///
    /// # Arguments
    ///
    /// * `index` - The heap index to remove (1-based, following ECMA-335 conventions)
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` if the removal was successful.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use dotscope::{CilAssembly, CilAssemblyView};
    /// # use std::path::Path;
    /// # let view = CilAssemblyView::from_path(&Path::new("assembly.dll"))?;
    /// let mut assembly = CilAssembly::new(view);
    ///
    /// // Remove string at index 42
    /// assembly.string_remove(42)?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if the string cannot be removed.
    pub fn string_remove(&mut self, index: u32) -> Result<()> {
        let original_heap_size = self
            .view()
            .streams()
            .iter()
            .find(|s| s.name == "#Strings")
            .map_or(0, |s| s.size);

        if index >= original_heap_size {
            self.changes
                .string_heap_changes
                .mark_appended_for_removal(index);
        } else {
            self.changes.string_heap_changes.add_removal(index);
        }
        Ok(())
    }

    /// Updates an existing blob in the blob heap at the specified index.
    ///
    /// # Arguments
    ///
    /// * `index` - The heap index to modify (1-based, following ECMA-335 conventions)
    /// * `new_data` - The new blob data to store at that index
    ///
    /// # Errors
    ///
    /// Returns an error if the blob cannot be updated.
    pub fn blob_update(&mut self, index: u32, new_data: &[u8]) -> Result<()> {
        self.changes
            .blob_heap_changes
            .add_modification(index, new_data.to_vec());
        Ok(())
    }

    /// Removes a blob from the blob heap at the specified index.
    ///
    /// # Arguments
    ///
    /// * `index` - The heap index to remove (1-based, following ECMA-335 conventions)
    ///
    /// # Errors
    ///
    /// Returns an error if the blob cannot be removed.
    pub fn blob_remove(&mut self, index: u32) -> Result<()> {
        self.changes.blob_heap_changes.add_removal(index);
        Ok(())
    }

    /// Updates an existing GUID in the GUID heap at the specified index.
    ///
    /// # Arguments
    ///
    /// * `index` - The heap index to modify. This can be either:
    ///   - A 1-based sequential index (following ECMA-335 conventions) for existing GUIDs
    ///   - A placeholder value from a ChangeRef for newly added GUIDs
    /// * `new_guid` - The new 16-byte GUID to store at that index
    ///
    /// # Errors
    ///
    /// Currently always succeeds, but returns `Result` for future extensibility.
    pub fn guid_update(&mut self, index: u32, new_guid: &[u8; 16]) -> Result<()> {
        // Check if this is a placeholder value (from a newly added GUID)
        // Placeholders have the high bit or marker bit set
        let lookup_key = if ChangeRef::is_placeholder(index) {
            // For placeholders, use directly - the streaming code looks up by placeholder
            index
        } else {
            // For existing GUIDs, convert 1-based sequential index to byte offset
            // GUID heap uses byte offsets internally: byte_offset = (index - 1) * 16
            index.saturating_sub(1).saturating_mul(16)
        };
        self.changes
            .guid_heap_changes
            .add_modification(lookup_key, *new_guid);
        Ok(())
    }

    /// Removes a GUID from the GUID heap at the specified index.
    ///
    /// # Arguments
    ///
    /// * `index` - The heap index to remove. This can be either:
    ///   - A 1-based sequential index (following ECMA-335 conventions) for existing GUIDs
    ///   - A placeholder value from a ChangeRef for newly added GUIDs
    ///
    /// # Errors
    ///
    /// Currently always succeeds, but returns `Result` for future extensibility.
    pub fn guid_remove(&mut self, index: u32) -> Result<()> {
        // Check if this is a placeholder value (from a newly added GUID)
        let lookup_key = if ChangeRef::is_placeholder(index) {
            index
        } else {
            // Convert 1-based sequential index to byte offset
            index.saturating_sub(1).saturating_mul(16)
        };
        self.changes.guid_heap_changes.add_removal(lookup_key);
        Ok(())
    }

    /// Updates an existing user string in the user string heap at the specified index.
    ///
    /// # Arguments
    ///
    /// * `index` - The heap index to modify (1-based, following ECMA-335 conventions)
    /// * `new_value` - The new string value to store at that index
    ///
    /// # Errors
    ///
    /// Currently always succeeds, but returns `Result` for future extensibility.
    pub fn userstring_update(&mut self, index: u32, new_value: &str) -> Result<()> {
        self.changes
            .userstring_heap_changes
            .add_modification(index, new_value.to_string());
        Ok(())
    }

    /// Removes a user string from the user string heap at the specified index.
    ///
    /// # Arguments
    ///
    /// * `index` - The heap index to remove (1-based, following ECMA-335 conventions)
    ///
    /// # Errors
    ///
    /// Currently always succeeds, but returns `Result` for future extensibility.
    pub fn userstring_remove(&mut self, index: u32) -> Result<()> {
        self.changes.userstring_heap_changes.add_removal(index);
        Ok(())
    }

    /// Replaces the entire string heap (#Strings) with the provided raw data.
    ///
    /// This completely replaces the string heap content, ignoring the original heap.
    /// If there is no existing string heap, a new one will be created. All subsequent
    /// append/modify/remove operations will be applied to this replacement heap
    /// instead of the original.
    ///
    /// # Arguments
    ///
    /// * `heap_data` - The raw bytes that will form the new string heap
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use dotscope::{CilAssemblyView, CilAssembly};
    /// # use std::path::Path;
    /// # let view = CilAssemblyView::from_path(&Path::new("assembly.dll"))?;
    /// let mut assembly = CilAssembly::new(view);
    ///
    /// // Replace with custom string heap containing "Hello\0World\0"
    /// let custom_heap = b"Hello\0World\0".to_vec();
    /// assembly.string_add_heap(custom_heap)?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Currently always succeeds, but returns `Result` for future extensibility.
    pub fn string_add_heap(&mut self, heap_data: Vec<u8>) -> Result<()> {
        self.changes.string_heap_changes.replace_heap(heap_data);
        Ok(())
    }

    /// Replaces the entire blob heap (#Blob) with the provided raw data.
    ///
    /// This completely replaces the blob heap content, ignoring the original heap.
    /// If there is no existing blob heap, a new one will be created. All subsequent
    /// append/modify/remove operations will be applied to this replacement heap
    /// instead of the original.
    ///
    /// # Arguments
    ///
    /// * `heap_data` - The raw bytes that will form the new blob heap
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use dotscope::{CilAssemblyView, CilAssembly};
    /// # use std::path::Path;
    /// # let view = CilAssemblyView::from_path(&Path::new("assembly.dll"))?;
    /// let mut assembly = CilAssembly::new(view);
    ///
    /// // Replace with custom blob heap containing length-prefixed blobs
    /// let custom_heap = vec![0x03, 0x01, 0x02, 0x03, 0x02, 0xFF, 0xFE];
    /// assembly.blob_add_heap(custom_heap)?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Currently always succeeds, but returns `Result` for future extensibility.
    pub fn blob_add_heap(&mut self, heap_data: Vec<u8>) -> Result<()> {
        self.changes.blob_heap_changes.replace_heap(heap_data);
        Ok(())
    }

    /// Replaces the entire GUID heap (#GUID) with the provided raw data.
    ///
    /// This completely replaces the GUID heap content, ignoring the original heap.
    /// If there is no existing GUID heap, a new one will be created. All subsequent
    /// append/modify/remove operations will be applied to this replacement heap
    /// instead of the original.
    ///
    /// # Arguments
    ///
    /// * `heap_data` - The raw bytes that will form the new GUID heap (must be 16-byte aligned)
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use dotscope::{CilAssemblyView, CilAssembly};
    /// # use std::path::Path;
    /// # let view = CilAssemblyView::from_path(&Path::new("assembly.dll"))?;
    /// let mut assembly = CilAssembly::new(view);
    ///
    /// // Replace with custom GUID heap containing one GUID
    /// let guid = [0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0,
    ///             0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77, 0x88];
    /// assembly.guid_add_heap(guid.to_vec())?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Currently always succeeds, but returns `Result` for future extensibility.
    pub fn guid_add_heap(&mut self, heap_data: Vec<u8>) -> Result<()> {
        self.changes.guid_heap_changes.replace_heap(heap_data);
        Ok(())
    }

    /// Replaces the entire user string heap (#US) with the provided raw data.
    ///
    /// This completely replaces the user string heap content, ignoring the original heap.
    /// If there is no existing user string heap, a new one will be created. All subsequent
    /// append/modify/remove operations will be applied to this replacement heap
    /// instead of the original.
    ///
    /// # Arguments
    ///
    /// * `heap_data` - The raw bytes that will form the new user string heap
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use dotscope::{CilAssemblyView, CilAssembly};
    /// # use std::path::Path;
    /// # let view = CilAssemblyView::from_path(&Path::new("assembly.dll"))?;
    /// let mut assembly = CilAssembly::new(view);
    ///
    /// // Replace with custom user string heap containing UTF-16 strings with length prefixes
    /// let custom_heap = vec![0x07, 0x48, 0x00, 0x65, 0x00, 0x6C, 0x00, 0x01]; // "Hel" + terminator
    /// assembly.userstring_add_heap(custom_heap)?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Currently always succeeds, but returns `Result` for future extensibility.
    pub fn userstring_add_heap(&mut self, heap_data: Vec<u8>) -> Result<()> {
        self.changes.userstring_heap_changes.replace_heap(heap_data);
        Ok(())
    }

    /// Updates an existing table row at the specified RID.
    ///
    /// This modifies the row data at the given RID in the specified table.
    ///
    /// # Arguments
    ///
    /// * `table_id` - The table containing the row to modify
    /// * `rid` - The Row ID to modify (1-based, following ECMA-335 conventions)
    /// * `new_row` - The new row data to store at that RID
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` if the modification was successful.
    ///
    /// # Errors
    ///
    /// Returns an error if the table operation fails or the provided row data is invalid.
    pub fn table_row_update(
        &mut self,
        table_id: TableId,
        rid: u32,
        new_row: TableDataOwned,
    ) -> Result<()> {
        let original_count = self.original_table_row_count(table_id);
        let table_changes = self
            .changes
            .table_changes
            .entry(table_id)
            .or_insert_with(|| TableModifications::new_sparse(original_count + 1));

        let operation = Operation::Update(rid, new_row);
        let table_operation = TableOperation::new(operation);
        table_changes.apply_operation(table_operation)?;
        Ok(())
    }

    /// Removes a table row at the specified RID.
    ///
    /// This marks the row at the given RID for deletion.
    ///
    /// # Arguments
    ///
    /// * `table_id` - The table containing the row to remove
    /// * `rid` - The Row ID to remove (1-based, following ECMA-335 conventions)
    ///
    /// # Returns
    ///
    /// Returns `Ok(())` if the removal was successful.
    ///
    /// # Errors
    ///
    /// Returns an error if the table operation fails or the specified row does not exist.
    pub fn table_row_remove(&mut self, table_id: TableId, rid: u32) -> Result<()> {
        let original_count = self.original_table_row_count(table_id);
        let table_changes = self
            .changes
            .table_changes
            .entry(table_id)
            .or_insert_with(|| TableModifications::new_sparse(original_count + 1));

        let operation = Operation::Delete(rid);
        let table_operation = TableOperation::new(operation);
        table_changes.apply_operation(table_operation)?;

        Ok(())
    }

    /// Basic table row addition.
    ///
    /// This is the foundational method for adding rows to tables.
    ///
    /// # Arguments
    ///
    /// * `table_id` - The table to add the row to
    /// * `row` - The row data to add
    ///
    /// # Returns
    ///
    /// Returns a [`ChangeRefRc`] that will be resolved to the final token/RID after
    /// the assembly is written. Use `placeholder()` on the returned reference to get
    /// a value that can be stored in other table rows and will be resolved at write time.
    ///
    /// # Errors
    ///
    /// Returns an error if the table cannot be converted to sparse mode.
    pub fn table_row_add(&mut self, table_id: TableId, row: TableDataOwned) -> Result<ChangeRefRc> {
        let original_count = self.original_table_row_count(table_id);
        let table_changes = self
            .changes
            .table_changes
            .entry(table_id)
            .or_insert_with(|| TableModifications::new_sparse(original_count + 1));

        let new_rid = table_changes.next_rid()?;
        let operation = Operation::Insert(new_rid, row);
        let table_operation = TableOperation::new(operation);
        table_changes.apply_operation(table_operation)?;

        // Create and register the ChangeRef for this inserted row
        // Resolve the token immediately since we know both the table ID and RID
        let change_ref = ChangeRef::new_table_row(table_id);
        let token = Token::from_parts(table_id, new_rid);
        change_ref.resolve_to_token(token);
        let change_ref_rc = change_ref.into_rc();
        table_changes.register_change_ref(new_rid, change_ref_rc.clone());

        Ok(change_ref_rc)
    }

    /// Writes the assembly to a file.
    ///
    /// This method generates a complete PE file with all modifications applied.
    /// Uses default generator configuration.
    ///
    /// # Arguments
    ///
    /// * `path` - The path where the assembly should be written
    ///
    /// # Errors
    ///
    /// Returns an error if the file cannot be written or if the assembly is invalid.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::{CilAssemblyView, CilAssembly};
    /// use std::path::Path;
    ///
    /// let view = CilAssemblyView::from_path(Path::new("input.dll"))?;
    /// let mut assembly = CilAssembly::new(view);
    /// assembly.to_file("output.dll")?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn to_file<P: AsRef<std::path::Path>>(&mut self, path: P) -> Result<()> {
        self.finalize_for_generation()?;
        PeGenerator::new(self).to_file(path)
    }

    /// Writes the assembly to a file with custom configuration.
    ///
    /// This method generates a complete PE file with all modifications applied,
    /// using the specified generator configuration for heap optimization and
    /// other settings.
    ///
    /// # Arguments
    ///
    /// * `path` - The path where the assembly should be written
    /// * `config` - Configuration options for the generator
    ///
    /// # Errors
    ///
    /// Returns an error if the file cannot be written or if the assembly is invalid.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::{CilAssemblyView, CilAssembly};
    /// use dotscope::prelude::GeneratorConfig;
    /// use std::path::Path;
    ///
    /// let view = CilAssemblyView::from_path(Path::new("input.dll"))?;
    /// let mut assembly = CilAssembly::new(view);
    /// assembly.to_file_with_config("output.dll", GeneratorConfig::default())?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn to_file_with_config<P: AsRef<std::path::Path>>(
        &mut self,
        path: P,
        config: GeneratorConfig,
    ) -> Result<()> {
        self.finalize_for_generation()?;
        PeGenerator::with_config(self, config).to_file(path)
    }

    /// Generates the assembly to memory as a byte vector.
    ///
    /// This method generates a complete PE file in memory, useful for:
    /// - In-memory assembly manipulation pipelines
    /// - Testing and validation without file I/O
    /// - Streaming assembly data to network or other outputs
    ///
    /// # Returns
    ///
    /// Returns `Ok(Vec<u8>)` containing the complete PE file bytes.
    ///
    /// # Errors
    ///
    /// Returns an error if generation fails or the assembly is invalid.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::{CilAssemblyView, CilAssembly};
    /// use std::path::Path;
    ///
    /// let view = CilAssemblyView::from_path(Path::new("input.dll"))?;
    /// let mut assembly = CilAssembly::new(view);
    /// let pe_bytes = assembly.to_memory()?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn to_memory(&mut self) -> Result<Vec<u8>> {
        self.finalize_for_generation()?;
        PeGenerator::new(self).to_memory()
    }

    /// Generates the assembly to memory with custom configuration.
    ///
    /// This method generates a complete PE file in memory using the specified
    /// generator configuration.
    ///
    /// # Arguments
    ///
    /// * `config` - Configuration options for the generator
    ///
    /// # Returns
    ///
    /// Returns `Ok(Vec<u8>)` containing the complete PE file bytes.
    ///
    /// # Errors
    ///
    /// Returns an error if generation fails or the assembly is invalid.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::{CilAssemblyView, CilAssembly};
    /// use dotscope::prelude::GeneratorConfig;
    /// use std::path::Path;
    ///
    /// let view = CilAssemblyView::from_path(Path::new("input.dll"))?;
    /// let mut assembly = CilAssembly::new(view);
    /// let pe_bytes = assembly.to_memory_with_config(GeneratorConfig::default())?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn to_memory_with_config(&mut self, config: GeneratorConfig) -> Result<Vec<u8>> {
        self.finalize_for_generation()?;
        PeGenerator::with_config(self, config).to_memory()
    }

    /// Converts this `CilAssembly` into a [`CilObject`](crate::CilObject) for analysis.
    ///
    /// This method writes all modifications to memory, then parses the result
    /// as a `CilObject`. Use this after making modifications to obtain a
    /// fully-parsed assembly ready for analysis.
    ///
    /// # Returns
    ///
    /// A [`CilObject`](crate::CilObject) containing the modified assembly.
    ///
    /// # Usage Examples
    ///
    /// ```rust,no_run
    /// use dotscope::CilObject;
    ///
    /// let assembly = CilObject::from_path("input.dll")?;
    /// let mut mutable = assembly.into_assembly();
    ///
    /// // Perform modifications
    /// mutable.string_add("NewString")?;
    ///
    /// // Convert back to CilObject for analysis
    /// let modified = mutable.into_cilobject()?;
    ///
    /// // Now we can analyze the modified assembly
    /// println!("Types: {}", modified.types().len());
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    ///
    /// # Errors
    ///
    /// Returns an error if writing modifications fails or if the result
    /// cannot be parsed as a valid .NET assembly.
    pub fn into_cilobject(mut self) -> Result<CilObject> {
        self.finalize_for_generation()?;
        let bytes = PeGenerator::new(&self).to_memory()?;
        CilObject::from_mem_with_validation(bytes, ValidationConfig::production())
    }

    /// Converts this `CilAssembly` into a [`CilObject`](crate::CilObject) with custom options.
    ///
    /// Like [`into_cilobject`](Self::into_cilobject) but allows specifying both
    /// the validation configuration and generator configuration for the resulting assembly.
    ///
    /// # Arguments
    ///
    /// * `validation_config` - Validation configuration for the output
    /// * `generator_config` - Generator configuration for PE file creation (controls optimizations
    ///   like heap deduplication, dead reference elimination, and section exclusion)
    ///
    /// # Returns
    ///
    /// A [`CilObject`](crate::CilObject) containing the modified assembly.
    ///
    /// # Errors
    ///
    /// Returns an error if writing modifications fails or if the result
    /// fails validation.
    pub fn into_cilobject_with(
        mut self,
        validation_config: ValidationConfig,
        generator_config: GeneratorConfig,
    ) -> Result<CilObject> {
        self.finalize_for_generation()?;
        let bytes = PeGenerator::with_config(&self, generator_config).to_memory()?;
        CilObject::from_mem_with_validation(bytes, validation_config)
    }

    /// Gets the original row count for a table
    pub fn original_table_row_count(&self, table_id: TableId) -> u32 {
        if let Some(tables) = self.view.tables() {
            tables.table_row_count(table_id)
        } else {
            0
        }
    }

    /// Gets the next available RID for a table.
    ///
    /// This returns the RID that will be assigned to the next row added to the table.
    /// It accounts for both the original table size and any modifications that have been made.
    ///
    /// # Arguments
    ///
    /// * `table_id` - The table to query
    ///
    /// # Returns
    ///
    /// The next RID that would be assigned (1-based).
    ///
    /// # Errors
    ///
    /// Returns an error if the row count exceeds u32::MAX.
    pub fn next_rid(&self, table_id: TableId) -> Result<u32> {
        if let Some(modifications) = self.changes.table_changes.get(&table_id) {
            modifications.next_rid()
        } else {
            // No modifications yet - next RID is original count + 1
            Ok(self.original_table_row_count(table_id) + 1)
        }
    }

    /// Gets a reference to the underlying view for read operations.
    pub fn view(&self) -> &CilAssemblyView {
        &self.view
    }

    /// Gets a reference to the underlying PE file.
    ///
    /// This is a convenience method equivalent to `self.view().file()`.
    pub fn file(&self) -> &File {
        self.view.file()
    }

    /// Gets a reference to the changes for write operations.
    pub fn changes(&self) -> &AssemblyChanges {
        &self.changes
    }

    /// Gets a mutable reference to the changes for write operations.
    pub fn changes_mut(&mut self) -> &mut AssemblyChanges {
        &mut self.changes
    }

    /// Adds a DLL to the native import table.
    ///
    /// Creates a new import descriptor for the specified DLL if it doesn't already exist.
    /// This method provides the foundation for native PE import functionality by managing
    /// DLL dependencies at the assembly level.
    ///
    /// # Arguments
    ///
    /// * `dll_name` - Name of the DLL (e.g., "kernel32.dll", "user32.dll")
    ///
    /// # Returns
    ///
    /// `Ok(())` if the DLL was added successfully, or if it already exists.
    ///
    /// # Errors
    ///
    /// Returns an error if the DLL name is empty or contains invalid characters.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use dotscope::{CilAssemblyView, CilAssembly};
    /// # use std::path::Path;
    /// # let view = CilAssemblyView::from_path(Path::new("test.dll"))?;
    /// let mut assembly = CilAssembly::new(view);
    ///
    /// assembly.add_native_import_dll("kernel32.dll")?;
    /// assembly.add_native_import_dll("user32.dll")?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn add_native_import_dll(&mut self, dll_name: &str) -> Result<()> {
        let imports = self.changes.native_imports_mut();
        imports.native_mut().add_dll(dll_name)
    }

    /// Adds a named function import from a specific DLL to the native import table.
    ///
    /// Adds a function import that uses name-based lookup. The DLL will be automatically
    /// added to the import table if it doesn't already exist. This method handles the
    /// complete import process including IAT allocation and Import Lookup Table setup.
    ///
    /// # Arguments
    ///
    /// * `dll_name` - Name of the DLL containing the function
    /// * `function_name` - Name of the function to import
    ///
    /// # Returns
    ///
    /// `Ok(())` if the function was added successfully.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The DLL name or function name is empty
    /// - The function is already imported from this DLL
    /// - There are issues with IAT allocation
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use dotscope::{CilAssemblyView, CilAssembly};
    /// # use std::path::Path;
    /// # let view = CilAssemblyView::from_path(Path::new("test.dll"))?;
    /// let mut assembly = CilAssembly::new(view);
    ///
    /// // Add kernel32 functions
    /// assembly.add_native_import_function("kernel32.dll", "GetCurrentProcessId")?;
    /// assembly.add_native_import_function("kernel32.dll", "ExitProcess")?;
    ///
    /// // Add user32 functions  
    /// assembly.add_native_import_function("user32.dll", "MessageBoxW")?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn add_native_import_function(
        &mut self,
        dll_name: &str,
        function_name: &str,
    ) -> Result<()> {
        let imports = self.changes.native_imports_mut();
        imports.add_native_function(dll_name, function_name)
    }

    /// Adds an ordinal-based function import to the native import table.
    ///
    /// Adds a function import that uses ordinal-based lookup instead of name-based.
    /// This can be more efficient and result in smaller import tables, but is less
    /// portable across DLL versions. The DLL will be automatically added if it
    /// doesn't exist.
    ///
    /// # Arguments
    ///
    /// * `dll_name` - Name of the DLL containing the function
    /// * `ordinal` - Ordinal number of the function in the DLL's export table
    ///
    /// # Returns
    ///
    /// `Ok(())` if the function was added successfully.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The DLL name is empty
    /// - The ordinal is 0 (invalid)
    /// - A function with the same ordinal is already imported from this DLL
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use dotscope::{CilAssemblyView, CilAssembly};
    /// # use std::path::Path;
    /// # let view = CilAssemblyView::from_path(Path::new("test.dll"))?;
    /// let mut assembly = CilAssembly::new(view);
    ///
    /// // Import MessageBoxW by ordinal (more efficient)
    /// assembly.add_native_import_function_by_ordinal("user32.dll", 120)?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn add_native_import_function_by_ordinal(
        &mut self,
        dll_name: &str,
        ordinal: u16,
    ) -> Result<()> {
        let imports = self.changes.native_imports_mut();
        imports.add_native_function_by_ordinal(dll_name, ordinal)
    }

    /// Adds a named function export to the native export table.
    ///
    /// Creates a function export that can be called by other modules. The function
    /// will be accessible by both name and ordinal. This method handles the complete
    /// export process including Export Address Table and Export Name Table setup.
    ///
    /// # Arguments
    ///
    /// * `function_name` - Name of the function to export
    /// * `ordinal` - Ordinal number for the export (must be unique)
    /// * `address` - Function address (RVA) in the image
    ///
    /// # Returns
    ///
    /// `Ok(())` if the function was exported successfully.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The function name is empty
    /// - The ordinal is 0 (invalid) or already in use
    /// - The function name is already exported
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use dotscope::{CilAssemblyView, CilAssembly};
    /// # use std::path::Path;
    /// # let view = CilAssemblyView::from_path(Path::new("test.dll"))?;
    /// let mut assembly = CilAssembly::new(view);
    ///
    /// // Export library functions
    /// assembly.add_native_export_function("MyLibraryInit", 1, 0x1000)?;
    /// assembly.add_native_export_function("ProcessData", 2, 0x2000)?;
    /// assembly.add_native_export_function("MyLibraryCleanup", 3, 0x3000)?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn add_native_export_function(
        &mut self,
        function_name: &str,
        ordinal: u16,
        address: u32,
    ) -> Result<()> {
        let exports = self.changes.native_exports_mut();
        exports.add_native_function(function_name, ordinal, address)
    }

    /// Adds an ordinal-only function export to the native export table.
    ///
    /// Creates a function export that is accessible by ordinal number only,
    /// without a symbolic name. This can reduce the size of the export table
    /// but makes the exports less discoverable.
    ///
    /// # Arguments
    ///
    /// * `ordinal` - Ordinal number for the export (must be unique)
    /// * `address` - Function address (RVA) in the image
    ///
    /// # Returns
    ///
    /// `Ok(())` if the function was exported successfully.
    ///
    /// # Errors
    ///
    /// Returns an error if the ordinal is 0 (invalid) or already in use.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use dotscope::{CilAssemblyView, CilAssembly};
    /// # use std::path::Path;
    /// # let view = CilAssemblyView::from_path(Path::new("test.dll"))?;
    /// let mut assembly = CilAssembly::new(view);
    ///
    /// // Export internal functions by ordinal only
    /// assembly.add_native_export_function_by_ordinal(100, 0x5000)?;
    /// assembly.add_native_export_function_by_ordinal(101, 0x6000)?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn add_native_export_function_by_ordinal(
        &mut self,
        ordinal: u16,
        address: u32,
    ) -> Result<()> {
        let exports = self.changes.native_exports_mut();
        exports.add_native_function_by_ordinal(ordinal, address)
    }

    /// Adds an export forwarder to the native export table.
    ///
    /// Creates a function export that forwards calls to a function in another DLL.
    /// The Windows loader resolves forwarders at runtime by loading the target
    /// DLL and finding the specified function. This is useful for implementing
    /// compatibility shims or redirecting calls.
    ///
    /// # Arguments
    ///
    /// * `function_name` - Name of the exported function (can be empty for ordinal-only)
    /// * `ordinal` - Ordinal number for the export (must be unique)
    /// * `target` - Target specification: "DllName.FunctionName" or "DllName.#Ordinal"
    ///
    /// # Returns
    ///
    /// `Ok(())` if the forwarder was added successfully.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The ordinal is 0 (invalid) or already in use
    /// - The function name is already exported (if name is provided)
    /// - The target specification is empty or malformed
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use dotscope::{CilAssemblyView, CilAssembly};
    /// # use std::path::Path;
    /// # let view = CilAssemblyView::from_path(Path::new("test.dll"))?;
    /// let mut assembly = CilAssembly::new(view);
    ///
    /// // Forward to functions in other DLLs
    /// assembly.add_native_export_forwarder("GetProcessId", 10, "kernel32.dll.GetCurrentProcessId")?;
    /// assembly.add_native_export_forwarder("MessageBox", 11, "user32.dll.MessageBoxW")?;
    /// assembly.add_native_export_forwarder("OrdinalForward", 12, "mydll.dll.#50")?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn add_native_export_forwarder(
        &mut self,
        function_name: &str,
        ordinal: u16,
        target: &str,
    ) -> Result<()> {
        let exports = self.changes.native_exports_mut();
        exports.add_native_forwarder(function_name, ordinal, target)
    }

    /// Gets read-only access to the unified import container.
    ///
    /// Returns the unified import container that provides access to both CIL and native
    /// PE imports. Returns `None` if no native import operations have been performed.
    ///
    /// # Returns
    ///
    /// Optional reference to the unified import container.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use dotscope::{CilAssemblyView, CilAssembly};
    /// # use std::path::Path;
    /// # let view = CilAssemblyView::from_path(Path::new("test.dll"))?;
    /// let assembly = CilAssembly::new(view);
    ///
    /// let imports = assembly.native_imports();
    /// let dll_names = imports.get_all_dll_names();
    /// println!("DLL dependencies: {:?}", dll_names);
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn native_imports(&self) -> &UnifiedImportContainer {
        self.changes.native_imports()
    }

    /// Gets read-only access to the unified export container.
    ///
    /// Returns the unified export container that provides access to both CIL and native
    /// PE exports. Returns `None` if no native export operations have been performed.
    ///
    /// # Returns
    ///
    /// Optional reference to the unified export container.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use dotscope::{CilAssemblyView, CilAssembly};
    /// # use std::path::Path;
    /// # let view = CilAssemblyView::from_path(Path::new("test.dll"))?;
    /// let assembly = CilAssembly::new(view);
    ///
    /// let exports = assembly.native_exports();
    /// let function_names = exports.get_native_function_names();
    /// println!("Exported functions: {:?}", function_names);
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn native_exports(&self) -> &UnifiedExportContainer {
        self.changes.native_exports()
    }

    /// Stores a method body and allocates a placeholder RVA for it.
    ///
    /// This method stores the method body with a placeholder RVA that will be resolved
    /// to the actual RVA during PE writing when the code section layout is determined.
    /// Used by method builders to store compiled method bodies and get placeholder RVAs
    /// for use in method definition metadata.
    ///
    /// # Arguments
    ///
    /// * `body_bytes` - The complete method body bytes including header and exception handlers
    ///
    /// # Returns
    ///
    /// A placeholder RVA that will be resolved to the actual RVA during binary writing.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use dotscope::{CilAssemblyView, CilAssembly};
    /// # use std::path::Path;
    /// # let view = CilAssemblyView::from_path(Path::new("test.dll"))?;
    /// let mut assembly = CilAssembly::new(view);
    ///
    /// let method_body = vec![0x02, 0x17, 0x2A]; // Tiny header + ldc.i4.1 + ret
    /// let placeholder_rva = assembly.store_method_body(method_body);
    /// // placeholder_rva will be resolved to actual RVA during binary writing
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn store_method_body(&mut self, body_bytes: Vec<u8>) -> u32 {
        self.changes.store_method_body(body_bytes)
    }

    /// Stores field initialization data and returns a placeholder RVA.
    ///
    /// The returned placeholder RVA is a temporary identifier that will later
    /// be resolved to the actual RVA during PE writing when the section layout
    /// is determined. This is used for FieldRVA entries that point to static
    /// field initialization data.
    ///
    /// # Arguments
    ///
    /// * `data` - The field initialization data bytes
    ///
    /// # Returns
    ///
    /// A placeholder RVA that will be resolved to the actual RVA during binary writing.
    pub fn store_field_data(&mut self, data: Vec<u8>) -> u32 {
        self.changes.store_field_data(data)
    }

    /// Gets or adds a string to the string heap, reusing existing strings when possible.
    ///
    /// This method first checks if the string already exists in the heap changes
    /// and reuses it if found. This helps avoid duplicate namespace strings and
    /// other common strings.
    ///
    /// # Arguments
    ///
    /// * `value` - The string to get or add to the heap
    ///
    /// # Returns
    ///
    /// A ChangeRef that will resolve to the string offset after write.
    ///
    /// # Errors
    ///
    /// Returns an error if the string cannot be added to the heap.
    pub fn string_get_or_add(&mut self, value: &str) -> Result<ChangeRefRc> {
        if let Some(existing_ref) = self.string_find(value) {
            return Ok(existing_ref);
        }
        self.string_add(value)
    }

    /// Helper method to find an existing string in the current heap changes.
    ///
    /// This searches through the strings added in the current session
    /// to avoid duplicates within the same session.
    fn string_find(&self, value: &str) -> Option<ChangeRefRc> {
        let heap_changes = &self.changes.string_heap_changes;
        for (existing_string, change_ref) in heap_changes.appended_iter() {
            if existing_string == value {
                return Some(change_ref.clone());
            }
        }
        None
    }

    /// Finds an AssemblyRef by its name.
    ///
    /// This method searches the AssemblyRef table to find an assembly reference
    /// with the specified name. This is useful for locating specific dependencies
    /// or core libraries.
    ///
    /// # Arguments
    ///
    /// * `name` - The exact name of the assembly to find (case-sensitive)
    ///
    /// # Returns
    ///
    /// A [`CodedIndex`] pointing to the matching AssemblyRef, or None if not found.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// # use dotscope::{CilAssemblyView, CilAssembly};
    /// # use std::path::Path;
    /// # let view = CilAssemblyView::from_path(Path::new("test.dll"))?;
    /// let assembly = CilAssembly::new(view);
    ///
    /// // Find a specific library
    /// if let Some(newtonsoft_ref) = assembly.find_assembly_ref_by_name("Newtonsoft.Json") {
    ///     println!("Found Newtonsoft.Json reference");
    /// }
    ///
    /// // Find core library
    /// if let Some(mscorlib_ref) = assembly.find_assembly_ref_by_name("mscorlib") {
    ///     println!("Found mscorlib reference");
    /// }
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn find_assembly_ref_by_name(&self, name: &str) -> Option<CodedIndex> {
        if let (Some(assembly_ref_table), Some(strings)) = (
            self.view.tables()?.table::<AssemblyRefRaw>(),
            self.view.strings(),
        ) {
            for (index, assemblyref) in assembly_ref_table.iter().enumerate() {
                if let Ok(assembly_name) = strings.get(assemblyref.name as usize) {
                    if assembly_name == name {
                        // Convert 0-based index to 1-based RID
                        return Some(CodedIndex::new(
                            TableId::AssemblyRef,
                            u32::try_from(index + 1).unwrap_or(u32::MAX),
                            CodedIndexType::Implementation,
                        ));
                    }
                }
            }
        }
        None
    }

    /// Finds the AssemblyRef for the core library.
    ///
    /// This method searches the AssemblyRef table to find the core library
    /// reference, which can be any of:
    /// - "mscorlib" (classic .NET Framework)
    /// - "System.Runtime" (.NET Core/.NET 5+)
    /// - "System.Private.CoreLib" (some .NET implementations)
    ///
    /// # Returns
    ///
    /// A [`CodedIndex`] pointing to the core library AssemblyRef, or None if not found.
    pub fn find_core_library_ref(&self) -> Option<CodedIndex> {
        self.find_assembly_ref_by_name("mscorlib")
            .or_else(|| self.find_assembly_ref_by_name("System.Runtime"))
            .or_else(|| self.find_assembly_ref_by_name("System.Private.CoreLib"))
    }

    /// Adds a method signature to the blob heap and returns its index.
    ///
    /// This encodes the method signature using the dedicated method signature encoder.
    /// The encoder handles all ECMA-335 method signature format requirements including
    /// calling conventions, parameter counts, and type encoding.
    ///
    /// # Arguments
    ///
    /// * `signature` - The method signature to encode and store
    ///
    /// # Returns
    ///
    /// A ChangeRef that will resolve to the blob heap offset after write.
    ///
    /// # Errors
    ///
    /// Returns an error if the signature cannot be encoded or added to the blob heap.
    pub fn add_method_signature(&mut self, signature: &SignatureMethod) -> Result<ChangeRefRc> {
        let encoded_data = encode_method_signature(signature)?;
        self.blob_add(&encoded_data)
    }

    /// Adds a field signature to the blob heap and returns its index.
    ///
    /// This encodes the field signature using the dedicated field signature encoder.
    /// The encoder handles ECMA-335 field signature format requirements including
    /// custom modifiers and field type encoding.
    ///
    /// # Arguments
    ///
    /// * `signature` - The field signature to encode and store
    ///
    /// # Returns
    ///
    /// A ChangeRef that will resolve to the blob heap offset after write.
    ///
    /// # Errors
    ///
    /// Returns an error if the signature cannot be encoded or added to the blob heap.
    pub fn add_field_signature(&mut self, signature: &SignatureField) -> Result<ChangeRefRc> {
        let encoded_data = encode_field_signature(signature)?;
        self.blob_add(&encoded_data)
    }

    /// Adds a property signature to the blob heap and returns its index.
    ///
    /// This encodes the property signature using the dedicated property signature encoder.
    /// The encoder handles ECMA-335 property signature format requirements including
    /// instance/static properties and indexer parameters.
    ///
    /// # Arguments
    ///
    /// * `signature` - The property signature to encode and store
    ///
    /// # Returns
    ///
    /// A ChangeRef that will resolve to the blob heap offset after write.
    ///
    /// # Errors
    ///
    /// Returns an error if the signature cannot be encoded or added to the blob heap.
    pub fn add_property_signature(&mut self, signature: &SignatureProperty) -> Result<ChangeRefRc> {
        let encoded_data = encode_property_signature(signature)?;
        self.blob_add(&encoded_data)
    }

    /// Adds a local variable signature to the blob heap and returns its index.
    ///
    /// This encodes the local variable signature using the dedicated local variable encoder.
    /// The encoder handles ECMA-335 local variable signature format requirements including
    /// pinned and byref modifiers.
    ///
    /// # Arguments
    ///
    /// * `signature` - The local variable signature to encode and store
    ///
    /// # Returns
    ///
    /// A ChangeRef that will resolve to the blob heap offset after write.
    ///
    /// # Errors
    ///
    /// Returns an error if the signature cannot be encoded or added to the blob heap.
    pub fn add_local_var_signature(
        &mut self,
        signature: &SignatureLocalVariables,
    ) -> Result<ChangeRefRc> {
        let encoded_data = encode_local_var_signature(signature)?;
        self.blob_add(&encoded_data)
    }

    /// Adds a type specification signature to the blob heap and returns its index.
    ///
    /// This encodes the type specification signature using the dedicated type specification
    /// encoder. Type specification signatures encode complex type signatures for generic
    /// instantiations, arrays, pointers, and other complex types.
    ///
    /// # Arguments
    ///
    /// * `signature` - The type specification signature to encode and store
    ///
    /// # Returns
    ///
    /// A ChangeRef that will resolve to the blob heap offset after write.
    ///
    /// # Errors
    ///
    /// Returns an error if the signature cannot be encoded or added to the blob heap.
    pub fn add_typespec_signature(&mut self, signature: &SignatureTypeSpec) -> Result<ChangeRefRc> {
        let encoded_data = encode_typespec_signature(signature)?;
        self.blob_add(&encoded_data)
    }
}

/// Conversion from `CilAssemblyView` to `CilAssembly`.
///
/// This provides the `view.to_owned()` syntax mentioned in the documentation.
impl From<CilAssemblyView> for CilAssembly {
    fn from(view: CilAssemblyView) -> Self {
        Self::new(view)
    }
}

impl std::fmt::Debug for CilAssembly {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("CilAssembly")
            .field("original_view", &"<CilAssemblyView>")
            .field("has_changes", &self.changes.has_changes())
            .finish_non_exhaustive()
    }
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    use super::*;
    use crate::test::factories::table::cilassembly::create_test_typedef_row;
    use crate::Error;

    #[test]
    fn test_convert_from_view() {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/WindowsBase.dll");
        if let Ok(_assembly) = CilAssembly::from_path(&path) {
            // Basic smoke test - conversion should succeed
        }
    }

    #[test]
    fn test_add_string() {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/WindowsBase.dll");
        if let Ok(mut assembly) = CilAssembly::from_path(&path) {
            let ref1 = assembly.string_add("Hello").unwrap();
            let ref2 = assembly.string_add("World").unwrap();

            assert_ne!(ref1.placeholder(), ref2.placeholder());
            assert!(ref2.placeholder() > ref1.placeholder());
        }
    }

    #[test]
    fn test_add_blob() {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/WindowsBase.dll");
        if let Ok(mut assembly) = CilAssembly::from_path(&path) {
            let ref1 = assembly.blob_add(&[1, 2, 3]).unwrap();
            let ref2 = assembly.blob_add(&[4, 5, 6]).unwrap();

            assert_ne!(ref1.placeholder(), ref2.placeholder());
            assert!(ref2.placeholder() > ref1.placeholder());
        }
    }

    #[test]
    fn test_add_guid() {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/WindowsBase.dll");
        if let Ok(mut assembly) = CilAssembly::from_path(&path) {
            let guid1 = [
                0x12, 0x34, 0x56, 0x78, 0x9A, 0xBC, 0xDE, 0xF0, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66,
                0x77, 0x88,
            ];
            let guid2 = [
                0xAA, 0xBB, 0xCC, 0xDD, 0xEE, 0xFF, 0x00, 0x11, 0x22, 0x33, 0x44, 0x55, 0x66, 0x77,
                0x88, 0x99,
            ];

            let ref1 = assembly.guid_add(&guid1).unwrap();
            let ref2 = assembly.guid_add(&guid2).unwrap();

            assert_ne!(ref1.placeholder(), ref2.placeholder());
            assert!(ref2.placeholder() > ref1.placeholder());
        }
    }

    #[test]
    fn test_add_userstring() {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/WindowsBase.dll");
        if let Ok(mut assembly) = CilAssembly::from_path(&path) {
            let ref1 = assembly.userstring_add("Hello").unwrap();
            let ref2 = assembly.userstring_add("World").unwrap();

            assert_ne!(ref1.placeholder(), ref2.placeholder());
            assert!(ref2.placeholder() > ref1.placeholder());
        }
    }

    #[test]
    fn test_table_row_assignment_uses_correct_rid() {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/WindowsBase.dll");
        if let Ok(mut assembly) = CilAssembly::from_path(&path) {
            // Create a minimal TypeDef row for testing
            if let Ok(typedef_row) = create_test_typedef_row() {
                // Add table row should return a ChangeRefRc
                if let Ok(change_ref) = assembly.table_row_add(TableId::TypeDef, typedef_row) {
                    // Verify the ChangeRef is for the TypeDef table
                    assert!(
                        change_ref.kind().is_table(),
                        "ChangeRef should be a table row reference"
                    );
                    assert_eq!(
                        change_ref.kind().table_id(),
                        Some(TableId::TypeDef),
                        "ChangeRef should be for TypeDef table"
                    );

                    // Add another row should get a different ChangeRef
                    if let Ok(typedef_row2) = create_test_typedef_row() {
                        if let Ok(change_ref2) =
                            assembly.table_row_add(TableId::TypeDef, typedef_row2)
                        {
                            // The two ChangeRefs should have different IDs
                            assert_ne!(
                                change_ref.id(),
                                change_ref2.id(),
                                "Different rows should have different ChangeRef IDs"
                            );
                        }
                    }
                }
            }
        }
    }

    #[test]
    fn test_heap_changes_initialized() {
        let path = PathBuf::from(env!("CARGO_MANIFEST_DIR")).join("tests/samples/WindowsBase.dll");
        if let Ok(assembly) = CilAssembly::from_path(&path) {
            // Verify heap changes are properly initialized
            // The additions count should be 0 initially
            assert_eq!(assembly.changes.string_heap_changes.additions_count(), 0);
            assert_eq!(assembly.changes.blob_heap_changes.additions_count(), 0);
            assert_eq!(assembly.changes.guid_heap_changes.additions_count(), 0);
            assert_eq!(
                assembly.changes.userstring_heap_changes.additions_count(),
                0
            );
        }
    }

    /// Mono runtime compatibility tests for assembly modification and execution
    mod mono_tests {
        use super::*;
        use crate::metadata::signatures::{
            encode_method_signature, SignatureMethod, SignatureParameter, TypeSignature,
        };
        use crate::metadata::tables::{
            CodedIndex, CodedIndexType, MemberRefBuilder, TableId, TypeRefBuilder,
        };
        use crate::metadata::token::Token;
        use crate::test::mono::*;

        #[test]
        fn test_mono_runtime_compatibility() -> Result<()> {
            // Create test runner using the new utilities
            let runner = TestRunner::new()?;

            // Define the assembly modification that adds a simple method
            let modify_assembly = |assembly: &mut CilAssembly| -> Result<()> {
                let _method_token = MethodBuilder::new("DotScopeAddedMethod")
                    .public()
                    .static_method()
                    .parameter("a", TypeSignature::I4)
                    .parameter("b", TypeSignature::I4)
                    .returns(TypeSignature::I4)
                    .implementation(|body| {
                        body.implementation(|asm| {
                            asm.ldarg_0()?.ldarg_1()?.add()?.ret()?;
                            Ok(())
                        })
                    })
                    .build(assembly)?;
                Ok(())
            };

            // Run the complete test workflow
            let results = run_complete_test(
                &runner,
                compilation::templates::HELLO_WORLD,
                modify_assembly,
            )?;

            // Assert all architectures passed all tests
            for result in &results {
                assert!(
                    result.compilation_success,
                    "Compilation failed for {}: {:?}",
                    result.architecture.name, result.errors
                );
                assert!(
                    result.modification_success,
                    "Assembly modification failed for {}: {:?}",
                    result.architecture.name, result.errors
                );
                assert!(
                    result.execution_success,
                    "Execution failed for {}: {:?}",
                    result.architecture.name, result.errors
                );
                assert!(
                    result.disassembly_success,
                    "Disassembly verification failed for {}: {:?}",
                    result.architecture.name, result.errors
                );
                assert!(
                    result.reflection_success,
                    "Reflection test failed for {}: {:?}",
                    result.architecture.name, result.errors
                );

                // Assert overall success
                assert!(
                    result.is_fully_successful(),
                    "Overall test failed for {} architecture with errors: {:?}",
                    result.architecture.name,
                    result.errors
                );
            }

            // Assert we tested all available architectures
            let expected_arch_count = runner.architectures().len();
            assert_eq!(
                results.len(),
                expected_arch_count,
                "Expected to test {} architectures",
                expected_arch_count
            );

            Ok(())
        }

        #[test]
        fn test_mono_enhanced_modifications() -> Result<()> {
            // Create test runner using the new utilities
            let runner = TestRunner::new()?;

            // Test string modification by adding a simple method
            let modify_assembly = |assembly: &mut CilAssembly| -> Result<()> {
                // Create method that prints the modified message using Console.WriteLine
                let new_string = "MODIFIED: Hello from enhanced dotscope test!";
                let new_string_ref = assembly.userstring_add(new_string)?;
                // Use placeholder value - bit 31 marks it as placeholder, resolved during write
                let new_string_token = Token::new(0x70000000 | new_string_ref.placeholder());

                // Find the assembly reference containing System.Console
                // .NET 8+ uses separate System.Console assembly, while older frameworks use mscorlib
                let console_assembly_ref = assembly
                    .find_assembly_ref_by_name("System.Console")
                    .or_else(|| assembly.find_core_library_ref())
                    .ok_or_else(|| {
                        Error::TypeError(
                            "Could not find System.Console or core library reference".to_string(),
                        )
                    })?;
                let console_assembly_token =
                    Token::new((TableId::AssemblyRef as u32) << 24 | console_assembly_ref.row);
                let console_writeline_ref =
                    create_console_writeline_ref(assembly, console_assembly_token)?;

                // Add a method that prints the modified string
                let new_string_token_copy = new_string_token;
                let console_writeline_ref_copy = console_writeline_ref;
                let _method_token = MethodBuilder::new("PrintModifiedMessage")
                    .public()
                    .static_method()
                    .returns(TypeSignature::Void)
                    .implementation(move |body| {
                        body.implementation(move |asm| {
                            asm.ldstr(new_string_token_copy)?
                                .call(console_writeline_ref_copy)?
                                .ret()?;
                            Ok(())
                        })
                    })
                    .build(assembly)?;

                Ok(())
            };

            // Run the complete test workflow
            let results = run_complete_test(
                &runner,
                compilation::templates::HELLO_WORLD,
                modify_assembly,
            )?;

            // Assert all tests passed
            for result in &results {
                assert!(
                    result.is_fully_successful(),
                    "String test execution failed for {}: {:?}",
                    result.architecture.name,
                    result.errors
                );
            }

            Ok(())
        }

        fn create_writeline_signature() -> Result<Vec<u8>> {
            let signature = SignatureMethod {
                has_this: false, // Static method
                explicit_this: false,
                default: true, // Default managed calling convention
                vararg: false,
                cdecl: false,
                stdcall: false,
                thiscall: false,
                fastcall: false,
                param_count_generic: 0,
                param_count: 1, // One string parameter
                return_type: SignatureParameter {
                    modifiers: Vec::new(),
                    by_ref: false,
                    base: TypeSignature::Void, // void return type
                },
                params: vec![SignatureParameter {
                    modifiers: Vec::new(),
                    by_ref: false,
                    base: TypeSignature::String, // string parameter
                }],
                varargs: Vec::new(),
            };

            encode_method_signature(&signature)
        }

        fn create_console_writeline_ref(
            assembly: &mut CilAssembly,
            mscorlib_ref: Token,
        ) -> Result<Token> {
            // Create TypeRef for System.Console
            let console_typeref_ref = TypeRefBuilder::new()
                .name("Console")
                .namespace("System")
                .resolution_scope(CodedIndex::new(
                    TableId::AssemblyRef,
                    mscorlib_ref.row(),
                    CodedIndexType::ResolutionScope,
                ))
                .build(assembly)?;
            let console_typeref_token = console_typeref_ref.placeholder_token().unwrap();

            // Create method signature for Console.WriteLine(string) using the working implementation
            let writeline_signature = create_writeline_signature()?;

            // Create MemberRef for Console.WriteLine method
            let memberref_ref = MemberRefBuilder::new()
                .name("WriteLine")
                .class(CodedIndex::new(
                    TableId::TypeRef,
                    console_typeref_token.row(),
                    CodedIndexType::MemberRefParent,
                ))
                .signature(&writeline_signature)
                .build(assembly)?;

            Ok(memberref_ref.placeholder_token().unwrap())
        }

        #[test]
        fn test_mono_mathematical_operations() -> Result<()> {
            // Test advanced mathematical operations and complex arithmetic
            let runner = TestRunner::new()?;

            let modify_assembly = |assembly: &mut CilAssembly| -> Result<()> {
                // Create method that performs multiple arithmetic operations
                // ComplexMath: (x * y) + (x - y) * 2
                let _complex_math_method = MethodBuilder::new("ComplexMath")
                    .public()
                    .static_method()
                    .parameter("x", TypeSignature::I4)
                    .parameter("y", TypeSignature::I4)
                    .returns(TypeSignature::I4)
                    .implementation(|body| {
                        body.implementation(|asm| {
                            asm.ldarg_0()?
                                .ldarg_1()?
                                .mul()?
                                .ldarg_0()?
                                .ldarg_1()?
                                .sub()?
                                .ldc_i4_2()?
                                .mul()?
                                .add()?
                                .ret()?;
                            Ok(())
                        })
                    })
                    .build(assembly)?;

                // DivideAndRemainder: (dividend / divisor) + (dividend % divisor)
                let _division_method = MethodBuilder::new("DivideAndRemainder")
                    .public()
                    .static_method()
                    .parameter("dividend", TypeSignature::I4)
                    .parameter("divisor", TypeSignature::I4)
                    .returns(TypeSignature::I4)
                    .implementation(|body| {
                        body.implementation(|asm| {
                            asm.ldarg_0()?
                                .ldarg_1()?
                                .div()?
                                .ldarg_0()?
                                .ldarg_1()?
                                .rem()?
                                .add()?
                                .ret()?;
                            Ok(())
                        })
                    })
                    .build(assembly)?;

                Ok(())
            };

            let results = run_complete_test_with_reflection(
                &runner,
                compilation::templates::HELLO_WORLD,
                modify_assembly,
                |_assembly_path| {
                    vec![
                        // Test ComplexMath: (x * y) + (x - y) * 2
                        // With x=5, y=3: (5*3) + (5-3)*2 = 15 + 4 = 19
                        MethodTest::new("ComplexMath")
                            .arg_int(5)
                            .arg_int(3)
                            .expect_int(19)
                            .describe("ComplexMath(5, 3) = 19"),
                        // With x=10, y=4: (10*4) + (10-4)*2 = 40 + 12 = 52
                        MethodTest::new("ComplexMath")
                            .arg_int(10)
                            .arg_int(4)
                            .expect_int(52)
                            .describe("ComplexMath(10, 4) = 52"),
                        // Test DivideAndRemainder: (dividend / divisor) + (dividend % divisor)
                        // With dividend=17, divisor=5: (17/5) + (17%5) = 3 + 2 = 5
                        MethodTest::new("DivideAndRemainder")
                            .arg_int(17)
                            .arg_int(5)
                            .expect_int(5)
                            .describe("DivideAndRemainder(17, 5) = 5"),
                        // With dividend=20, divisor=4: (20/4) + (20%4) = 5 + 0 = 5
                        MethodTest::new("DivideAndRemainder")
                            .arg_int(20)
                            .arg_int(4)
                            .expect_int(5)
                            .describe("DivideAndRemainder(20, 4) = 5"),
                    ]
                },
            )?;

            // Assert all tests passed
            for result in &results {
                assert!(
                    result.is_fully_successful(),
                    "Mathematical operations test failed for {} architecture: {:?}",
                    result.architecture.name,
                    result.errors
                );
            }

            Ok(())
        }

        #[test]
        fn test_mono_local_variables_and_stack_operations() -> Result<()> {
            // Test local variable manipulation and stack operations
            let runner = TestRunner::new()?;

            let modify_assembly = |assembly: &mut CilAssembly| -> Result<()> {
                // TestLocalVariables: temp1=input*2, temp2=temp1+5, return temp2-temp1 (always 5)
                let _local_vars_method = MethodBuilder::new("TestLocalVariables")
                    .public()
                    .static_method()
                    .parameter("input", TypeSignature::I4)
                    .returns(TypeSignature::I4)
                    .implementation(|body| {
                        body.local("temp1", TypeSignature::I4)
                            .local("temp2", TypeSignature::I4)
                            .implementation(|asm| {
                                asm.ldarg_0()?
                                    .ldc_i4_2()?
                                    .mul()?
                                    .stloc_0()?
                                    .ldloc_0()?
                                    .ldc_i4_5()?
                                    .add()?
                                    .stloc_1()?
                                    .ldloc_1()?
                                    .ldloc_0()?
                                    .sub()?
                                    .ret()?;
                                Ok(())
                            })
                    })
                    .build(assembly)?;

                // StackOperations: 2a + b (uses dup to duplicate 'a' on stack)
                let _stack_ops_method = MethodBuilder::new("StackOperations")
                    .public()
                    .static_method()
                    .parameter("a", TypeSignature::I4)
                    .parameter("b", TypeSignature::I4)
                    .returns(TypeSignature::I4)
                    .implementation(|body| {
                        body.implementation(|asm| {
                            asm.ldarg_0()?.dup()?.ldarg_1()?.add()?.add()?.ret()?;
                            Ok(())
                        })
                    })
                    .build(assembly)?;

                Ok(())
            };

            let results = run_complete_test_with_reflection(
                &runner,
                compilation::templates::HELLO_WORLD,
                modify_assembly,
                |_assembly_path| {
                    vec![
                        // TestLocalVariables: temp1=input*2, temp2=temp1+5, return temp2-temp1
                        // With input=10: temp1=20, temp2=25, return 25-20=5
                        MethodTest::new("TestLocalVariables")
                            .arg_int(10)
                            .expect_int(5)
                            .describe("TestLocalVariables(10) = 5"),
                        // With input=7: temp1=14, temp2=19, return 19-14=5
                        MethodTest::new("TestLocalVariables")
                            .arg_int(7)
                            .expect_int(5)
                            .describe("TestLocalVariables(7) = 5"),
                        // StackOperations: 2a + b
                        // With a=3, b=4: 2*3 + 4 = 10
                        MethodTest::new("StackOperations")
                            .arg_int(3)
                            .arg_int(4)
                            .expect_int(10)
                            .describe("StackOperations(3, 4) = 10"),
                        // With a=5, b=7: 2*5 + 7 = 17
                        MethodTest::new("StackOperations")
                            .arg_int(5)
                            .arg_int(7)
                            .expect_int(17)
                            .describe("StackOperations(5, 7) = 17"),
                    ]
                },
            )?;

            // Assert all tests passed
            for result in &results {
                assert!(
                    result.is_fully_successful(),
                    "Local variables test failed for {} architecture: {:?}",
                    result.architecture.name,
                    result.errors
                );
            }

            Ok(())
        }

        #[test]
        fn test_mono_multiple_method_cross_references() -> Result<()> {
            // Test multiple methods that call each other
            let runner = TestRunner::new()?;

            let modify_assembly = |assembly: &mut CilAssembly| -> Result<()> {
                // DoubleNumber: value * 2
                let double_method = MethodBuilder::new("DoubleNumber")
                    .public()
                    .static_method()
                    .parameter("value", TypeSignature::I4)
                    .returns(TypeSignature::I4)
                    .implementation(|body| {
                        body.implementation(|asm| {
                            asm.ldarg_0()?.ldc_i4_2()?.mul()?.ret()?;
                            Ok(())
                        })
                    })
                    .build(assembly)?;

                // AddTen: value + 10
                let add_ten_method = MethodBuilder::new("AddTen")
                    .public()
                    .static_method()
                    .parameter("value", TypeSignature::I4)
                    .returns(TypeSignature::I4)
                    .implementation(|body| {
                        body.implementation(|asm| {
                            asm.ldarg_0()?.ldc_i4_s(10)?.add()?.ret()?;
                            Ok(())
                        })
                    })
                    .build(assembly)?;

                // ProcessNumber: calls DoubleNumber then AddTen => (input * 2) + 10
                let double_token = double_method.placeholder_token().unwrap();
                let add_ten_token = add_ten_method.placeholder_token().unwrap();
                let _main_method = MethodBuilder::new("ProcessNumber")
                    .public()
                    .static_method()
                    .parameter("input", TypeSignature::I4)
                    .returns(TypeSignature::I4)
                    .implementation(move |body| {
                        body.implementation(move |asm| {
                            asm.ldarg_0()?
                                .call(double_token)?
                                .call(add_ten_token)?
                                .ret()?;
                            Ok(())
                        })
                    })
                    .build(assembly)?;

                // Factorial: iterative implementation with loop
                let _factorial_method = MethodBuilder::new("Factorial")
                    .public()
                    .static_method()
                    .parameter("n", TypeSignature::I4)
                    .returns(TypeSignature::I4)
                    .implementation(|body| {
                        body.local("result", TypeSignature::I4)
                            .local("counter", TypeSignature::I4)
                            .implementation(|asm| {
                                asm.ldc_i4_1()?
                                    .stloc_0()?
                                    .ldc_i4_1()?
                                    .stloc_1()?
                                    .label("loop_start")?
                                    .ldloc_1()?
                                    .ldarg_0()?
                                    .bgt_s("loop_end")?
                                    .ldloc_0()?
                                    .ldloc_1()?
                                    .mul()?
                                    .stloc_0()?
                                    .ldloc_1()?
                                    .ldc_i4_1()?
                                    .add()?
                                    .stloc_1()?
                                    .br_s("loop_start")?
                                    .label("loop_end")?
                                    .ldloc_0()?
                                    .ret()?;
                                Ok(())
                            })
                    })
                    .build(assembly)?;

                Ok(())
            };

            let results = run_complete_test_with_reflection(
                &runner,
                compilation::templates::HELLO_WORLD,
                modify_assembly,
                |_assembly_path| {
                    vec![
                        // DoubleNumber: value * 2
                        MethodTest::new("DoubleNumber")
                            .arg_int(5)
                            .expect_int(10)
                            .describe("DoubleNumber(5) = 10"),
                        // AddTen: value + 10
                        MethodTest::new("AddTen")
                            .arg_int(7)
                            .expect_int(17)
                            .describe("AddTen(7) = 17"),
                        // ProcessNumber: (input * 2) + 10
                        // With input=5: (5*2) + 10 = 20
                        MethodTest::new("ProcessNumber")
                            .arg_int(5)
                            .expect_int(20)
                            .describe("ProcessNumber(5) = 20"),
                        // With input=15: (15*2) + 10 = 40
                        MethodTest::new("ProcessNumber")
                            .arg_int(15)
                            .expect_int(40)
                            .describe("ProcessNumber(15) = 40"),
                        // Factorial tests
                        // 5! = 120
                        MethodTest::new("Factorial")
                            .arg_int(5)
                            .expect_int(120)
                            .describe("Factorial(5) = 120"),
                        // 6! = 720
                        MethodTest::new("Factorial")
                            .arg_int(6)
                            .expect_int(720)
                            .describe("Factorial(6) = 720"),
                        // 1! = 1
                        MethodTest::new("Factorial")
                            .arg_int(1)
                            .expect_int(1)
                            .describe("Factorial(1) = 1"),
                    ]
                },
            )?;

            // Assert all tests passed
            for result in &results {
                assert!(
                    result.is_fully_successful(),
                    "Cross-reference test failed for {} architecture: {:?}",
                    result.architecture.name,
                    result.errors
                );
            }

            let expected_arch_count = runner.architectures().len();
            assert_eq!(
                results.len(),
                expected_arch_count,
                "Expected to test {} architectures",
                expected_arch_count
            );
            Ok(())
        }

        #[test]
        fn test_mono_blob_heap_and_complex_signatures() -> Result<()> {
            // Test blob heap modifications with complex method signatures
            let runner = TestRunner::new()?;

            let results = run_complete_test_with_reflection(
                &runner,
                compilation::templates::HELLO_WORLD,
                |assembly: &mut CilAssembly| -> Result<()> {
                    // ComplexMethod with mixed parameter types (int, string, bool)
                    let _complex_method = MethodBuilder::new("ComplexMethod")
                        .public()
                        .static_method()
                        .parameter("intParam", TypeSignature::I4)
                        .parameter("stringParam", TypeSignature::String)
                        .parameter("boolParam", TypeSignature::Boolean)
                        .returns(TypeSignature::String)
                        .implementation(|body| {
                            body.local("result", TypeSignature::String)
                                .implementation(|asm| {
                                    asm.ldstr(Token::new(0x70000001))?
                                        .stloc_0()?
                                        .ldloc_0()?
                                        .ret()?;
                                    Ok(())
                                })
                        })
                        .build(assembly)?;

                    let result_string_ref =
                        assembly.userstring_add("ComplexMethod executed successfully")?;
                    let _result_string_token =
                        Token::new(0x70000000 | result_string_ref.placeholder());

                    // TestParameters: (a + b) * c
                    let _param_test_method = MethodBuilder::new("TestParameters")
                        .public()
                        .static_method()
                        .parameter("a", TypeSignature::I4)
                        .parameter("b", TypeSignature::I4)
                        .parameter("c", TypeSignature::I4)
                        .returns(TypeSignature::I4)
                        .implementation(|body| {
                            body.implementation(|asm| {
                                asm.ldarg_0()?.ldarg_1()?.add()?.ldarg_2()?.mul()?.ret()?;
                                Ok(())
                            })
                        })
                        .build(assembly)?;

                    // BooleanLogic: flag1 AND flag2
                    let _bool_method = MethodBuilder::new("BooleanLogic")
                        .public()
                        .static_method()
                        .parameter("flag1", TypeSignature::Boolean)
                        .parameter("flag2", TypeSignature::Boolean)
                        .returns(TypeSignature::Boolean)
                        .implementation(|body| {
                            body.implementation(|asm| {
                                asm.ldarg_0()?.ldarg_1()?.and()?.ret()?;
                                Ok(())
                            })
                        })
                        .build(assembly)?;

                    Ok(())
                },
                |_assembly_path| {
                    vec![
                        // TestParameters: (a + b) * c
                        // (2 + 3) * 4 = 20
                        MethodTest::new("TestParameters")
                            .arg_int(2)
                            .arg_int(3)
                            .arg_int(4)
                            .expect_int(20)
                            .describe("TestParameters(2, 3, 4) = 20"),
                        // (10 + 5) * 2 = 30
                        MethodTest::new("TestParameters")
                            .arg_int(10)
                            .arg_int(5)
                            .arg_int(2)
                            .expect_int(30)
                            .describe("TestParameters(10, 5, 2) = 30"),
                        // BooleanLogic: flag1 AND flag2
                        // true AND false = false
                        MethodTest::new("BooleanLogic")
                            .arg_bool(true)
                            .arg_bool(false)
                            .expect_bool(false)
                            .describe("BooleanLogic(true, false) = false"),
                        // true AND true = true
                        MethodTest::new("BooleanLogic")
                            .arg_bool(true)
                            .arg_bool(true)
                            .expect_bool(true)
                            .describe("BooleanLogic(true, true) = true"),
                        // false AND false = false
                        MethodTest::new("BooleanLogic")
                            .arg_bool(false)
                            .arg_bool(false)
                            .expect_bool(false)
                            .describe("BooleanLogic(false, false) = false"),
                    ]
                },
            )?;

            // Assert all tests passed
            for result in &results {
                assert!(
                    result.is_fully_successful(),
                    "Blob heap/Complex signature test failed for {} architecture: {:?}",
                    result.architecture.name,
                    result.errors
                );
            }

            let expected_arch_count = runner.architectures().len();
            assert_eq!(
                results.len(),
                expected_arch_count,
                "Expected to test {} architectures",
                expected_arch_count
            );
            Ok(())
        }

        #[test]
        fn test_mono_reflection_detects_wrong_results() -> Result<()> {
            // Negative test: verify that our test framework actually detects wrong results
            // This ensures we're not just passing everything blindly
            let runner = TestRunner::new()?;

            // Create a simple Add method: returns a + b
            let results = run_complete_test_with_reflection(
                &runner,
                compilation::templates::HELLO_WORLD,
                |assembly: &mut CilAssembly| -> Result<()> {
                    let _add_method = MethodBuilder::new("Add")
                        .public()
                        .static_method()
                        .parameter("a", TypeSignature::I4)
                        .parameter("b", TypeSignature::I4)
                        .returns(TypeSignature::I4)
                        .implementation(|body| {
                            body.implementation(|asm| {
                                asm.ldarg_0()?.ldarg_1()?.add()?.ret()?;
                                Ok(())
                            })
                        })
                        .build(assembly)?;
                    Ok(())
                },
                |_assembly_path| {
                    vec![
                        // INTENTIONALLY WRONG: Add(2, 3) should be 5, not 999
                        MethodTest::new("Add")
                            .arg_int(2)
                            .arg_int(3)
                            .expect_int(999)
                            .describe("Add(2, 3) should NOT equal 999"),
                    ]
                },
            )?;

            // The reflection test should FAIL because 2+3=5, not 999
            for result in &results {
                assert!(
                    !result.reflection_success,
                    "Reflection should have FAILED for {} because we expected wrong result",
                    result.architecture.name
                );
                // Verify the error message mentions the mismatch
                let has_mismatch_error = result
                    .errors
                    .iter()
                    .any(|e| e.contains("Expected") || e.contains("999") || e.contains("5"));
                assert!(
                    has_mismatch_error,
                    "Error should mention result mismatch for {}: {:?}",
                    result.architecture.name, result.errors
                );
            }

            Ok(())
        }
    }
}