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
//! CIL instruction encoding and assembly functionality.
//!
//! This module provides the core instruction encoding capabilities for generating CIL bytecode
//! from high-level instruction representations. It serves as the reverse counterpart to the
//! decoder module, using the same instruction metadata tables for maximum consistency and code reuse.
//!
//! # Architecture
//!
//! The encoder follows a mirror approach to the decoder, reusing existing type definitions and
//! instruction metadata while providing reverse lookup capabilities. This ensures type safety
//! and maintains consistency between assembly and disassembly operations.
//!
//! # Key Components
//!
//! - [`InstructionEncoder`] - Core encoding engine for CIL instructions
//! - [`LabelFixup`] - Label resolution system for branch instructions
//! - Reverse lookup tables generated from existing [`crate::assembly::INSTRUCTIONS`] tables
//!
//! # Usage Examples
//!
//! ```rust,no_run
//! use dotscope::assembly::{InstructionEncoder, Operand, Immediate};
//!
//! let mut encoder = InstructionEncoder::new();
//!
//! // Encode simple instructions
//! encoder.emit_instruction("nop", None)?;
//! encoder.emit_instruction("ldarg.0", None)?;
//! encoder.emit_instruction("ldarg.s", Some(Operand::Immediate(Immediate::Int8(5))))?;
//! encoder.emit_instruction("add", None)?;
//! encoder.emit_instruction("ret", None)?;
//!
//! let bytecode = encoder.finalize()?;
//! # Ok::<(), dotscope::Error>(())
//! ```
//!
//! # Label Resolution
//!
//! ```rust,no_run
//! use dotscope::assembly::InstructionEncoder;
//!
//! let mut encoder = InstructionEncoder::new();
//!
//! encoder.emit_instruction("ldarg.0", None)?;
//! encoder.emit_branch("br.s", "end_label")?;
//! encoder.emit_instruction("ldarg.1", None)?;
//! encoder.define_label("end_label")?;
//! encoder.emit_instruction("ret", None)?;
//!
//! let bytecode = encoder.finalize()?; // Labels resolved automatically
//! # Ok::<(), dotscope::Error>(())
//! ```

use crate::{
    assembly::{
        instruction::{FlowType, Immediate, Instruction, Operand, OperandType},
        instructions::{CilInstruction, INSTRUCTIONS, INSTRUCTIONS_FE},
    },
    Error, Result,
};
use std::{
    collections::{HashMap, HashSet},
    sync::OnceLock,
};

/// Reverse lookup table mapping mnemonics to opcode information.
///
/// This static lookup table provides efficient O(1) mnemonic-to-opcode resolution by creating
/// a HashMap from the existing instruction tables. Each entry maps an instruction mnemonic
/// (e.g., "nop", "add", "br.s") to a tuple containing:
/// - Primary opcode byte
/// - Prefix byte (0x00 for single-byte instructions, 0xFE for extended instructions)  
/// - Reference to the instruction metadata
///
/// This approach maximizes code reuse by building on the existing static instruction tables
/// rather than duplicating instruction definitions.
static MNEMONIC_TO_OPCODE: OnceLock<
    HashMap<&'static str, (u8, u8, &'static CilInstruction<'static>)>,
> = OnceLock::new();

fn get_mnemonic_lookup(
) -> &'static HashMap<&'static str, (u8, u8, &'static CilInstruction<'static>)> {
    MNEMONIC_TO_OPCODE.get_or_init(|| {
        let mut map = HashMap::new();

        // Single-byte instructions (0x00 to 0xE0)
        for (opcode, instr) in INSTRUCTIONS.iter().enumerate() {
            if !instr.instr.is_empty() {
                let opcode_u8 = u8::try_from(opcode)
                    .unwrap_or_else(|_| panic!("Opcode {opcode} exceeds u8 range"));
                map.insert(instr.instr, (opcode_u8, 0, instr));
            }
        }

        // Extended instructions (0xFE prefix)
        for (opcode, instr) in INSTRUCTIONS_FE.iter().enumerate() {
            if !instr.instr.is_empty() {
                let opcode_u8 = u8::try_from(opcode)
                    .unwrap_or_else(|_| panic!("Opcode {opcode} exceeds u8 range"));
                map.insert(instr.instr, (opcode_u8, 0xFE, instr));
            }
        }

        map
    })
}

/// Label fixup information for branch instruction resolution.
///
/// This structure tracks unresolved label references during the encoding process,
/// allowing forward and backward branch resolution when the final bytecode positions
/// are calculated.
#[derive(Debug, Clone)]
pub struct LabelFixup {
    /// The target label name to resolve
    pub label: String,
    /// Position in bytecode where the branch offset should be written
    pub fixup_position: usize,
    /// Size of the branch offset field (1, 2, or 4 bytes)
    pub offset_size: u8,
    /// Position of the branch instruction for relative offset calculation
    pub instruction_position: usize,
    /// If Some, this branch can be optimized to short form using this mnemonic
    pub short_form_mnemonic: Option<&'static str>,
}

/// Switch fixup information for multi-way branch resolution.
///
/// This structure tracks unresolved switch target references, allowing
/// forward label resolution for switch instructions.
#[derive(Debug, Clone)]
pub struct SwitchFixup {
    /// The target label names to resolve (one per switch case)
    pub labels: Vec<String>,
    /// Position in bytecode where the switch targets start (after the count)
    pub fixup_position: usize,
    /// Position after the switch instruction (for relative offset calculation)
    pub instruction_end_position: usize,
}

/// Core CIL instruction encoder.
///
/// This encoder provides low-level instruction encoding capabilities, transforming
/// mnemonics and operands into CIL bytecode. It handles operand type validation,
/// opcode lookup, and maintains a label resolution system for branch instructions.
///
/// # Thread Safety
///
/// [`InstructionEncoder`] is not [`std::marker::Send`] or [`std::marker::Sync`] as it contains
/// mutable state for bytecode generation and label tracking. Create separate instances
/// for concurrent encoding operations.
///
/// # Examples
///
/// ## Basic Instruction Encoding
///
/// ```rust,no_run  
/// use dotscope::assembly::{InstructionEncoder, Operand, Immediate};
///
/// let mut encoder = InstructionEncoder::new();
///
/// // Simple instructions without operands
/// encoder.emit_instruction("nop", None)?;
/// encoder.emit_instruction("ret", None)?;
///
/// // Instructions with immediate operands
/// encoder.emit_instruction("ldc.i4.s", Some(Operand::Immediate(Immediate::Int8(42))))?;
/// encoder.emit_instruction("ldarg.s", Some(Operand::Immediate(Immediate::Int8(1))))?;
///
/// let result = encoder.finalize()?;
/// # Ok::<(), dotscope::Error>(())
/// ```
///
/// ## Branch Instructions with Labels
///
/// ```rust,no_run
/// use dotscope::assembly::InstructionEncoder;
///
/// let mut encoder = InstructionEncoder::new();
///
/// encoder.emit_instruction("ldarg.0", None)?;
/// encoder.emit_branch("brfalse.s", "false_case")?;
/// encoder.emit_instruction("ldc.i4.1", None)?;
/// encoder.emit_branch("br.s", "end")?;
///
/// encoder.define_label("false_case")?;
/// encoder.emit_instruction("ldc.i4.0", None)?;
///
/// encoder.define_label("end")?;
/// encoder.emit_instruction("ret", None)?;
///
/// let bytecode = encoder.finalize()?;
/// # Ok::<(), dotscope::Error>(())
/// ```
pub struct InstructionEncoder {
    /// Generated bytecode buffer
    bytecode: Vec<u8>,
    /// Defined label positions (label_name -> byte_position)
    labels: HashMap<String, u32>,
    /// Pending branch fixups awaiting label resolution
    fixups: Vec<LabelFixup>,
    /// Pending switch fixups awaiting label resolution
    switch_fixups: Vec<SwitchFixup>,
    /// Current stack depth (number of items on evaluation stack)
    current_stack_depth: i16,
    /// Maximum stack depth reached during encoding
    max_stack_depth: u16,
    /// Expected stack depth at branch targets for validation.
    /// When a branch is emitted, the current stack depth is recorded for the target label.
    /// When the label is defined, we verify all paths have the same depth.
    label_stack_depths: HashMap<String, i16>,
    /// Whether we're in unreachable code (after an unconditional branch, return, throw, etc.).
    /// When unreachable, the current_stack_depth is meaningless since there's no execution path.
    /// Defining a label resets this to false (the label makes code reachable again).
    unreachable: bool,
}

/// Maps long-form branch mnemonics to their short-form equivalents.
fn get_short_form_mnemonic(mnemonic: &str) -> Option<&'static str> {
    match mnemonic {
        "br" => Some("br.s"),
        "brfalse" => Some("brfalse.s"),
        "brtrue" => Some("brtrue.s"),
        "beq" => Some("beq.s"),
        "bne.un" => Some("bne.un.s"),
        "bge" => Some("bge.s"),
        "bge.un" => Some("bge.un.s"),
        "bgt" => Some("bgt.s"),
        "bgt.un" => Some("bgt.un.s"),
        "ble" => Some("ble.s"),
        "ble.un" => Some("ble.un.s"),
        "blt" => Some("blt.s"),
        "blt.un" => Some("blt.un.s"),
        "leave" => Some("leave.s"),
        _ => None,
    }
}

impl InstructionEncoder {
    /// Create a new instruction encoder.
    ///
    /// Initializes an empty encoder ready for instruction emission. The encoder
    /// maintains internal state for bytecode generation and label resolution.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::assembly::InstructionEncoder;
    ///
    /// let mut encoder = InstructionEncoder::new();
    /// // Ready for instruction emission
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    #[must_use]
    pub fn new() -> Self {
        Self {
            bytecode: Vec::new(),
            labels: HashMap::new(),
            fixups: Vec::new(),
            switch_fixups: Vec::new(),
            current_stack_depth: 0,
            max_stack_depth: 0,
            label_stack_depths: HashMap::new(),
            unreachable: false,
        }
    }

    /// Emit a CIL instruction with optional operand.
    ///
    /// This method performs instruction encoding by looking up the mnemonic in the
    /// reverse lookup table, validating the operand type, and emitting the appropriate
    /// bytecode sequence.
    ///
    /// # Parameters
    ///
    /// * `mnemonic` - The instruction mnemonic (e.g., "nop", "add", "ldarg.s")
    /// * `operand` - Optional operand for the instruction, must match expected type
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - The mnemonic is not recognized
    /// - The operand type doesn't match the instruction's expected operand type
    /// - The operand is missing when required or present when not expected
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::assembly::{InstructionEncoder, Operand, Immediate};
    ///
    /// let mut encoder = InstructionEncoder::new();
    ///
    /// // Instructions without operands
    /// encoder.emit_instruction("nop", None)?;
    /// encoder.emit_instruction("add", None)?;
    /// encoder.emit_instruction("ret", None)?;
    ///
    /// // Instructions with operands  
    /// encoder.emit_instruction("ldarg.s", Some(Operand::Immediate(Immediate::Int8(2))))?;
    /// encoder.emit_instruction("ldc.i4", Some(Operand::Immediate(Immediate::Int32(100))))?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn emit_instruction(&mut self, mnemonic: &str, operand: Option<Operand>) -> Result<()> {
        let (opcode, prefix, metadata) = get_mnemonic_lookup()
            .get(mnemonic)
            .ok_or_else(|| Error::InvalidMnemonic(mnemonic.to_string()))?;

        // Emit prefix byte if needed (0xFE for extended instructions)
        if *prefix != 0 {
            self.bytecode.push(*prefix);
        }

        // Emit primary opcode
        self.bytecode.push(*opcode);

        // Emit operand based on expected type
        self.emit_operand(operand, metadata.op_type)?;

        // Update stack tracking
        self.update_stack_depth(metadata.stack_pops, metadata.stack_pushes)
            .map_err(|e| malformed_error!("Stack error at instruction '{}': {}", mnemonic, e))?;

        // Mark code as unreachable after terminating instructions.
        // After these, there's no fall-through - execution only continues via labels.
        if matches!(
            metadata.flow,
            FlowType::Return | FlowType::Throw | FlowType::EndFinally
        ) {
            self.unreachable = true;
        }

        Ok(())
    }

    /// Emit an instruction from a previously decoded [`Instruction`].
    ///
    /// This method re-encodes a decoded instruction, preserving its mnemonic and operand.
    /// It's useful for transforming IL bytecode by decoding, modifying operands
    /// (e.g., remapping tokens), and re-encoding.
    ///
    /// # Arguments
    ///
    /// * `instruction` - The decoded instruction to emit
    ///
    /// # Errors
    ///
    /// Returns an error if the instruction's mnemonic is not recognized or if
    /// the operand doesn't match the expected type for that instruction.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::assembly::{InstructionEncoder, decode_stream};
    /// use dotscope::Parser;
    ///
    /// // Decode some IL
    /// let il_bytes = &[0x00, 0x2A]; // nop, ret
    /// let mut parser = Parser::new(il_bytes);
    /// let instructions = decode_stream(&mut parser, 0)?;
    ///
    /// // Re-encode the instructions
    /// let mut encoder = InstructionEncoder::new();
    /// for instr in &instructions {
    ///     encoder.emit_instruction_decoded(instr)?;
    /// }
    /// let (bytecode, _, _) = encoder.finalize()?;
    /// assert_eq!(bytecode, il_bytes);
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn emit_instruction_decoded(&mut self, instruction: &Instruction) -> Result<()> {
        let operand = if matches!(instruction.operand, Operand::None) {
            None
        } else {
            Some(instruction.operand.clone())
        };
        self.emit_instruction(instruction.mnemonic, operand)
    }

    /// Emit a branch instruction with label reference.
    ///
    /// This method handles branch instructions that reference labels, creating
    /// fixup entries for later resolution. The branch offset will be calculated
    /// and written during the finalization process.
    ///
    /// # Parameters
    ///
    /// * `mnemonic` - The branch instruction mnemonic (e.g., "br.s", "brfalse", "brtrue.s")
    /// * `label` - The target label name to branch to
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::InvalidMnemonic`] if the mnemonic is not recognized.
    /// Returns [`crate::Error::InvalidBranch`] if the mnemonic is not a branch instruction
    /// or has an invalid operand type for branch encoding.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::assembly::InstructionEncoder;
    ///
    /// let mut encoder = InstructionEncoder::new();
    ///
    /// encoder.emit_branch("br.s", "target_label")?;
    /// encoder.emit_instruction("nop", None)?;
    /// encoder.define_label("target_label")?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn emit_branch(&mut self, mnemonic: &str, label: &str) -> Result<()> {
        let (opcode, prefix, metadata) = get_mnemonic_lookup()
            .get(mnemonic)
            .ok_or_else(|| Error::InvalidMnemonic(mnemonic.to_string()))?;

        // Verify this is actually a branch instruction
        if !matches!(
            metadata.flow,
            FlowType::ConditionalBranch | FlowType::UnconditionalBranch | FlowType::Leave
        ) {
            return Err(Error::InvalidBranch(format!(
                "instruction '{mnemonic}' is not a branch instruction"
            )));
        }

        let instruction_start = self.bytecode.len();

        // Emit prefix byte if needed
        if *prefix != 0 {
            self.bytecode.push(*prefix);
        }

        // Emit primary opcode
        self.bytecode.push(*opcode);

        // Determine offset size and create fixup
        let offset_size = match metadata.op_type {
            OperandType::Int8 => 1,
            OperandType::Int16 => 2,
            OperandType::Int32 => 4,
            _ => {
                return Err(Error::InvalidBranch(
                    "operand type must be Int8, Int16, or Int32".to_string(),
                ))
            }
        };

        // Record fixup for later resolution
        // For long-form branches, record the short form for potential optimization
        let short_form_mnemonic = if offset_size == 4 {
            get_short_form_mnemonic(mnemonic)
        } else {
            None
        };
        let fixup = LabelFixup {
            label: label.to_string(),
            fixup_position: self.bytecode.len(),
            offset_size,
            instruction_position: instruction_start,
            short_form_mnemonic,
        };
        self.fixups.push(fixup);

        // Emit placeholder bytes for the offset (will be filled during finalization)
        for _ in 0..offset_size {
            self.bytecode.push(0);
        }

        // Update stack tracking for branch instructions
        self.update_stack_depth(metadata.stack_pops, metadata.stack_pushes)
            .map_err(|e| {
                malformed_error!("Stack error at branch '{}' to '{}': {}", mnemonic, label, e)
            })?;

        // Record expected stack depth at branch target for validation.
        // After the branch pops its condition (if any), the target should see this depth.
        self.record_label_stack_depth(label)?;

        // Mark code as unreachable after unconditional branches.
        // Conditional branches (brfalse, brtrue, beq, etc.) have fall-through paths,
        // but unconditional branches (br, leave) and their short forms do not.
        if matches!(
            metadata.flow,
            FlowType::UnconditionalBranch | FlowType::Leave
        ) {
            self.unreachable = true;
        }

        Ok(())
    }

    /// Emit a switch instruction with multiple target labels.
    ///
    /// The switch instruction performs a multi-way branch based on an integer value.
    /// If the value is within range (0 to n-1), execution transfers to the corresponding
    /// label. If the value is out of range, execution continues to the next instruction
    /// (fall-through).
    ///
    /// # Parameters
    ///
    /// * `labels` - Target label names for each switch case (0-indexed)
    ///
    /// # Errors
    ///
    /// Returns an error if the labels slice is empty or instruction encoding fails.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::assembly::InstructionEncoder;
    ///
    /// let mut encoder = InstructionEncoder::new();
    ///
    /// encoder.emit_instruction("ldarg.0", None)?;
    /// encoder.emit_switch(&["case0", "case1", "case2"])?;
    /// encoder.emit_instruction("ldc.i4.m1", None)?; // Default case (fall-through)
    /// encoder.emit_instruction("ret", None)?;
    ///
    /// encoder.define_label("case0")?;
    /// encoder.emit_instruction("ldc.i4.0", None)?;
    /// encoder.emit_instruction("ret", None)?;
    ///
    /// encoder.define_label("case1")?;
    /// encoder.emit_instruction("ldc.i4.1", None)?;
    /// encoder.emit_instruction("ret", None)?;
    ///
    /// encoder.define_label("case2")?;
    /// encoder.emit_instruction("ldc.i4.2", None)?;
    /// encoder.emit_instruction("ret", None)?;
    ///
    /// let (bytecode, max_stack, _) = encoder.finalize()?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn emit_switch(&mut self, labels: &[&str]) -> Result<()> {
        if labels.is_empty() {
            return Err(Error::InvalidBranch(
                "switch must have at least one target".to_string(),
            ));
        }

        // Emit the switch opcode (0x45)
        self.bytecode.push(0x45);

        // Emit the number of targets
        let num_targets =
            u32::try_from(labels.len()).map_err(|_| malformed_error!("Too many switch targets"))?;
        self.bytecode.extend_from_slice(&num_targets.to_le_bytes());

        // Record the position where targets start
        let fixup_position = self.bytecode.len();

        // Emit placeholder bytes for each target (4 bytes each)
        for _ in 0..labels.len() {
            self.bytecode.extend_from_slice(&[0, 0, 0, 0]);
        }

        // Record the position after the switch instruction (for relative offset calculation)
        let instruction_end_position = self.bytecode.len();

        // Create the switch fixup
        let switch_fixup = SwitchFixup {
            labels: labels.iter().map(|s| (*s).to_string()).collect(),
            fixup_position,
            instruction_end_position,
        };
        self.switch_fixups.push(switch_fixup);

        // Switch pops one value from the stack
        self.update_stack_depth(1, 0)
            .map_err(|e| malformed_error!("Stack error at 'switch': {}", e))?;

        // Record expected stack depth at all switch targets for validation
        for label in labels {
            self.record_label_stack_depth(label)?;
        }

        Ok(())
    }

    /// Emit a call instruction with explicit stack effect tracking.
    ///
    /// This method handles `call`, `callvirt`, `calli`, and `newobj` instructions
    /// where the stack effect depends on the method signature and cannot be
    /// determined from static instruction metadata alone.
    ///
    /// # Parameters
    ///
    /// * `mnemonic` - The instruction mnemonic ("call", "callvirt", "calli", or "newobj")
    /// * `operand` - The method/signature token operand
    /// * `num_args` - Number of arguments popped from stack (including 'this' for instance calls)
    /// * `has_result` - Whether the call pushes a result onto the stack
    ///
    /// # Errors
    ///
    /// Returns an error if the mnemonic is not recognized or encoding fails.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::assembly::{InstructionEncoder, Operand};
    /// use dotscope::metadata::token::Token;
    ///
    /// let mut encoder = InstructionEncoder::new();
    ///
    /// // Call a method with 2 arguments that returns a value
    /// encoder.emit_call(
    ///     "call",
    ///     Some(Operand::Token(Token::new(0x0a000001))),
    ///     2,    // pops 2 arguments
    ///     true  // pushes 1 result
    /// )?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn emit_call(
        &mut self,
        mnemonic: &str,
        operand: Option<Operand>,
        num_args: u8,
        has_result: bool,
    ) -> Result<()> {
        let (opcode, prefix, metadata) = get_mnemonic_lookup()
            .get(mnemonic)
            .ok_or_else(|| Error::InvalidMnemonic(mnemonic.to_string()))?;

        // Emit prefix byte if needed (0xFE for extended instructions)
        if *prefix != 0 {
            self.bytecode.push(*prefix);
        }

        // Emit primary opcode
        self.bytecode.push(*opcode);

        // Emit operand based on expected type
        self.emit_operand(operand, metadata.op_type)?;

        // Use the caller-provided stack effect instead of metadata
        let pushes = u8::from(has_result);
        self.update_stack_depth(num_args, pushes)
            .map_err(|e| malformed_error!("Stack error at call '{}': {}", mnemonic, e))?;

        Ok(())
    }

    /// Emit a `ldarg` instruction with optimal encoding.
    ///
    /// Automatically selects the most compact form:
    /// - `ldarg.0` through `ldarg.3` for indices 0-3 (1 byte)
    /// - `ldarg.s` for indices 4-255 (2 bytes)
    /// - `ldarg` for indices 256+ (4 bytes)
    ///
    /// # Errors
    ///
    /// Returns an error if instruction encoding fails.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::assembly::InstructionEncoder;
    ///
    /// let mut encoder = InstructionEncoder::new();
    /// encoder.emit_ldarg(0)?;  // Emits ldarg.0 (1 byte)
    /// encoder.emit_ldarg(10)?; // Emits ldarg.s 10 (2 bytes)
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn emit_ldarg(&mut self, index: u16) -> Result<()> {
        match index {
            0 => self.emit_instruction("ldarg.0", None),
            1 => self.emit_instruction("ldarg.1", None),
            2 => self.emit_instruction("ldarg.2", None),
            3 => self.emit_instruction("ldarg.3", None),
            x if x <= 255 =>
            {
                #[allow(clippy::cast_possible_truncation)]
                self.emit_instruction(
                    "ldarg.s",
                    Some(Operand::Immediate(Immediate::UInt8(x as u8))),
                )
            }
            x =>
            {
                #[allow(clippy::cast_possible_wrap)]
                self.emit_instruction(
                    "ldarg",
                    Some(Operand::Immediate(Immediate::Int16(x as i16))),
                )
            }
        }
    }

    /// Emit a `ldloc` instruction with optimal encoding.
    ///
    /// Automatically selects the most compact form:
    /// - `ldloc.0` through `ldloc.3` for indices 0-3 (1 byte)
    /// - `ldloc.s` for indices 4-255 (2 bytes)
    /// - `ldloc` for indices 256+ (4 bytes)
    ///
    /// # Errors
    ///
    /// Returns an error if instruction encoding fails.
    pub fn emit_ldloc(&mut self, index: u16) -> Result<()> {
        match index {
            0 => self.emit_instruction("ldloc.0", None),
            1 => self.emit_instruction("ldloc.1", None),
            2 => self.emit_instruction("ldloc.2", None),
            3 => self.emit_instruction("ldloc.3", None),
            x if x <= 255 =>
            {
                #[allow(clippy::cast_possible_truncation)]
                self.emit_instruction(
                    "ldloc.s",
                    Some(Operand::Immediate(Immediate::UInt8(x as u8))),
                )
            }
            x =>
            {
                #[allow(clippy::cast_possible_wrap)]
                self.emit_instruction(
                    "ldloc",
                    Some(Operand::Immediate(Immediate::Int16(x as i16))),
                )
            }
        }
    }

    /// Emit a `starg` instruction with optimal encoding.
    ///
    /// Automatically selects the most compact form:
    /// - `starg.s` for indices 0-255 (2 bytes)
    /// - `starg` for indices 256+ (4 bytes)
    ///
    /// # Errors
    ///
    /// Returns an error if instruction encoding fails.
    pub fn emit_starg(&mut self, index: u16) -> Result<()> {
        if index <= 255 {
            #[allow(clippy::cast_possible_truncation)]
            self.emit_instruction(
                "starg.s",
                Some(Operand::Immediate(Immediate::UInt8(index as u8))),
            )
        } else {
            #[allow(clippy::cast_possible_wrap)]
            self.emit_instruction(
                "starg",
                Some(Operand::Immediate(Immediate::Int16(index as i16))),
            )
        }
    }

    /// Emit a `stloc` instruction with optimal encoding.
    ///
    /// Automatically selects the most compact form:
    /// - `stloc.0` through `stloc.3` for indices 0-3 (1 byte)
    /// - `stloc.s` for indices 4-255 (2 bytes)
    /// - `stloc` for indices 256+ (4 bytes)
    ///
    /// # Errors
    ///
    /// Returns an error if instruction encoding fails.
    pub fn emit_stloc(&mut self, index: u16) -> Result<()> {
        match index {
            0 => self.emit_instruction("stloc.0", None),
            1 => self.emit_instruction("stloc.1", None),
            2 => self.emit_instruction("stloc.2", None),
            3 => self.emit_instruction("stloc.3", None),
            x if x <= 255 =>
            {
                #[allow(clippy::cast_possible_truncation)]
                self.emit_instruction(
                    "stloc.s",
                    Some(Operand::Immediate(Immediate::UInt8(x as u8))),
                )
            }
            x =>
            {
                #[allow(clippy::cast_possible_wrap)]
                self.emit_instruction(
                    "stloc",
                    Some(Operand::Immediate(Immediate::Int16(x as i16))),
                )
            }
        }
    }

    /// Emit a `ldc.i4` instruction with optimal encoding.
    ///
    /// Automatically selects the most compact form:
    /// - `ldc.i4.m1` through `ldc.i4.8` for values -1 to 8 (1 byte)
    /// - `ldc.i4.s` for values -128 to 127 (2 bytes)
    /// - `ldc.i4` for all other values (5 bytes)
    ///
    /// # Errors
    ///
    /// Returns an error if instruction encoding fails.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::assembly::InstructionEncoder;
    ///
    /// let mut encoder = InstructionEncoder::new();
    /// encoder.emit_ldc_i4(0)?;      // Emits ldc.i4.0 (1 byte)
    /// encoder.emit_ldc_i4(42)?;     // Emits ldc.i4.s 42 (2 bytes)
    /// encoder.emit_ldc_i4(1000)?;   // Emits ldc.i4 1000 (5 bytes)
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn emit_ldc_i4(&mut self, value: i32) -> Result<()> {
        match value {
            -1 => self.emit_instruction("ldc.i4.m1", None),
            0 => self.emit_instruction("ldc.i4.0", None),
            1 => self.emit_instruction("ldc.i4.1", None),
            2 => self.emit_instruction("ldc.i4.2", None),
            3 => self.emit_instruction("ldc.i4.3", None),
            4 => self.emit_instruction("ldc.i4.4", None),
            5 => self.emit_instruction("ldc.i4.5", None),
            6 => self.emit_instruction("ldc.i4.6", None),
            7 => self.emit_instruction("ldc.i4.7", None),
            8 => self.emit_instruction("ldc.i4.8", None),
            x if (-128..=127).contains(&x) =>
            {
                #[allow(clippy::cast_possible_truncation)]
                self.emit_instruction(
                    "ldc.i4.s",
                    Some(Operand::Immediate(Immediate::Int8(x as i8))),
                )
            }
            x => self.emit_instruction("ldc.i4", Some(Operand::Immediate(Immediate::Int32(x)))),
        }
    }

    /// Emit a `ldarga` instruction with optimal encoding.
    ///
    /// Automatically selects the most compact form:
    /// - `ldarga.s` for indices 0-255 (2 bytes)
    /// - `ldarga` for indices 256+ (4 bytes)
    ///
    /// # Errors
    ///
    /// Returns an error if instruction encoding fails.
    pub fn emit_ldarga(&mut self, index: u16) -> Result<()> {
        if index <= 255 {
            #[allow(clippy::cast_possible_truncation)]
            self.emit_instruction(
                "ldarga.s",
                Some(Operand::Immediate(Immediate::UInt8(index as u8))),
            )
        } else {
            #[allow(clippy::cast_possible_wrap)]
            self.emit_instruction(
                "ldarga",
                Some(Operand::Immediate(Immediate::Int16(index as i16))),
            )
        }
    }

    /// Emit a `ldloca` instruction with optimal encoding.
    ///
    /// Automatically selects the most compact form:
    /// - `ldloca.s` for indices 0-255 (2 bytes)
    /// - `ldloca` for indices 256+ (4 bytes)
    ///
    /// # Errors
    ///
    /// Returns an error if instruction encoding fails.
    pub fn emit_ldloca(&mut self, index: u16) -> Result<()> {
        if index <= 255 {
            #[allow(clippy::cast_possible_truncation)]
            self.emit_instruction(
                "ldloca.s",
                Some(Operand::Immediate(Immediate::UInt8(index as u8))),
            )
        } else {
            #[allow(clippy::cast_possible_wrap)]
            self.emit_instruction(
                "ldloca",
                Some(Operand::Immediate(Immediate::Int16(index as i16))),
            )
        }
    }

    /// Define a label at the current bytecode position.
    ///
    /// Labels mark positions in the bytecode that can be referenced by branch
    /// instructions. Each label must have a unique name within the encoder scope.
    ///
    /// # Parameters
    ///
    /// * `name` - Unique label name
    ///
    /// # Errors
    ///
    /// Returns an error if a label with the same name has already been defined.
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::assembly::InstructionEncoder;
    ///
    /// let mut encoder = InstructionEncoder::new();
    ///
    /// encoder.emit_instruction("nop", None)?;
    /// encoder.define_label("loop_start")?;
    /// encoder.emit_instruction("ldarg.0", None)?;
    /// encoder.emit_branch("br.s", "loop_start")?;
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn define_label(&mut self, name: &str) -> Result<()> {
        if self.labels.contains_key(name) {
            return Err(Error::DuplicateLabel(name.to_string()));
        }

        // Validate or set stack depth for this label.
        // All control flow paths to this label must have the same stack depth.
        if let Some(&expected) = self.label_stack_depths.get(name) {
            if self.unreachable {
                // We're in unreachable code (after an unconditional branch/return/throw).
                // The current_stack_depth is meaningless since there's no execution path here.
                // Reset to the expected depth from branches that target this label.
                self.current_stack_depth = expected;
            } else if self.current_stack_depth != expected {
                // We have a fall-through path AND branches to this label.
                // All paths must have the same stack depth.
                return Err(malformed_error!(
                    "Stack depth mismatch at label '{}': expected {} (from branch), got {} (current)",
                    name,
                    expected,
                    self.current_stack_depth
                ));
            }
        } else if !self.unreachable {
            // First time seeing this label via fall-through from reachable code.
            // Record the current depth as expected.
            self.label_stack_depths
                .insert(name.to_string(), self.current_stack_depth);
        } else {
            // Unreachable code with no existing expected depth.
            // Reset current_stack_depth to 0 before making code reachable again.
            // The depth was meaningless garbage from unreachable code, and we don't
            // want it to propagate to reachable code that follows this label.
            // The first actual branch to this label will set the correct expected depth.
            self.current_stack_depth = 0;
        }

        // Defining a label makes code reachable again (via branches to this label).
        self.unreachable = false;

        let bytecode_len = u32::try_from(self.bytecode.len())
            .map_err(|_| malformed_error!("Bytecode length exceeds u32 range"))?;
        self.labels.insert(name.to_string(), bytecode_len);
        Ok(())
    }

    /// Returns the current bytecode position (length of emitted bytecode so far).
    ///
    /// This can be used to track instruction offsets during code generation,
    /// for example to record block start positions for exception handler remapping.
    ///
    /// # Returns
    ///
    /// The current bytecode length in bytes.
    #[must_use]
    pub fn current_position(&self) -> u32 {
        // CIL method bodies are limited to u32 size by the format
        #[allow(clippy::cast_possible_truncation)]
        let position = self.bytecode.len() as u32;
        position
    }

    /// Ensures the method ends with a proper method-terminating instruction.
    ///
    /// CIL methods must end with an instruction that terminates execution
    /// (ret, throw, rethrow, jmp, endfinally). Control flow instructions like
    /// `br` or `br.s` transfer control but don't terminate the method - if the
    /// branch target is an empty block at the end, the decoder would read past
    /// the method body into garbage data.
    ///
    /// This method checks two conditions:
    /// 1. If the bytecode ends with a valid method terminator opcode
    /// 2. If any branch targets a label at or past the end of bytecode (empty block)
    ///
    /// If either condition fails, a `ret` instruction is appended.
    ///
    /// # Method Terminators
    ///
    /// The following opcodes are considered proper method terminators:
    /// - `ret` (0x2A) - Return from method
    /// - `throw` (0x7A) - Throw exception
    /// - `rethrow` (0xFE 0x1A) - Rethrow current exception
    /// - `endfinally` (0xDC) - End finally/fault block
    /// - `jmp` (0x27) - Jump to another method (tail call)
    ///
    /// # Errors
    ///
    /// Returns an error if emitting the `ret` instruction fails.
    fn ensure_method_terminated(&mut self) -> Result<()> {
        if self.bytecode.is_empty() {
            // Empty method - no terminator needed (or handled elsewhere)
            return Ok(());
        }

        // Check if the last instruction is a proper method terminator
        let ends_with_terminator = if let Some(&last_byte) = self.bytecode.last() {
            // Single-byte terminators: ret, throw, endfinally, jmp
            matches!(last_byte, 0x2A | 0x7A | 0xDC | 0x27)
                // Two-byte terminator: rethrow (0xFE 0x1A)
                || (self.bytecode.len() >= 2
                    && self.bytecode[self.bytecode.len() - 2] == 0xFE
                    && last_byte == 0x1A)
        } else {
            false
        };

        if ends_with_terminator {
            return Ok(());
        }

        // The bytecode doesn't end with a terminator. Check if any branch targets
        // a label at or past the current end of bytecode. Such branches point to
        // empty blocks and need valid code at the target.
        let current_len = self.bytecode.len();
        let has_branch_to_end = self.fixups.iter().any(|fixup| {
            if let Some(&label_pos) = self.labels.get(&fixup.label) {
                // Label is defined at or past the end of bytecode
                label_pos as usize >= current_len
            } else {
                // Label not defined yet - shouldn't happen, but be safe
                false
            }
        });

        if has_branch_to_end {
            self.emit_instruction("ret", None)?;
        }

        Ok(())
    }

    /// Returns the resolved offset for a defined label.
    ///
    /// # Arguments
    ///
    /// * `name` - The label name to look up.
    ///
    /// # Returns
    ///
    /// The byte offset of the label, or `None` if the label is not defined.
    #[must_use]
    pub fn label_offset(&self, name: &str) -> Option<u32> {
        self.labels.get(name).copied()
    }

    /// Finalize encoding and resolve all label references.
    ///
    /// This method completes the encoding process by resolving all pending label
    /// fixups and calculating branch offsets. After finalization, the encoder
    /// cannot be used for further instruction emission.
    ///
    /// # Returns
    ///
    /// A tuple containing:
    /// - The complete CIL bytecode with all labels resolved
    /// - The maximum stack depth required during execution
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - [`crate::Error::UndefinedLabel`] - Any referenced labels are undefined
    /// - [`crate::Error::InvalidBranch`] - Branch offsets exceed the allowed range for their instruction type
    /// - [`crate::Error::Malformed`] - Stack underflow occurred during encoding (negative stack depth)
    ///
    /// # Examples
    ///
    /// ```rust,no_run
    /// use dotscope::assembly::InstructionEncoder;
    ///
    /// let mut encoder = InstructionEncoder::new();
    /// encoder.emit_instruction("ldc.i4.1", None)?; // Pushes 1 item
    /// encoder.emit_instruction("ret", None)?;     // Returns with 1 item
    ///
    /// let (bytecode, max_stack, _labels) = encoder.finalize()?;
    /// assert_eq!(bytecode, vec![0x17, 0x2A]); // ldc.i4.1, ret
    /// assert_eq!(max_stack, 1); // Maximum stack depth was 1
    /// # Ok::<(), dotscope::Error>(())
    /// ```
    pub fn finalize(mut self) -> Result<(Vec<u8>, u16, HashMap<String, u32>)> {
        // Ensure the method ends with a proper terminating instruction.
        // This must be done before branch optimization since it may add instructions.
        self.ensure_method_terminated()?;

        // Optimize branches iteratively until no more improvements
        self.optimize_branch_forms()?;

        // Resolve all branch fixups
        let fixups = std::mem::take(&mut self.fixups);
        for fixup in &fixups {
            let label_position = self
                .labels
                .get(&fixup.label)
                .ok_or_else(|| Error::UndefinedLabel(fixup.label.clone()))?;

            // Calculate relative offset from end of branch instruction to label
            let next_instruction_pos = fixup.fixup_position + fixup.offset_size as usize;

            let label_pos_i32 = i32::try_from(*label_position)
                .map_err(|_| malformed_error!("Label position exceeds i32 range"))?;
            let next_instr_pos_i32 = i32::try_from(next_instruction_pos)
                .map_err(|_| malformed_error!("Instruction position exceeds i32 range"))?;

            let offset = label_pos_i32 - next_instr_pos_i32;

            self.write_branch_offset(offset, fixup)?;
        }

        // Process switch fixups
        let switch_fixups = std::mem::take(&mut self.switch_fixups);
        for switch_fixup in &switch_fixups {
            let instruction_end_i32 = i32::try_from(switch_fixup.instruction_end_position)
                .map_err(|_| malformed_error!("Switch instruction end exceeds i32 range"))?;

            for (i, label) in switch_fixup.labels.iter().enumerate() {
                let label_position = self
                    .labels
                    .get(label)
                    .ok_or_else(|| Error::UndefinedLabel(label.clone()))?;

                let label_pos_i32 = i32::try_from(*label_position)
                    .map_err(|_| malformed_error!("Label position exceeds i32 range"))?;

                // Switch offsets are relative to the end of the switch instruction
                let offset = label_pos_i32 - instruction_end_i32;

                // Write the 4-byte offset at the correct position
                let target_pos = switch_fixup.fixup_position + i * 4;
                let offset_bytes = offset.to_le_bytes();
                self.bytecode[target_pos..target_pos + 4].copy_from_slice(&offset_bytes);
            }
        }

        // Return bytecode, max stack, and final label positions (after branch optimization)
        Ok((self.bytecode, self.max_stack_depth, self.labels))
    }

    /// Optimize branch forms by converting long-form branches to short-form where possible.
    ///
    /// This method iteratively shrinks branches until no more optimizations are possible.
    /// Each iteration may enable additional optimizations as the bytecode shrinks.
    fn optimize_branch_forms(&mut self) -> Result<()> {
        const MAX_ITERATIONS: usize = 100;

        for _ in 0..MAX_ITERATIONS {
            let shrinkable = self.find_shrinkable_branches()?;
            if shrinkable.is_empty() {
                break; // No more optimizations possible
            }

            // Rebuild bytecode with short-form branches
            self.apply_branch_shrinking(&shrinkable)?;
        }

        Ok(())
    }

    /// Find branches that could be converted to short form.
    ///
    /// Returns indices of fixups that can be shrunk.
    fn find_shrinkable_branches(&self) -> Result<Vec<usize>> {
        let mut shrinkable = Vec::new();

        for (idx, fixup) in self.fixups.iter().enumerate() {
            // Only consider long-form branches that have a short form
            if fixup.offset_size != 4 || fixup.short_form_mnemonic.is_none() {
                continue;
            }

            let label_position = self
                .labels
                .get(&fixup.label)
                .ok_or_else(|| Error::UndefinedLabel(fixup.label.clone()))?;

            // Calculate offset as if we used short form (1 byte offset instead of 4)
            // Short form: instruction is 2 bytes (opcode + 1-byte offset)
            // The offset is relative to the end of the instruction
            let short_form_end = fixup.instruction_position + 2; // opcode + 1-byte offset

            let label_pos_i32 = i32::try_from(*label_position)
                .map_err(|_| malformed_error!("Label position exceeds i32 range"))?;
            let short_end_i32 = i32::try_from(short_form_end)
                .map_err(|_| malformed_error!("Instruction position exceeds i32 range"))?;

            // Calculate what the offset would be with short form
            // Note: We need to account for the 3-byte savings in positions after this branch
            let offset = label_pos_i32 - short_end_i32;

            // Check if offset fits in signed byte (-128 to +127)
            if (-128..=127).contains(&offset) {
                shrinkable.push(idx);
            }
        }

        Ok(shrinkable)
    }

    /// Apply branch shrinking by rebuilding bytecode with short-form branches.
    fn apply_branch_shrinking(&mut self, shrinkable: &[usize]) -> Result<()> {
        if shrinkable.is_empty() {
            return Ok(());
        }

        // Build a set for O(1) lookup
        let shrinkable_set: HashSet<usize> = shrinkable.iter().copied().collect();

        // Calculate position adjustments for each shrunk branch
        // Each shrunk branch saves 3 bytes (5 bytes -> 2 bytes)
        let mut adjustments: Vec<(usize, i32)> = Vec::new(); // (position, cumulative_adjustment)
        let mut cumulative = 0i32;

        for &idx in shrinkable {
            let fixup = &self.fixups[idx];
            // The adjustment takes effect after this instruction
            let instr_end = fixup.fixup_position + fixup.offset_size as usize;
            cumulative -= 3; // Shrinking saves 3 bytes
            adjustments.push((instr_end, cumulative));
        }

        // Helper to calculate adjusted position
        let adjust_position = |pos: usize| -> usize {
            let mut adj = 0i32;
            for &(threshold, cumulative_adj) in &adjustments {
                if pos >= threshold {
                    adj = cumulative_adj;
                } else {
                    break;
                }
            }
            // CIL method bodies are limited by format; positions are validated elsewhere
            #[allow(
                clippy::cast_possible_truncation,
                clippy::cast_possible_wrap,
                clippy::cast_sign_loss
            )]
            let adjusted = (pos as i32 + adj).max(0) as usize;
            adjusted
        };

        // Rebuild bytecode
        let mut new_bytecode = Vec::with_capacity(self.bytecode.len());
        let mut src_pos = 0usize;

        // Sort fixups by position for sequential processing
        let mut sorted_indices: Vec<usize> = (0..self.fixups.len()).collect();
        sorted_indices.sort_by_key(|&i| self.fixups[i].instruction_position);

        for &idx in &sorted_indices {
            let fixup = &self.fixups[idx];

            // Copy bytes up to this instruction
            if src_pos < fixup.instruction_position {
                new_bytecode.extend_from_slice(&self.bytecode[src_pos..fixup.instruction_position]);
            }
            src_pos = fixup.instruction_position;

            if shrinkable_set.contains(&idx) {
                // Emit short-form branch
                let short_mnemonic = fixup.short_form_mnemonic.ok_or_else(|| {
                    Error::InvalidMnemonic("missing short form for shrinkable branch".to_string())
                })?;
                let (opcode, prefix, _) = get_mnemonic_lookup()
                    .get(short_mnemonic)
                    .ok_or_else(|| Error::InvalidMnemonic(short_mnemonic.to_string()))?;

                if *prefix != 0 {
                    new_bytecode.push(*prefix);
                }
                new_bytecode.push(*opcode);
                new_bytecode.push(0); // Placeholder for offset

                // Skip the original instruction (opcode + 4-byte offset)
                src_pos = fixup.fixup_position + 4;
            } else {
                // Copy original instruction
                let instr_end = fixup.fixup_position + fixup.offset_size as usize;
                new_bytecode.extend_from_slice(&self.bytecode[src_pos..instr_end]);
                src_pos = instr_end;
            }
        }

        // Copy remaining bytes
        if src_pos < self.bytecode.len() {
            new_bytecode.extend_from_slice(&self.bytecode[src_pos..]);
        }

        // Update labels
        for pos in self.labels.values_mut() {
            // CIL method bodies are limited to u32 size by the format
            #[allow(clippy::cast_possible_truncation)]
            let adjusted_pos = adjust_position(*pos as usize) as u32;
            *pos = adjusted_pos;
        }

        // Update fixups
        for (idx, fixup) in self.fixups.iter_mut().enumerate() {
            let new_instr_pos = adjust_position(fixup.instruction_position);

            if shrinkable_set.contains(&idx) {
                // This branch was shrunk
                fixup.instruction_position = new_instr_pos;
                fixup.fixup_position = new_instr_pos + 1; // opcode + offset position
                fixup.offset_size = 1;
                fixup.short_form_mnemonic = None; // Already optimized
            } else {
                // Just adjust positions
                fixup.instruction_position = new_instr_pos;
                fixup.fixup_position = adjust_position(fixup.fixup_position);
            }
        }

        // Update switch fixups
        for switch_fixup in &mut self.switch_fixups {
            switch_fixup.fixup_position = adjust_position(switch_fixup.fixup_position);
            switch_fixup.instruction_end_position =
                adjust_position(switch_fixup.instruction_end_position);
        }

        self.bytecode = new_bytecode;
        Ok(())
    }

    /// Emit operand bytes based on the expected operand type.
    ///
    /// This internal method handles the encoding of instruction operands according
    /// to their expected types, performing validation and byte serialization.
    fn emit_operand(&mut self, operand: Option<Operand>, expected: OperandType) -> Result<()> {
        match expected {
            OperandType::None => {
                if operand.is_some() {
                    return Err(Error::UnexpectedOperand);
                }
            }
            OperandType::Int8 => {
                if let Some(Operand::Immediate(Immediate::Int8(val))) = operand {
                    self.bytecode.push(val.to_le_bytes()[0]);
                } else {
                    return Err(Error::WrongOperandType {
                        expected: "Int8".to_string(),
                    });
                }
            }
            OperandType::UInt8 => {
                if let Some(Operand::Immediate(Immediate::UInt8(val))) = operand {
                    self.bytecode.push(val);
                } else {
                    return Err(Error::WrongOperandType {
                        expected: "UInt8".to_string(),
                    });
                }
            }
            OperandType::Int16 => {
                if let Some(Operand::Immediate(Immediate::Int16(val))) = operand {
                    self.bytecode.extend_from_slice(&val.to_le_bytes());
                } else {
                    return Err(Error::WrongOperandType {
                        expected: "Int16".to_string(),
                    });
                }
            }
            OperandType::UInt16 => {
                if let Some(Operand::Immediate(Immediate::UInt16(val))) = operand {
                    self.bytecode.extend_from_slice(&val.to_le_bytes());
                } else {
                    return Err(Error::WrongOperandType {
                        expected: "UInt16".to_string(),
                    });
                }
            }
            OperandType::Int32 => {
                if let Some(Operand::Immediate(Immediate::Int32(val))) = operand {
                    self.bytecode.extend_from_slice(&val.to_le_bytes());
                } else {
                    return Err(Error::WrongOperandType {
                        expected: "Int32".to_string(),
                    });
                }
            }
            OperandType::UInt32 => {
                if let Some(Operand::Immediate(Immediate::UInt32(val))) = operand {
                    self.bytecode.extend_from_slice(&val.to_le_bytes());
                } else {
                    return Err(Error::WrongOperandType {
                        expected: "UInt32".to_string(),
                    });
                }
            }
            OperandType::Int64 => {
                if let Some(Operand::Immediate(Immediate::Int64(val))) = operand {
                    self.bytecode.extend_from_slice(&val.to_le_bytes());
                } else {
                    return Err(Error::WrongOperandType {
                        expected: "Int64".to_string(),
                    });
                }
            }
            OperandType::UInt64 => {
                if let Some(Operand::Immediate(Immediate::UInt64(val))) = operand {
                    self.bytecode.extend_from_slice(&val.to_le_bytes());
                } else {
                    return Err(Error::WrongOperandType {
                        expected: "UInt64".to_string(),
                    });
                }
            }
            OperandType::Float32 => {
                if let Some(Operand::Immediate(Immediate::Float32(val))) = operand {
                    self.bytecode.extend_from_slice(&val.to_le_bytes());
                } else {
                    return Err(Error::WrongOperandType {
                        expected: "Float32".to_string(),
                    });
                }
            }
            OperandType::Float64 => {
                if let Some(Operand::Immediate(Immediate::Float64(val))) = operand {
                    self.bytecode.extend_from_slice(&val.to_le_bytes());
                } else {
                    return Err(Error::WrongOperandType {
                        expected: "Float64".to_string(),
                    });
                }
            }
            OperandType::Token => {
                if let Some(Operand::Token(token)) = operand {
                    self.bytecode
                        .extend_from_slice(&token.value().to_le_bytes());
                } else {
                    return Err(Error::WrongOperandType {
                        expected: "Token".to_string(),
                    });
                }
            }
            OperandType::Switch => {
                if let Some(Operand::Switch(targets)) = operand {
                    // Switch format: count (4 bytes) + targets (4 bytes each)
                    let targets_len = u32::try_from(targets.len())
                        .map_err(|_| malformed_error!("Too many switch targets"))?;
                    self.bytecode.extend_from_slice(&targets_len.to_le_bytes());
                    for target in targets {
                        self.bytecode.extend_from_slice(&target.to_le_bytes());
                    }
                } else {
                    return Err(Error::WrongOperandType {
                        expected: "Switch".to_string(),
                    });
                }
            }
        }
        Ok(())
    }

    /// Write a branch offset at the specified fixup position.
    ///
    /// This internal method writes the calculated branch offset into the bytecode
    /// at the position specified by the fixup, using the appropriate byte size.
    ///
    /// # Errors
    ///
    /// Returns [`crate::Error::InvalidBranch`] if the offset exceeds the range for the
    /// instruction's offset size (1, 2, or 4 bytes) or if the offset size is invalid.
    fn write_branch_offset(&mut self, offset: i32, fixup: &LabelFixup) -> Result<()> {
        match fixup.offset_size {
            1 => {
                if offset < i32::from(i8::MIN) || offset > i32::from(i8::MAX) {
                    return Err(Error::InvalidBranch(format!(
                        "offset {offset} out of range for 1-byte instruction"
                    )));
                }
                let offset_i8 = i8::try_from(offset)
                    .map_err(|_| malformed_error!("Branch offset exceeds i8 range"))?;
                self.bytecode[fixup.fixup_position] = offset_i8.to_le_bytes()[0];
            }
            2 => {
                if offset < i32::from(i16::MIN) || offset > i32::from(i16::MAX) {
                    return Err(Error::InvalidBranch(format!(
                        "offset {offset} out of range for 2-byte instruction"
                    )));
                }
                let offset_i16 = i16::try_from(offset)
                    .map_err(|_| malformed_error!("Branch offset exceeds i16 range"))?;
                let bytes = offset_i16.to_le_bytes();
                self.bytecode[fixup.fixup_position..fixup.fixup_position + 2]
                    .copy_from_slice(&bytes);
            }
            4 => {
                let bytes = offset.to_le_bytes();
                self.bytecode[fixup.fixup_position..fixup.fixup_position + 4]
                    .copy_from_slice(&bytes);
            }
            _ => {
                return Err(Error::InvalidBranch(format!(
                    "invalid offset size: {} bytes",
                    fixup.offset_size
                )))
            }
        }
        Ok(())
    }

    /// Update stack depth tracking based on instruction stack behavior.
    ///
    /// This internal method applies the stack effects of an instruction and validates
    /// that stack underflow doesn't occur.
    ///
    /// # Parameters
    ///
    /// * `pops` - Number of items the instruction pops from the stack
    /// * `pushes` - Number of items the instruction pushes onto the stack
    ///
    /// # Errors
    ///
    /// Returns an error if stack underflow would occur (negative stack depth).
    fn update_stack_depth(&mut self, pops: u8, pushes: u8) -> Result<()> {
        // Apply stack effect
        let net_effect = i16::from(pushes) - i16::from(pops);
        self.current_stack_depth += net_effect;

        // Check for stack underflow - but only in reachable code.
        // In unreachable code, the stack depth is meaningless, so we don't error.
        // We still track it for when code becomes reachable again via a label.
        if self.current_stack_depth < 0 && !self.unreachable {
            return Err(malformed_error!(
                "Stack underflow: depth became {} after instruction with {} pops, {} pushes",
                self.current_stack_depth,
                pops,
                pushes
            ));
        }

        // Clamp negative depth to 0 to prevent cascading issues
        if self.current_stack_depth < 0 {
            self.current_stack_depth = 0;
        }

        // Update maximum stack depth
        let current_depth_u16 = u16::try_from(self.current_stack_depth)
            .map_err(|_| malformed_error!("Stack depth exceeds u16 range"))?;
        self.max_stack_depth = self.max_stack_depth.max(current_depth_u16);

        Ok(())
    }

    /// Get the current maximum stack depth without finalizing the encoder.
    ///
    /// This method allows checking the maximum stack depth that has been reached
    /// so far during encoding without consuming the encoder.
    ///
    /// # Returns
    ///
    /// The maximum stack depth reached so far during instruction encoding.
    #[must_use]
    pub fn max_stack_depth(&self) -> u16 {
        self.max_stack_depth
    }

    /// Get the current stack depth without finalizing the encoder.
    ///
    /// This method returns the current number of items on the evaluation stack.
    /// Useful for debugging or validation during encoding.
    ///
    /// # Returns
    ///
    /// The current stack depth (number of items on evaluation stack).
    #[must_use]
    pub fn current_stack_depth(&self) -> i16 {
        self.current_stack_depth
    }

    /// Get the position of a defined label.
    ///
    /// This method allows accessing label positions before finalization,
    /// which is useful for exception handler offset calculation.
    ///
    /// # Parameters
    ///
    /// * `label_name` - The name of the label to look up
    ///
    /// # Returns
    ///
    /// The byte position of the label if it exists, otherwise None.
    #[must_use]
    pub fn get_label_position(&self, label_name: &str) -> Option<u32> {
        self.labels.get(label_name).copied()
    }

    /// Records the expected stack depth at a branch target label.
    ///
    /// When a branch instruction is emitted, the current stack depth (after popping
    /// any condition) is recorded as the expected depth at the target label. When
    /// the label is defined, we validate that the current depth matches.
    ///
    /// # Parameters
    ///
    /// * `label` - The target label name
    ///
    /// # Errors
    ///
    /// Returns an error if the label was previously recorded with a different depth,
    /// indicating inconsistent stack depths across control flow paths.
    fn record_label_stack_depth(&mut self, label: &str) -> Result<()> {
        // In unreachable code, don't record or validate stack depths.
        // The current_stack_depth is meaningless since there's no execution path.
        // The first reachable branch to this label will set the correct depth.
        if self.unreachable {
            return Ok(());
        }

        if let Some(&expected) = self.label_stack_depths.get(label) {
            if self.current_stack_depth != expected {
                return Err(malformed_error!(
                    "Stack depth mismatch for branch to '{}': expected {}, but branch has {}",
                    label,
                    expected,
                    self.current_stack_depth
                ));
            }
        } else {
            self.label_stack_depths
                .insert(label.to_string(), self.current_stack_depth);
        }
        Ok(())
    }

    /// Sets the expected stack depth at a label.
    ///
    /// This is used to explicitly set the expected depth for labels that may be
    /// reached via fall-through or other non-branch control flow (e.g., exception
    /// handlers). Unlike `record_label_stack_depth`, this does not validate - it
    /// just sets the expectation.
    ///
    /// # Parameters
    ///
    /// * `label` - The label name
    /// * `depth` - The expected stack depth at this label
    pub fn set_label_stack_depth(&mut self, label: &str, depth: i16) {
        self.label_stack_depths.insert(label.to_string(), depth);
    }

    /// Sets the current stack depth directly.
    ///
    /// This is used at control flow boundaries where the stack depth is known
    /// (e.g., after exception handlers where stack is cleared, at method entry).
    ///
    /// # Parameters
    ///
    /// * `depth` - The new stack depth
    pub fn set_stack_depth(&mut self, depth: i16) {
        self.current_stack_depth = depth;
        if depth >= 0 {
            self.max_stack_depth = self.max_stack_depth.max(depth.cast_unsigned());
        }
    }
}

impl Default for InstructionEncoder {
    fn default() -> Self {
        Self::new()
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::assembly::{Immediate, Operand};

    #[test]
    fn test_encoder_creation() {
        let encoder = InstructionEncoder::new();
        assert!(encoder.bytecode.is_empty());
        assert!(encoder.labels.is_empty());
        assert!(encoder.fixups.is_empty());
    }

    #[test]
    fn test_simple_instruction_encoding() -> Result<()> {
        let mut encoder = InstructionEncoder::new();

        encoder.emit_instruction("nop", None)?;
        encoder.emit_instruction("ret", None)?;

        let (bytecode, _max_stack, _) = encoder.finalize()?;
        assert_eq!(bytecode, vec![0x00, 0x2A]); // nop = 0x00, ret = 0x2A

        Ok(())
    }

    #[test]
    fn test_instruction_with_operands() -> Result<()> {
        let mut encoder = InstructionEncoder::new();

        // ldarg.s uses UInt8 for argument index (0-255 range, no sign needed)
        encoder.emit_instruction("ldarg.s", Some(Operand::Immediate(Immediate::UInt8(1))))?;
        // ldc.i4.s uses Int8 for the signed immediate value
        encoder.emit_instruction("ldc.i4.s", Some(Operand::Immediate(Immediate::Int8(42))))?;

        let (bytecode, _max_stack, _) = encoder.finalize()?;
        // ldarg.s = 0x0E, ldarg index = 1, ldc.i4.s = 0x1F, immediate = 42
        assert_eq!(bytecode, vec![0x0E, 0x01, 0x1F, 42]);

        Ok(())
    }

    #[test]
    fn test_label_resolution() -> Result<()> {
        let mut encoder = InstructionEncoder::new();

        encoder.emit_instruction("nop", None)?; // 0x00
        encoder.emit_branch("br.s", "target")?; // 0x2B + offset
        encoder.emit_instruction("nop", None)?; // 0x00
        encoder.define_label("target")?;
        encoder.emit_instruction("ret", None)?; // 0x2A

        let (bytecode, _max_stack, _) = encoder.finalize()?;
        // br.s offset should be 1 (skip the nop instruction)
        assert_eq!(bytecode, vec![0x00, 0x2B, 0x01, 0x00, 0x2A]);

        Ok(())
    }

    #[test]
    fn test_invalid_mnemonic() {
        let mut encoder = InstructionEncoder::new();
        let result = encoder.emit_instruction("invalid_instruction", None);
        assert!(result.is_err());
    }

    #[test]
    fn test_wrong_operand_type() {
        let mut encoder = InstructionEncoder::new();
        // ldarg.s expects Int8, but we provide UInt32
        let result =
            encoder.emit_instruction("ldarg.s", Some(Operand::Immediate(Immediate::UInt32(1))));
        assert!(result.is_err());
    }

    #[test]
    fn test_undefined_label() {
        let mut encoder = InstructionEncoder::new();
        encoder.emit_branch("br.s", "undefined_label").unwrap();
        let result = encoder.finalize();
        assert!(result.is_err());
    }

    #[test]
    fn test_duplicate_label() -> Result<()> {
        let mut encoder = InstructionEncoder::new();
        encoder.define_label("test_label")?;
        let result = encoder.define_label("test_label");
        assert!(result.is_err());
        Ok(())
    }

    #[test]
    fn test_reverse_lookup_table_completeness() {
        // Verify that our reverse lookup table contains all non-empty instructions
        let mut instruction_count = 0;

        // Count single-byte instructions
        for instr in INSTRUCTIONS.iter() {
            if !instr.instr.is_empty() {
                instruction_count += 1;
                assert!(get_mnemonic_lookup().contains_key(instr.instr));
            }
        }

        // Count extended instructions
        for instr in INSTRUCTIONS_FE.iter() {
            if !instr.instr.is_empty() {
                instruction_count += 1;
                assert!(get_mnemonic_lookup().contains_key(instr.instr));
            }
        }

        // Verify the lookup table has exactly the expected number of entries
        assert_eq!(get_mnemonic_lookup().len(), instruction_count);
    }
}