riscv_assembler 0.1.0

A Rust implementation of a RISC-V (RV32IM) assembler with both a library and CLI tool.
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
//! Main assembler code
#![allow(unused_assignments)]
use crate::error::AssemblerError;
use crate::isa::{Instruction, Operand as IsaOperand, Register};
use crate::lexer::tokenize;
use crate::parser::{Directive, Operand as ParsedOperand, ParsedItem, Parser};
use crate::symbol::SymbolTable;

/// Represents the output of the assembler, containing machine code and metadata
pub struct AssemblyOutput {
    /// The machine code as a sequence of words (32-bit values)
    pub code: Vec<u32>,
    /// The final size in bytes
    pub size: usize,
    /// Starting address of the code
    pub start_address: u32,
}

/// Assembles RISC-V assembly code into machine code
pub fn assemble(source: &str) -> Result<AssemblyOutput, AssemblerError> {
    // Step 1: Tokenize the assembly code
    let tokens = tokenize(source)?;

    // Step 2: Parse tokens and build the symbol table
    let mut symbol_table = SymbolTable::new();
    let mut parser = Parser::new(&tokens);
    let parsed_items = parser.parse_all(&mut symbol_table)?;

    // Check for unresolved symbols
    let unresolved = symbol_table.check_unresolved();
    if !unresolved.is_empty() {
        let mut errors = Vec::new();
        for (name, lines) in unresolved {
            errors.push(AssemblerError::SymbolError {
                message: format!("Undefined symbol: {}", name),
                loc: crate::error::SourceLocation {
                    line: *lines.first().unwrap_or(&0),
                    col: 0,
                },
            });
        }
        if errors.len() == 1 {
            return Err(errors.remove(0));
        } else {
            return Err(AssemblerError::MultipleErrors(errors));
        }
    }

    // Step 3: Allocate memory based on parsed items
    let mut memory_map = MemoryMap::new();
    allocate_memory(&parsed_items, &mut memory_map)?;

    // Step 4: Generate machine code
    let output = generate_machine_code(&parsed_items, &symbol_table, &memory_map)?;
    Ok(output)
}

/// Represents a memory location during assembly
#[derive(Debug)]
pub struct MemoryLocation {
    pub address: u32,
    pub size: usize, // in bytes
}

/// Maps parsed items to their allocated memory locations
#[derive(Debug)]
struct MemoryMap {
    locations: Vec<(usize, MemoryLocation)>, // (item_index, location)
    current_address: u32,
}

impl MemoryMap {
    fn new() -> Self {
        MemoryMap {
            locations: Vec::new(),
            current_address: 0,
        }
    }

    ///When we call `map.allocate(0, 4, 4)`, we're saying:
    /// 1. "I need to store item #0"
    /// 2. "It requires 4 bytes of space"
    /// 3. "Its starting address must be divisible by 4"
    fn allocate(&mut self, item_index: usize, size: usize, align: usize) -> u32 {
        // Handle alignment if needed
        if align > 1 {
            let mask = align - 1;
            self.current_address = (self.current_address + mask as u32) & !(mask as u32);
        }

        let address = self.current_address;
        self.locations
            .push((item_index, MemoryLocation { address, size }));

        self.current_address += size as u32;
        address
    }

    fn get_address(&self, item_index: usize) -> Option<u32> {
        self.locations
            .iter()
            .find(|(idx, _)| *idx == item_index)
            .map(|(_, loc)| loc.address)
    }
}

/// First pass: allocate memory for all instructions and directives
fn allocate_memory(
    parsed_items: &[ParsedItem],
    memory_map: &mut MemoryMap,
) -> Result<(), AssemblerError> {
    for (i, item) in parsed_items.iter().enumerate() {
        match item {
            ParsedItem::Instruction(_) => {
                // All RISC-V instructions are 4 bytes
                memory_map.allocate(i, 4, 4); // Align instructions to 4 bytes
            }
            ParsedItem::Directive(dir) => match &dir.directive {
                Directive::Byte(_) => {
                    memory_map.allocate(i, 1, 1);
                }
                Directive::Half(_) => {
                    memory_map.allocate(i, 2, 2);
                }
                Directive::Word(_) => {
                    memory_map.allocate(i, 4, 4);
                }
                Directive::Asciz(s) => {
                    memory_map.allocate(i, s.len() + 1, 1); // +1 for null terminator
                }
                Directive::Align(n) => {
                    // Align to 2^n boundary
                    let alignment = 1 << *n;
                    memory_map.allocate(i, 0, alignment as usize); // Size 0 since we're just aligning
                }
                Directive::Space(n) | Directive::Zero(n) => {
                    memory_map.allocate(i, *n as usize, 1);
                }
                Directive::Org(addr) => {
                    // Set the current address explicitly
                    memory_map.current_address = *addr as u32;
                }
                // Other directives don't consume memory
                _ => {}
            },
            // Labels and empty lines don't consume memory
            _ => {}
        }
    }

    Ok(())
}

/// Second pass: generate machine code for all instructions and directives
fn generate_machine_code(
    parsed_items: &[ParsedItem],
    symbol_table: &SymbolTable,
    memory_map: &MemoryMap,
) -> Result<AssemblyOutput, AssemblerError> {
    let mut output_address = 0;
    let start_address = memory_map
        .locations
        .first()
        .map(|(_, loc)| loc.address)
        .unwrap_or(0);

    // Pre-allocate bytes for the entire program
    let total_size = memory_map.current_address as usize;
    let mut bytes = vec![0u8; total_size];

    for (i, item) in parsed_items.iter().enumerate() {
        if let Some(address) = memory_map.get_address(i) {
            output_address = address;

            match item {
                ParsedItem::Instruction(instr) => {
                    // Convert parsed instruction to ISA instruction
                    let isa_instr = convert_to_isa_instruction(instr, symbol_table)?;

                    // Encode the instruction
                    let loc = crate::error::SourceLocation {
                        line: instr.line_number,
                        col: instr.column,
                    };
                    let encoded = isa_instr.encode(symbol_table, output_address, &loc)?;

                    // Write to the output buffer
                    let offset = output_address as usize;
                    bytes[offset..offset + 4].copy_from_slice(&encoded.to_le_bytes());
                }
                ParsedItem::Directive(dir) => match &dir.directive {
                    Directive::Byte(val) => {
                        let offset = output_address as usize;
                        bytes[offset] = *val as u8;
                    }
                    Directive::Half(val) => {
                        let offset = output_address as usize;
                        bytes[offset..offset + 2].copy_from_slice(&(*val as u16).to_le_bytes());
                    }
                    Directive::Word(val) => {
                        let offset = output_address as usize;
                        bytes[offset..offset + 4].copy_from_slice(&(*val as u32).to_le_bytes());
                    }
                    Directive::Asciz(s) => {
                        let offset = output_address as usize;
                        // Copy the string bytes plus null terminator
                        for (i, b) in s.bytes().enumerate() {
                            bytes[offset + i] = b;
                        }
                        // Null terminator
                        bytes[offset + s.len()] = 0;
                    }
                    Directive::Space(n) => {
                        // Space already filled with zeros by our pre-allocation
                        let offset = output_address as usize;
                        for i in 0..*n as usize {
                            bytes[offset + i] = 0;
                        }
                    }
                    Directive::Zero(n) => {
                        // Same as Space, already zeroed
                        let offset = output_address as usize;
                        for i in 0..*n as usize {
                            bytes[offset + i] = 0;
                        }
                    }
                    // Other directives don't generate code
                    _ => {}
                },
                _ => {} // Labels and empty lines don't generate code
            }
        }
    }

    // Convert bytes to 32-bit words for the output
    let word_count = (bytes.len() + 3) / 4; // Ceiling division to include partial final word
    let mut words = Vec::with_capacity(word_count);

    for chunk in bytes.chunks(4) {
        let mut word = 0u32;
        for (i, &byte) in chunk.iter().enumerate() {
            word |= (byte as u32) << (i * 8);
        }
        words.push(word);
    }

    Ok(AssemblyOutput {
        code: words,
        size: bytes.len(),
        start_address,
    })
}

/// Convert a parsed instruction to an ISA instruction for encoding
fn convert_to_isa_instruction(
    instr: &crate::parser::ParsedInstruction,
    symbol_table: &SymbolTable,
) -> Result<Instruction, AssemblerError> {
    use crate::isa::Instruction::*;

    // Helper to convert a ParsedOperand to an IsaOperand
    let convert_operand = |op: &ParsedOperand| -> Result<IsaOperand, AssemblerError> {
        match op {
            ParsedOperand::Register(r) => Ok(IsaOperand::Register(Register::new(*r).unwrap())),
            ParsedOperand::Immediate(val) => Ok(IsaOperand::Immediate(*val)),
            ParsedOperand::Symbol(name) => {
                // Lookup the symbol
                if let Some(sym) = symbol_table.lookup(name) {
                    Ok(IsaOperand::Immediate(sym.address() as i64))
                } else {
                    Err(AssemblerError::SymbolError {
                        message: format!("Undefined symbol: {}", name),
                        loc: crate::error::SourceLocation {
                            line: instr.line_number,
                            col: instr.column,
                        },
                    })
                }
            }
            ParsedOperand::Memory { offset, base } => {
                // Memory operands typically need to be handled specially based on the instruction
                // but for now we'll just note this is incomplete
                // We would need to get the content of the register at the base and add it to the offset. for now I would advice this instruction format should not be used
                Ok(IsaOperand::ImmediateAndRegister(
                    *offset,
                    Register::new(*base).unwrap(),
                ))
            }
        }
    };

    // Match based on mnemonic and operands
    match instr.mnemonic.as_str() {
        // R-type instructions
        "add" if instr.operands.len() == 3 => {
            let rd = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };
            let rs1 = match convert_operand(&instr.operands[1])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 1, "register")),
            };
            let rs2 = match convert_operand(&instr.operands[2])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 2, "register")),
            };
            Ok(Add { rd, rs1, rs2 })
        }

        "sub" if instr.operands.len() == 3 => {
            let rd = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };
            let rs1 = match convert_operand(&instr.operands[1])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 1, "register")),
            };
            let rs2 = match convert_operand(&instr.operands[2])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 2, "register")),
            };
            Ok(Sub { rd, rs1, rs2 })
        }

        "xor" if instr.operands.len() == 3 => {
            let rd = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };
            let rs1 = match convert_operand(&instr.operands[1])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 1, "register")),
            };
            let rs2 = match convert_operand(&instr.operands[2])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 2, "register")),
            };
            Ok(Xor { rd, rs1, rs2 })
        }

        "or" if instr.operands.len() == 3 => {
            let rd = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };
            let rs1 = match convert_operand(&instr.operands[1])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 1, "register")),
            };
            let rs2 = match convert_operand(&instr.operands[2])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 2, "register")),
            };
            Ok(Or { rd, rs1, rs2 })
        }

        "and" if instr.operands.len() == 3 => {
            let rd = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };
            let rs1 = match convert_operand(&instr.operands[1])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 1, "register")),
            };
            let rs2 = match convert_operand(&instr.operands[2])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 2, "register")),
            };
            Ok(And { rd, rs1, rs2 })
        }

        "sll" if instr.operands.len() == 3 => {
            let rd = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };
            let rs1 = match convert_operand(&instr.operands[1])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 1, "register")),
            };
            let rs2 = match convert_operand(&instr.operands[2])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 2, "register")),
            };
            Ok(Sll { rd, rs1, rs2 })
        }

        "srl" if instr.operands.len() == 3 => {
            let rd = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };
            let rs1 = match convert_operand(&instr.operands[1])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 1, "register")),
            };
            let rs2 = match convert_operand(&instr.operands[2])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 2, "register")),
            };
            Ok(Srl { rd, rs1, rs2 })
        }

        "sra" if instr.operands.len() == 3 => {
            let rd = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };
            let rs1 = match convert_operand(&instr.operands[1])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 1, "register")),
            };
            let rs2 = match convert_operand(&instr.operands[2])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 2, "register")),
            };
            Ok(Sra { rd, rs1, rs2 })
        }

        "slt" if instr.operands.len() == 3 => {
            let rd = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };
            let rs1 = match convert_operand(&instr.operands[1])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 1, "register")),
            };
            let rs2 = match convert_operand(&instr.operands[2])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 2, "register")),
            };
            Ok(Slt { rd, rs1, rs2 })
        }

        "sltu" if instr.operands.len() == 3 => {
            let rd = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };
            let rs1 = match convert_operand(&instr.operands[1])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 1, "register")),
            };
            let rs2 = match convert_operand(&instr.operands[2])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 2, "register")),
            };
            Ok(Sltu { rd, rs1, rs2 })
        }

        // M-extension R-type instructions
        "mul" if instr.operands.len() == 3 => {
            let rd = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };
            let rs1 = match convert_operand(&instr.operands[1])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 1, "register")),
            };
            let rs2 = match convert_operand(&instr.operands[2])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 2, "register")),
            };
            Ok(Mul { rd, rs1, rs2 })
        }

        "mulh" if instr.operands.len() == 3 => {
            let rd = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };
            let rs1 = match convert_operand(&instr.operands[1])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 1, "register")),
            };
            let rs2 = match convert_operand(&instr.operands[2])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 2, "register")),
            };
            Ok(Mulh { rd, rs1, rs2 })
        }

        "mulhsu" if instr.operands.len() == 3 => {
            let rd = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };
            let rs1 = match convert_operand(&instr.operands[1])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 1, "register")),
            };
            let rs2 = match convert_operand(&instr.operands[2])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 2, "register")),
            };
            Ok(Mulhsu { rd, rs1, rs2 })
        }

        "mulhu" if instr.operands.len() == 3 => {
            let rd = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };
            let rs1 = match convert_operand(&instr.operands[1])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 1, "register")),
            };
            let rs2 = match convert_operand(&instr.operands[2])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 2, "register")),
            };
            Ok(Mulhu { rd, rs1, rs2 })
        }

        "div" if instr.operands.len() == 3 => {
            let rd = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };
            let rs1 = match convert_operand(&instr.operands[1])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 1, "register")),
            };
            let rs2 = match convert_operand(&instr.operands[2])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 2, "register")),
            };
            Ok(Div { rd, rs1, rs2 })
        }

        "divu" if instr.operands.len() == 3 => {
            let rd = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };
            let rs1 = match convert_operand(&instr.operands[1])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 1, "register")),
            };
            let rs2 = match convert_operand(&instr.operands[2])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 2, "register")),
            };
            Ok(Divu { rd, rs1, rs2 })
        }

        "rem" if instr.operands.len() == 3 => {
            let rd = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };
            let rs1 = match convert_operand(&instr.operands[1])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 1, "register")),
            };
            let rs2 = match convert_operand(&instr.operands[2])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 2, "register")),
            };
            Ok(Rem { rd, rs1, rs2 })
        }

        "remu" if instr.operands.len() == 3 => {
            let rd = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };
            let rs1 = match convert_operand(&instr.operands[1])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 1, "register")),
            };
            let rs2 = match convert_operand(&instr.operands[2])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 2, "register")),
            };
            Ok(Remu { rd, rs1, rs2 })
        }

        // I-type instructions
        "addi" if instr.operands.len() == 3 => {
            let rd = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };
            let rs1 = match convert_operand(&instr.operands[1])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 1, "register")),
            };
            let imm = convert_operand(&instr.operands[2])?;
            Ok(Addi { rd, rs1, imm })
        }

        "xori" if instr.operands.len() == 3 => {
            let rd = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };
            let rs1 = match convert_operand(&instr.operands[1])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 1, "register")),
            };
            let imm = convert_operand(&instr.operands[2])?;
            Ok(Xori { rd, rs1, imm })
        }

        "ori" if instr.operands.len() == 3 => {
            let rd = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };
            let rs1 = match convert_operand(&instr.operands[1])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 1, "register")),
            };
            let imm = convert_operand(&instr.operands[2])?;
            Ok(Ori { rd, rs1, imm })
        }

        "andi" if instr.operands.len() == 3 => {
            let rd = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };
            let rs1 = match convert_operand(&instr.operands[1])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 1, "register")),
            };
            let imm = convert_operand(&instr.operands[2])?;
            Ok(Andi { rd, rs1, imm })
        }

        "slli" if instr.operands.len() == 3 => {
            let rd = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };
            let rs1 = match convert_operand(&instr.operands[1])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 1, "register")),
            };
            let shamt = convert_operand(&instr.operands[2])?;
            Ok(Slli { rd, rs1, shamt })
        }

        "srli" if instr.operands.len() == 3 => {
            let rd = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };
            let rs1 = match convert_operand(&instr.operands[1])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 1, "register")),
            };
            let shamt = convert_operand(&instr.operands[2])?;
            Ok(Srli { rd, rs1, shamt })
        }

        "srai" if instr.operands.len() == 3 => {
            let rd = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };
            let rs1 = match convert_operand(&instr.operands[1])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 1, "register")),
            };
            let shamt = convert_operand(&instr.operands[2])?;
            Ok(Srai { rd, rs1, shamt })
        }

        "slti" if instr.operands.len() == 3 => {
            let rd = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };
            let rs1 = match convert_operand(&instr.operands[1])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 1, "register")),
            };
            let imm = convert_operand(&instr.operands[2])?;
            Ok(Slti { rd, rs1, imm })
        }

        "sltiu" if instr.operands.len() == 3 => {
            let rd = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };
            let rs1 = match convert_operand(&instr.operands[1])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 1, "register")),
            };
            let imm = convert_operand(&instr.operands[2])?;
            Ok(Sltiu { rd, rs1, imm })
        }

        // Load instructions
        "lb" if instr.operands.len() == 2 => {
            let rd = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };

            match &instr.operands[1] {
                ParsedOperand::Memory { offset, base } => {
                    let rs1 = Register::new(*base).unwrap();
                    Ok(Lb {
                        rd,
                        rs1,
                        imm: IsaOperand::Immediate(*offset),
                    })
                }
                _ => Err(invalid_operand_error(instr, 1, "memory reference")),
            }
        }

        "lh" if instr.operands.len() == 2 => {
            let rd = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };

            match &instr.operands[1] {
                ParsedOperand::Memory { offset, base } => {
                    let rs1 = Register::new(*base).unwrap();
                    Ok(Lh {
                        rd,
                        rs1,
                        imm: IsaOperand::Immediate(*offset),
                    })
                }
                _ => Err(invalid_operand_error(instr, 1, "memory reference")),
            }
        }
        "lw" if instr.operands.len() == 2 => {
            let rd = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };

            // Handle memory operand
            match &instr.operands[1] {
                ParsedOperand::Memory { offset, base } => {
                    let rs1 = Register::new(*base).unwrap();
                    Ok(Lw {
                        rd,
                        rs1,
                        imm: IsaOperand::Immediate(*offset),
                    })
                }
                _ => Err(invalid_operand_error(instr, 1, "memory reference")),
            }
        }

        "lbu" if instr.operands.len() == 2 => {
            let rd = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };

            match &instr.operands[1] {
                ParsedOperand::Memory { offset, base } => {
                    let rs1 = Register::new(*base).unwrap();
                    Ok(Lbu {
                        rd,
                        rs1,
                        imm: IsaOperand::Immediate(*offset),
                    })
                }
                _ => Err(invalid_operand_error(instr, 1, "memory reference")),
            }
        }

        "lhu" if instr.operands.len() == 2 => {
            let rd = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };

            match &instr.operands[1] {
                ParsedOperand::Memory { offset, base } => {
                    let rs1 = Register::new(*base).unwrap();
                    Ok(Lhu {
                        rd,
                        rs1,
                        imm: IsaOperand::Immediate(*offset),
                    })
                }
                _ => Err(invalid_operand_error(instr, 1, "memory reference")),
            }
        }

        // Store instructions
        "sb" if instr.operands.len() == 2 => {
            let rs2 = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };

            match &instr.operands[1] {
                ParsedOperand::Memory { offset, base } => {
                    let rs1 = Register::new(*base).unwrap();
                    Ok(Sb {
                        rs1,
                        rs2,
                        imm: IsaOperand::Immediate(*offset),
                    })
                }
                _ => Err(invalid_operand_error(instr, 1, "memory reference")),
            }
        }

        "sh" if instr.operands.len() == 2 => {
            let rs2 = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };

            match &instr.operands[1] {
                ParsedOperand::Memory { offset, base } => {
                    let rs1 = Register::new(*base).unwrap();
                    Ok(Sh {
                        rs1,
                        rs2,
                        imm: IsaOperand::Immediate(*offset),
                    })
                }
                _ => Err(invalid_operand_error(instr, 1, "memory reference")),
            }
        }

        "sw" if instr.operands.len() == 2 => {
            let rs2 = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };

            // Handle memory operand
            match &instr.operands[1] {
                ParsedOperand::Memory { offset, base } => {
                    let rs1 = Register::new(*base).unwrap();
                    Ok(Sw {
                        rs1,
                        rs2,
                        imm: IsaOperand::Immediate(*offset),
                    })
                }
                _ => Err(invalid_operand_error(instr, 1, "memory reference")),
            }
        }

        // Branch instructions
        "beq" if instr.operands.len() == 3 => {
            let rs1 = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };
            let rs2 = match convert_operand(&instr.operands[1])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 1, "register")),
            };
            let target = convert_operand(&instr.operands[2])?;
            Ok(Beq { rs1, rs2, target })
        }

        "bne" if instr.operands.len() == 3 => {
            let rs1 = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };
            let rs2 = match convert_operand(&instr.operands[1])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 1, "register")),
            };
            let target = convert_operand(&instr.operands[2])?;
            Ok(Bne { rs1, rs2, target })
        }

        "blt" if instr.operands.len() == 3 => {
            let rs1 = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };
            let rs2 = match convert_operand(&instr.operands[1])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 1, "register")),
            };
            let target = convert_operand(&instr.operands[2])?;
            Ok(Blt { rs1, rs2, target })
        }

        "bge" if instr.operands.len() == 3 => {
            let rs1 = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };
            let rs2 = match convert_operand(&instr.operands[1])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 1, "register")),
            };
            let target = convert_operand(&instr.operands[2])?;
            Ok(Bge { rs1, rs2, target })
        }

        "bltu" if instr.operands.len() == 3 => {
            let rs1 = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };
            let rs2 = match convert_operand(&instr.operands[1])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 1, "register")),
            };
            let target = convert_operand(&instr.operands[2])?;
            Ok(Bltu { rs1, rs2, target })
        }

        "bgeu" if instr.operands.len() == 3 => {
            let rs1 = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };
            let rs2 = match convert_operand(&instr.operands[1])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 1, "register")),
            };
            let target = convert_operand(&instr.operands[2])?;
            Ok(Bgeu { rs1, rs2, target })
        }

        // Jump instructions
        "jal" if instr.operands.len() == 2 => {
            let rd = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };
            let target = convert_operand(&instr.operands[1])?;
            Ok(Jal { rd, target })
        }

        // Special case for pseudo-instruction 'j label' -> 'jal x0, label'
        // TODO: Propagate this feature to the lexer
        "j" if instr.operands.len() == 1 => {
            let target = convert_operand(&instr.operands[0])?;
            Ok(Jal {
                rd: Register::new(0).unwrap(),
                target,
            })
        }

        "jalr" if instr.operands.len() == 3 => {
            let rd = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };
            let rs1 = match convert_operand(&instr.operands[1])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 1, "register")),
            };
            let imm = convert_operand(&instr.operands[2])?;
            Ok(Jalr { rd, rs1, imm })
        }

        // Special case for pseudo-instruction 'ret' -> 'jalr x0, ra, 0'
        // TODO: Propagate this feature to the lexer
        "ret" if instr.operands.is_empty() => {
            Ok(Jalr {
                rd: Register::new(0).unwrap(),
                rs1: Register::new(1).unwrap(), // ra is x1
                imm: IsaOperand::Immediate(0),
            })
        }

        // U-type instructions
        "lui" if instr.operands.len() == 2 => {
            let rd = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };
            let imm = convert_operand(&instr.operands[1])?;
            Ok(Lui { rd, imm })
        }

        "auipc" if instr.operands.len() == 2 => {
            let rd = match convert_operand(&instr.operands[0])? {
                IsaOperand::Register(r) => r,
                _ => return Err(invalid_operand_error(instr, 0, "register")),
            };
            let imm = convert_operand(&instr.operands[1])?;
            Ok(Auipc { rd, imm })
        }

        // Special instruction
        "ecall" if instr.operands.is_empty() => Ok(Ecall),

        // Add more instructions as needed...
        _ => Err(AssemblerError::EncodingError {
            message: format!("Unsupported instruction: {}", instr.mnemonic),
            loc: crate::error::SourceLocation {
                line: instr.line_number,
                col: instr.column,
            },
        }),
    }
}

fn invalid_operand_error(
    instr: &crate::parser::ParsedInstruction,
    operand_idx: usize,
    expected: &str,
) -> AssemblerError {
    AssemblerError::EncodingError {
        message: format!(
            "Invalid operand for {}: expected {}\n OperandIndex: {}",
            instr.mnemonic, expected, operand_idx
        ),
        loc: crate::error::SourceLocation {
            line: instr.line_number,
            col: instr.column,
        },
    }
}

#[cfg(test)]
mod tests {
    use crate::parser::{ParsedDirective, ParsedInstruction, ParsedLabel};

    use super::*;

    #[test]
    fn test_simple_assembly() {
        let source = r#"
        .text
    start:
        addi x1, x0, 1    # 4 bytes
        addi x2, x0, 2    # 4 bytes
        .align 3          # Align to 8 bytes (might add padding)
    aligned:
        addi x3, x0, 3    # 4 bytes
        .word 0xdeadbeef  # 4 bytes
        .byte 0x42        # 1 byte
        "#;

        let result = assemble(source).unwrap();

        // We should have at least 4 words (3 instructions + 1 data word)
        assert!(result.code.len() >= 4);

        // Verify the first instruction (addi x1, x0, 1)
        // 0x00100093 = addi x1, x0, 1
        assert_eq!(result.code[0], 0x00100093);

        // Verify the second instruction (addi x2, x0, 2)
        // 0x00200113 = addi x2, x0, 2
        assert_eq!(result.code[1], 0x00200113);

        // The alignment might add padding

        // Verify the third instruction (addi x3, x0, 3)
        // This might not be at index 2 if there's padding from .align
        // We'd need to look up its address to be sure

        // Verify the .word directive
        // Check if 0xdeadbeef is in the output
        assert!(result.code.contains(&0xdeadbeef));

        // Verify the .byte directive
        // The byte 0x42 is somewhere in the last word
        // We would need to check the exact position based on alignment
    }

    #[test]
    fn test_memory_map() {
        let mut map = MemoryMap::new();

        // Test initial state
        assert_eq!(map.current_address, 0);
        assert_eq!(map.locations.len(), 0);

        // Test basic allocation
        let addr1 = map.allocate(0, 4, 4); // Allocate 4 bytes with 4-byte alignment
        assert_eq!(addr1, 0);
        assert_eq!(map.current_address, 4);
        assert_eq!(map.locations.len(), 1);

        // Test alignment
        let addr2 = map.allocate(1, 2, 8); // Allocate 2 bytes with 8-byte alignment
        // Current address is 4, aligning to 8 should give 8
        assert_eq!(addr2, 8);
        assert_eq!(map.current_address, 10);

        // Test get_address
        assert_eq!(map.get_address(0), Some(0));
        assert_eq!(map.get_address(1), Some(8));
        assert_eq!(map.get_address(2), None);

        // Test another allocation
        let addr3 = map.allocate(2, 6, 4); // Allocate 6 bytes with 4-byte alignment
        // Current address is 10, aligning to 4 should give 12
        assert_eq!(addr3, 12);
        assert_eq!(map.current_address, 18);
    }

    #[test]
    fn test_convert_to_isa_instruction() {
        let mut symbol_table = SymbolTable::new();
        symbol_table
            .define("loop".to_string(), 0x100, Some(5))
            .unwrap();

        // Test ADD instruction conversion
        let add_instr = ParsedInstruction {
            mnemonic: "add".to_string(),
            operands: vec![
                ParsedOperand::Register(1), // x1
                ParsedOperand::Register(2), // x2
                ParsedOperand::Register(3), // x3
            ],
            address: 0,
            line_number: 1,
            column: 1,
        };

        let result = convert_to_isa_instruction(&add_instr, &symbol_table).unwrap();
        if let crate::isa::Instruction::Add { rd, rs1, rs2 } = result {
            assert_eq!(rd.number(), 1);
            assert_eq!(rs1.number(), 2);
            assert_eq!(rs2.number(), 3);
        } else {
            panic!("Expected Add instruction");
        }

        // Test ADDI instruction with immediate
        let addi_instr = ParsedInstruction {
            mnemonic: "addi".to_string(),
            operands: vec![
                ParsedOperand::Register(5),   // x5
                ParsedOperand::Register(0),   // x0
                ParsedOperand::Immediate(42), // 42
            ],
            address: 0,
            line_number: 2,
            column: 1,
        };

        let result = convert_to_isa_instruction(&addi_instr, &symbol_table).unwrap();
        if let crate::isa::Instruction::Addi { rd, rs1, imm } = result {
            assert_eq!(rd.number(), 5);
            assert_eq!(rs1.number(), 0);
            assert!(matches!(imm, crate::isa::Operand::Immediate(42)));
        } else {
            panic!("Expected Addi instruction");
        }

        // Test LW instruction with memory operand
        let lw_instr = ParsedInstruction {
            mnemonic: "lw".to_string(),
            operands: vec![
                ParsedOperand::Register(10),                  // x10 (a0)
                ParsedOperand::Memory { offset: 8, base: 2 }, // 8(x2) (sp)
            ],
            address: 0,
            line_number: 3,
            column: 1,
        };

        let result = convert_to_isa_instruction(&lw_instr, &symbol_table).unwrap();
        if let crate::isa::Instruction::Lw { rd, rs1, imm } = result {
            assert_eq!(rd.number(), 10);
            assert_eq!(rs1.number(), 2);
            assert!(matches!(imm, crate::isa::Operand::Immediate(8)));
        } else {
            panic!("Expected Lw instruction");
        }

        // Test instruction with symbol reference
        let beq_instr = ParsedInstruction {
            mnemonic: "beq".to_string(),
            operands: vec![
                ParsedOperand::Register(4),           // x4
                ParsedOperand::Register(5),           // x5
                ParsedOperand::Symbol("loop".into()), // loop label
            ],
            address: 0,
            line_number: 4,
            column: 1,
        };

        let result = convert_to_isa_instruction(&beq_instr, &symbol_table).unwrap();
        if let crate::isa::Instruction::Beq { rs1, rs2, target } = result {
            assert_eq!(rs1.number(), 4);
            assert_eq!(rs2.number(), 5);
            assert!(matches!(target, crate::isa::Operand::Immediate(256))); // 0x100
        } else {
            panic!("Expected Beq instruction");
        }
    }

    #[test]
    fn test_allocate_memory() {
        let mut memory_map = MemoryMap::new();

        // Create a list of parsed items
        let parsed_items = vec![
            // An instruction (4 bytes)
            ParsedItem::Instruction(ParsedInstruction {
                mnemonic: "add".to_string(),
                operands: vec![
                    ParsedOperand::Register(1),
                    ParsedOperand::Register(2),
                    ParsedOperand::Register(3),
                ],
                address: 0,
                line_number: 1,
                column: 1,
            }),
            // A label (doesn't consume memory)
            ParsedItem::Label(ParsedLabel {
                name: "label1".to_string(),
                address: 4,
                line_number: 2,
                column: 1,
            }),
            // A byte directive (1 byte)
            ParsedItem::Directive(ParsedDirective {
                directive: Directive::Byte(42),
                address: 4,
                line_number: 3,
                column: 1,
            }),
            // A word directive (4 bytes)
            ParsedItem::Directive(ParsedDirective {
                directive: Directive::Word(0xdeadbeef),
                address: 5,
                line_number: 4,
                column: 1,
            }),
            // An align directive (aligns to 8-byte boundary)
            ParsedItem::Directive(ParsedDirective {
                directive: Directive::Align(3), // 2^3 = 8
                address: 9,
                line_number: 5,
                column: 1,
            }),
            // Another instruction after alignment
            ParsedItem::Instruction(ParsedInstruction {
                mnemonic: "addi".to_string(),
                operands: vec![
                    ParsedOperand::Register(5),
                    ParsedOperand::Register(0),
                    ParsedOperand::Immediate(10),
                ],
                address: 0,
                line_number: 6,
                column: 1,
            }),
        ];

        // Allocate memory for the items
        allocate_memory(&parsed_items, &mut memory_map).unwrap();

        // Verify memory allocations
        assert_eq!(memory_map.get_address(0), Some(0)); // First instruction at 0
        assert_eq!(memory_map.get_address(2), Some(4)); // Byte directive at 4
        assert_eq!(memory_map.get_address(3), Some(8)); // Word directive at 5
        assert_eq!(memory_map.get_address(4), Some(16)); // Align directive at 9

        // The last instruction should be at address 16 (after alignment to 8-byte boundary)
        // 9 -> 16 (aligned to 8) -> 16 + 4 = 20 (end)
        assert_eq!(memory_map.get_address(5), Some(16));

        // Final address should be 20
        assert_eq!(memory_map.current_address, 20);
    }

    #[test]
    fn test_generate_machine_code() {
        let mut symbol_table = SymbolTable::new();
        symbol_table
            .define("start".to_string(), 0, Some(1))
            .unwrap();

        let mut memory_map = MemoryMap::new();

        let parsed_items = vec![
            // Label
            ParsedItem::Label(ParsedLabel {
                name: "start".to_string(),
                address: 0,
                line_number: 1,
                column: 1,
            }),
            // addi x1, x0, 1
            ParsedItem::Instruction(ParsedInstruction {
                mnemonic: "addi".to_string(),
                operands: vec![
                    ParsedOperand::Register(1),
                    ParsedOperand::Register(0),
                    ParsedOperand::Immediate(1),
                ],
                address: 0,
                line_number: 2,
                column: 1,
            }),
            // .word 0xdeadbeef
            ParsedItem::Directive(ParsedDirective {
                directive: Directive::Word(0xdeadbeef),
                address: 4,
                line_number: 3,
                column: 1,
            }),
        ];

        // Allocate memory
        allocate_memory(&parsed_items, &mut memory_map).unwrap();

        // Generate machine code
        let output = generate_machine_code(&parsed_items, &symbol_table, &memory_map).unwrap();

        // Check the output
        assert_eq!(output.start_address, 0);
        assert_eq!(output.size, 8); // 4 bytes instruction + 4 bytes word
        assert_eq!(output.code.len(), 2);

        // Check that first word is the ADDI instruction
        // addi x1, x0, 1 => 0x00100093
        assert_eq!(output.code[0], 0x00100093);

        // Check that second word is 0xdeadbeef
        assert_eq!(output.code[1], 0xdeadbeef);
    }

    #[test]
    fn test_generate_machine_code_2() {
        let source = r#"
        .text
        start:
            addi x1, x0, 1    # 4 bytes
            addi x2, x0, 2    # 4 bytes
            .align 3          # Align to 8 bytes (might add padding)
        aligned:
            addi x3, x0, 3    # 4 bytes
            .word 0xdeadbeef  # 4 bytes
            .byte 0x42        # 1 byte
            "#;

        let tokens = tokenize(source).unwrap();
        let mut parser = Parser::new(&tokens);
        let mut symbol_table = SymbolTable::new();

        let parsed_items = parser.parse_all(&mut symbol_table).unwrap();

        let mut memory_map = MemoryMap::new();
        allocate_memory(&parsed_items, &mut memory_map).unwrap();
        // Generate machine code
        let output = generate_machine_code(&parsed_items, &symbol_table, &memory_map).unwrap();

        // Check the output
        assert_eq!(output.start_address, 0);
        assert_eq!(output.size, 17); // 4 bytes instruction + 4 bytes word
        assert_eq!(output.code.len(), 5);

        // Check that first word is the ADDI instruction
        assert_eq!(output.code[0], 1048723);
        assert_eq!(output.code[1], 2097427);
    }

    #[test]
    fn test_generate_machine_code_3() {
        let source = r#"
        .text
        start:
            addi x1, x0, 1    # 4 bytes
            addi x2, x0, 2    # 4 bytes
            .align 3          # Align to 8 bytes (might add padding)
        aligned:
            addi x3, x0, 3    # 4 bytes
            .word 0xdeadbeef  # 4 bytes
            .byte 0x42        # 1 byte
            "#;

        let tokens = tokenize(source).unwrap();
        let mut parser = Parser::new(&tokens);
        let mut symbol_table = SymbolTable::new();

        let parsed_items = parser.parse_all(&mut symbol_table).unwrap();

        let mut memory_map = MemoryMap::new();
        allocate_memory(&parsed_items, &mut memory_map).unwrap();
        // Generate machine code
        let output = generate_machine_code(&parsed_items, &symbol_table, &memory_map).unwrap();

        // Check the output
        assert_eq!(output.start_address, 0);
        assert_eq!(output.size, 17); // 4 bytes instruction + 4 bytes word
        assert_eq!(output.code.len(), 5);

        // Check that first word is the ADDI instruction
        assert_eq!(output.code[0], 1048723);
        assert_eq!(output.code[1], 2097427);
    }

    #[test]
    fn test_assemble_1() {
        let source = r#"
        .text
        start:
            addi x1, x0, 1    # 4 bytes
            addi x2, x0, 2    # 4 bytes
            .align 3          # Align to 8 bytes (might add padding)
        aligned:
            addi x3, x0, 3    # 4 bytes
            .word 0xdeadbeef  # 4 bytes
            .byte 0x42        # 1 byte
            "#;

        // assemble machine code
        let output = assemble(source).unwrap();

        // Check the output
        assert_eq!(output.start_address, 0);
        assert_eq!(output.size, 17); // 4 bytes instruction + 4 bytes word
        assert_eq!(output.code.len(), 5);

        // Check that first word is the ADDI instruction
        assert_eq!(output.code[0], 1048723);
        assert_eq!(output.code[1], 2097427);
    }

    #[test]
    #[ignore = "would be back to this after cli implemenation"]
    fn test_assemble_complete_program() {
        // A simple but complete RISC-V program that:
        // 1. Sets up registers
        // 2. Uses various instruction types
        // 3. Contains labels and branches
        // 4. Uses different directives
        let source = r#"
            # Test program with various RISC-V features

            .text

            # Program entry point
            main:
                # Stack setup
                addi sp, sp, -16       # Allocate stack frame
                sw ra, 12(sp)          # Save return address

                # Initialize registers
                addi a0, zero, 5       # Initialize a0 with 5
                addi a1, zero, 10      # Initialize a1 with 10

                # Test branch
                beq a0, a1, skip       # This branch should not be taken
                add a2, a0, a1         # a2 = a0 + a1 = 15

            skip:
                # Test jump and link
                jal ra, function       # Call function, store return address in ra

                # Cleanup and exit
                lw ra, 12(sp)          # Restore return address
                addi sp, sp, 16        # Deallocate stack frame

                # Test alignment directive
                .align 2               # Align to 4-byte boundary

            function:
                # Function that adds 1 to a0 and returns
                addi a0, a0, 1         # Increment a0
                jalr zero, ra, 0       # Return to caller

            # Data section
            .data
            .align 2
            value:
                .word 0xdeadbeef       # Test word directive
                .byte 0x42             # Test byte directive
        "#;

        // Assemble the program
        let result = assemble(source).expect("Assembly should succeed");

        // Check the basic properties of the output
        assert!(result.code.len() > 0, "Should generate machine code");
        assert_eq!(result.start_address, 0, "Program should start at address 0");

        println!("Generated code: {:?}", result.code);

        // Verify specific instructions in the output

        // addi sp, sp, -16 (first instruction) = 0xFF010113
        assert_eq!(result.code[0], 0xFF010113);

        // sw ra, 12(sp) (second instruction) = 0x00C12623
        assert_eq!(result.code[1], 0x00C12623);

        // addi a0, zero, 5 (third instruction) = 0x00500513
        assert_eq!(result.code[2], 0x00500513);

        // addi a1, zero, 10 (fourth instruction) = 0x00A00593
        assert_eq!(result.code[3], 0x00A00593);

        // We can also verify the total size is reasonable
        assert!(result.size > 40, "Program size should be at least 40 bytes");

        // Verify the size is consistent with the code length * 4
        assert_eq!(
            result.size,
            result.code.len() * 4,
            "Size should match code length * 4 (bytes per word)"
        );

        println!("Generated code: {:?}", result.code);
        println!("Program size: {} bytes", result.size);
    }

    #[test]
    fn test_assemble_with_forward_references() {
        // Test that the assembler correctly handles forward references
        let source = r#"
            # Program using forward references

            .text
            start:
                addi x5, zero, 1       # Set x5 = 1
                beq x5, zero, end      # Forward branch to end (should not be taken)
                jal x1, middle         # Forward jump to middle

            loop:
                addi x5, x5, -1        # Decrement x5
                bge x5, zero, loop     # Loop until x5 < 0
                jal x0, end                  # Jump to end

            middle:
                addi x5, x5, 5         # x5 = x5 + 5 = 6
                jalr zero, x1, 0       # Return to caller

            end:
                addi x10, x5, 0         # Set return value in x10
        "#;

        // Assemble the program
        let result = assemble(source).expect("Assembly should succeed");

        // The program should have at least 7 instructions
        assert!(
            result.code.len() >= 7,
            "Should generate at least 7 instructions"
        );

        // First instruction: addi x5, zero, 1 = 0x00100293
        assert_eq!(result.code[0], 0x00100293);

        println!("Generated code with forward references: {:?}", result.code);
        println!("Program size: {} bytes", result.size);
    }

    #[test]
    #[ignore = "would be back to this after cli implemenation"]
    fn test_assemble_data_directives() {
        // Test that the assembler correctly handles data directives
        let source = r#"
            .data
            values:
                .word 0x12345678       # Test word
                .half 0xABCD           # Test half-word
                .byte 0x42             # Test byte

            .align 3                   # Align to 8-byte boundary
            string:
                .asciz "Hello, RISC-V" # Test string
        "#;

        // Assemble the program
        let result = assemble(source).expect("Assembly should succeed");

        // Verify the first word is our test value
        assert_eq!(result.code[0], 0x12345678);

        // Other data should also be in the output
        // We'd need to examine the exact memory layout to check everything

        println!("Generated data section: {:?}", result.code);
        println!("Data section size: {} bytes", result.size);
    }

    #[test]
    #[ignore = "would be back to this after cli implemenation"]
    fn test_assemble_error_handling() {
        // Test that the assembler correctly reports errors
        let invalid_source = r#"
            .text
            start:
                add x1, x2, x99        # Invalid register x99
        "#;

        // Assemble should return an error
        let result = assemble(invalid_source);
        assert!(
            result.is_err(),
            "Assembly should fail with invalid register"
        );

        // Test undefined symbol
        let undefined_symbol = r#"
            .text
            start:
                beq x0, x0, nonexistent_label  # Undefined label
        "#;

        let result = assemble(undefined_symbol);
        assert!(
            result.is_err(),
            "Assembly should fail with undefined symbol"
        );
    }

    #[test]
    fn test_equ_directive() {
        // Test program using .equ directive to define constants
        let source = r#"
            # Define some constants
            .equ BUFFER_SIZE, 64
            .equ ZERO_REG, 0
            .equ DATA_OFFSET, 16
            
            .text
            start:
                # Use the constants in instructions
                addi a0, x0, BUFFER_SIZE     # a0 = 64
                addi t0, x0, DATA_OFFSET     # t0 = 16
                addi t1, x0, ZERO_REG        # t1 = 0
        "#;

        // Tokenize and parse
        let tokens = tokenize(source).unwrap();
        let mut parser = Parser::new(&tokens);
        let mut symbol_table = SymbolTable::new();

        let parsed_items = parser.parse_all(&mut symbol_table).unwrap();

        // Verify symbols were defined in the symbol table
        assert!(
            symbol_table.is_defined("BUFFER_SIZE"),
            "BUFFER_SIZE should be defined"
        );
        assert!(
            symbol_table.is_defined("ZERO_REG"),
            "ZERO_REG should be defined"
        );
        assert!(
            symbol_table.is_defined("DATA_OFFSET"),
            "DATA_OFFSET should be defined"
        );

        // Verify the symbol values
        assert_eq!(symbol_table.lookup("BUFFER_SIZE").unwrap().address(), 64);
        assert_eq!(symbol_table.lookup("ZERO_REG").unwrap().address(), 0);
        assert_eq!(symbol_table.lookup("DATA_OFFSET").unwrap().address(), 16);

        // Verify the instructions use the constants
        let mut found_addi_buffer = false;
        let mut found_addi_offset = false;
        let mut found_addi_zero = false;

        for item in parsed_items {
            if let ParsedItem::Instruction(instr) = item {
                if instr.mnemonic == "addi" {
                    match &instr.operands[0] {
                        ParsedOperand::Register(10) => {
                            // a0 is x10
                            // addi a0, x0, BUFFER_SIZE
                            assert_eq!(
                                instr.operands[2],
                                ParsedOperand::Symbol("BUFFER_SIZE".to_string())
                            );
                            found_addi_buffer = true;
                        }
                        ParsedOperand::Register(5) => {
                            // t0 is x5
                            // addi t0, x0, DATA_OFFSET
                            assert_eq!(
                                instr.operands[2],
                                ParsedOperand::Symbol("DATA_OFFSET".to_string())
                            );
                            found_addi_offset = true;
                        }
                        ParsedOperand::Register(6) => {
                            // t1 is x6
                            // addi t1, x0, ZERO_REG
                            assert_eq!(
                                instr.operands[2],
                                ParsedOperand::Symbol("ZERO_REG".to_string())
                            );
                            found_addi_zero = true;
                        }
                        _ => {}
                    }
                }
            }
        }

        assert!(
            found_addi_buffer,
            "Didn't find addi instruction using BUFFER_SIZE"
        );
        assert!(
            found_addi_offset,
            "Didn't find addi instruction using DATA_OFFSET"
        );
        assert!(
            found_addi_zero,
            "Didn't find addi instruction using ZERO_REG"
        );

        // Now let's assemble the program and check that the symbol values are used in the machine code
        let result = assemble(source).unwrap();

        // First instruction: addi a0, x0, 64 (BUFFER_SIZE)
        // 0x04000513
        assert_eq!(result.code[0], 0x04000513);

        // Second instruction: addi t0, x0, 16 (DATA_OFFSET)
        // 0x01000293
        assert_eq!(result.code[1], 0x01000293);

        // Third instruction: addi t1, x0, 0 (ZERO_REG)
        // 0x00000313
        assert_eq!(result.code[2], 0x00000313);
    }
}