aboutsummaryrefslogtreecommitdiff
path: root/lib/xixanta/src/assembler.rs
blob: bf7b5a01608340d1e74b49d036a8e305eb88c41c (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
use crate::errors::{Error, EvalError};
use crate::mapping::Mapping;
use crate::node::{ControlType, NodeType, PNode, PString};
pub use crate::object::{Bundle, Context, Object, ObjectType};
use crate::opcodes::{AddressingMode, INSTRUCTIONS};
use crate::parser::Parser;
use std::cmp::Ordering;
use std::collections::HashMap;
use std::io::Read;
use std::ops::Range;

/// The mode in which a literal is expressed.
#[derive(Clone, PartialEq)]
pub enum LiteralMode {
    /// An 8/16 bit hexadecimal value.
    Hexadecimal,

    /// A byte expressed in binary format.
    Binary,

    /// A byte expressed in plain decimal format.
    Plain,
}

/// The different stages that the assembler goes through and which are relevant
/// for the process.
#[derive(PartialEq)]
pub enum Stage {
    /// The context is still building up (i.e. we don't have all the variable
    /// values, labels and their addresses yet).
    Context,

    /// An initial context is there, and we can already consume most bundles. We
    /// only need to leave some of them as pending if they require a value that
    /// is relative to the end size of segments.
    Bundling,

    /// We have most bundles, and we already know the size for all segments.
    /// Hence, we can resolve (crunch) the nodes that were pending to be
    /// bundled.
    Crunching,
}

#[derive(Clone, Debug)]
pub struct Macro {
    nodes: Range<usize>,
    args: Vec<PString>,
}

#[derive(Clone, Debug)]
pub struct PendingNode {
    mapping: usize,
    segment: usize,
    context: String,
    bundle_index: usize,
    node: PNode,
    labels_seen: usize,
}

pub struct Assembler {
    context: Context,
    literal_mode: Option<LiteralMode>,
    stage: Stage,
    macros: HashMap<String, Macro>,
    can_bundle: bool,
    mappings: Vec<Mapping>,
    current_mapping: usize,
    current_segment: usize,
    pending: Vec<PendingNode>,
    labels_seen: usize,
}

impl Assembler {
    pub fn new(mappings: Vec<Mapping>) -> Self {
        crate::mapping::assert(&mappings);

        Self {
            context: Context::new(),
            literal_mode: None,
            stage: Stage::Context,
            macros: HashMap::new(),
            can_bundle: true,
            mappings,
            current_mapping: 0,
            current_segment: 0,
            pending: vec![],
            labels_seen: 0,
        }
    }

    pub fn assemble(&mut self, reader: impl Read) -> Result<Vec<Bundle>, Vec<Error>> {
        // First of all, parse the input so we get a list of nodes we can work
        // with.
        let mut parser = Parser::default();
        if let Err(errors) = parser.parse(reader) {
            return Err(errors.iter().map(|e| Error::Parse(e.clone())).collect());
        }

        // Build the context by iterating over the parsed nodes and checking
        // where scopes start/end, evaluating values for variables, labels, etc.
        self.eval_context(&parser.nodes)?;

        // Finally convert the relevant nodes into binary bundles which can be
        // used by the caller.
        self.stage = Stage::Bundling;
        self.bundle(&parser.nodes)?;

        self.stage = Stage::Crunching;
        self.crunch_and_resolve_pending()
    }

    pub fn eval_context(&mut self, nodes: &[PNode]) -> Result<(), Vec<Error>> {
        let mut errors = Vec::new();
        let mut current_macro = None;

        for (idx, node) in nodes.iter().enumerate() {
            match &node.node_type {
                NodeType::Label => {
                    if !node.value.is_empty() {
                        if let Err(err) = self.context.set_variable(
                            &node.value,
                            &Object::new(
                                self.current_mapping,
                                self.current_segment,
                                ObjectType::Address,
                            ),
                            false,
                        ) {
                            errors.push(Error::Context(err));
                        }
                    }
                }
                NodeType::Assignment => {
                    // TODO: in fact, we cannot have assignments in many places.
                    if current_macro.is_some() {
                        errors.push(Error::Eval(EvalError {
                            message: "cannot have assignments inside of macro definitions"
                                .to_string(),
                            line: node.value.line,
                            global: false,
                        }));
                        continue;
                    }
                    match self.evaluate_node(node.left.as_ref().unwrap()) {
                        Ok(value) => {
                            if let Err(err) = self.context.set_variable(
                                &node.value,
                                &Object {
                                    bundle: value,
                                    mapping: self.current_mapping,
                                    segment: self.current_segment,
                                    object_type: ObjectType::Value,
                                },
                                false,
                            ) {
                                errors.push(Error::Context(err));
                            }
                        }
                        Err(e) => errors.push(Error::Eval(e)),
                    }
                }
                NodeType::Control(control_type) => {
                    // TODO: prevent nesting of control statements depending on
                    // a definition (e.g. .macro's cannot be nested inside of
                    // another control statement, but .if yes).

                    match control_type {
                        ControlType::StartMacro => {
                            // TODO: macros are only on the global scope.
                            //
                            // TODO: boy this is ugly. In fact, this stupid shit if
                            // current_macro might not be relevant anymore.
                            current_macro = Some(&node.left.as_ref().unwrap().value);
                            // TODO: watch out for weird shit on the name of arguments.
                            self.macros
                                .entry(node.left.as_ref().unwrap().value.value.clone())
                                .or_insert(Macro {
                                    nodes: Range {
                                        start: idx + 1,
                                        end: idx + 1,
                                    },
                                    args: node
                                        .args
                                        .clone()
                                        .unwrap_or_default()
                                        .into_iter()
                                        .map(|a| a.value)
                                        .collect::<Vec<_>>(),
                                });
                        }
                        ControlType::EndMacro => {
                            // TODO: if m.nodes.start < idx - 1 => empty macro

                            if let Some(name) = current_macro {
                                self.macros
                                    .entry(name.value.clone())
                                    .and_modify(|m| m.nodes.end = idx - 1);
                            }
                            current_macro = None;
                        }
                        _ => {}
                    }
                    if let Err(err) = self.context.change_context(node) {
                        // TODO: forbid if inside_macro
                        errors.push(Error::Context(err));
                    }
                }
                _ => {}
            }
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }

    pub fn bundle(&mut self, nodes: &Vec<PNode>) -> Result<(), Vec<Error>> {
        let mut errors = Vec::new();

        for node in nodes {
            match node.node_type {
                NodeType::Label => {
                    let segment =
                        &self.mappings[self.current_mapping].segments[self.current_segment];
                    let value = segment.offset.to_le_bytes();
                    let object = Object {
                        bundle: Bundle {
                            bytes: [value[0], value[1], value[2]],
                            size: 2,
                            address: 0,
                            cycles: 0,
                            affected_on_page: false,
                            resolved: false,
                        },
                        mapping: self.current_mapping,
                        segment: self.current_segment,
                        object_type: ObjectType::Address,
                    };

                    if !node.value.is_empty() {
                        if let Err(err) = self.context.set_variable(&node.value, &object, true) {
                            errors.push(Error::Context(err));
                        }
                    }
                    self.context.add_label(&object);
                }
                NodeType::Instruction => {
                    if self.can_bundle {
                        self.literal_mode = None;
                        match self.evaluate_node(node) {
                            Ok(bundle) => {
                                if let Err(e) = self.push_bundle(bundle, node) {
                                    errors.push(Error::Eval(e));
                                }
                            }
                            Err(e) => errors.push(Error::Eval(e)),
                        }
                    }
                }
                NodeType::Control(_) => {
                    if let Err(e) = self.evaluate_control_statement(node) {
                        errors.push(Error::Eval(e));
                    }
                }
                NodeType::Value | NodeType::Call => {
                    if let Err(e) = self.bundle_call(node, nodes) {
                        errors.push(Error::Eval(e));
                    }
                }

                _ => {}
            }
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(errors)
        }
    }

    // TODO: maybe split?
    pub fn crunch_and_resolve_pending(&mut self) -> Result<Vec<Bundle>, Vec<Error>> {
        let mut errors = vec![];

        for pn in self.pending.clone() {
            self.labels_seen = pn.labels_seen;
            self.context.force_context_switch(&pn.context);

            match self.evaluate_node(&pn.node) {
                Ok(mut bundle) => {
                    let current = &self.mappings[pn.mapping].segments[pn.segment];
                    bundle.address = current.bundles[pn.bundle_index].address;

                    if pn.node.is_branch() {
                        bundle.resolved = true;
                        if let Err(e) = self.to_relative_address(&pn.node, &mut bundle) {
                            errors.push(Error::Eval(e));
                        }
                    }

                    let current_mut = &mut self.mappings[pn.mapping].segments[pn.segment];
                    current_mut.bundles[pn.bundle_index].bytes = bundle.bytes;
                }
                Err(e) => errors.push(Error::Eval(e)),
            }

            self.context.force_context_pop();
        }

        // Validate the mappings that have been evaluated before spitting it
        // out.
        if let Err(e) = crate::mapping::validate(&self.mappings) {
            return Err(vec![Error::Eval(e)]);
        }

        let mut res = vec![];

        for mapping in &mut self.mappings {
            for segment in mapping.segments.iter_mut() {
                // TODO: return a warning instead.
                if segment.is_empty() {
                    return Err(vec![Error::Eval(EvalError {
                        line: 0,
                        message: format!("segment '{}' is empty", segment.name),
                        global: true,
                    })]);
                }
                res.append(&mut segment.bundles);
            }

            let mut diff = mapping.size as isize - mapping.offset as isize;
            if diff < 0 {
                errors.push(Error::Eval(EvalError{
                        line: 0,
                        message: format!(
                            "exceeding segment size for '{}'; expecting {} bytes and {} bytes have already been seen",
                            mapping.name, mapping.size, mapping.offset,
                        ),
                        global: false,
                }));
            }

            if let Some(fill) = mapping.fill {
                while diff > 0 {
                    res.push(Bundle::fill(fill));
                    diff -= 1;
                }
            }
        }

        if errors.is_empty() {
            Ok(res)
        } else {
            Err(errors)
        }
    }

    fn bundle_call(&mut self, node: &PNode, nodes: &[PNode]) -> Result<(), EvalError> {
        // Get the macro object for the given identifier.
        let mcr = self
            .macros
            .get(&node.value.value)
            .ok_or(EvalError {
                line: node.value.line,
                message: format!(
                    "could not find a macro with the name '{}'",
                    node.value.value
                ),
                global: false,
            })?
            .clone();

        // Detect missmatches between the number of arguments provided and the
        // ones defined by the macro.
        let args = node.args.as_ref();
        let nargs = match args {
            Some(v) => v.len(),
            None => 0,
        };
        if mcr.args.len() != nargs {
            return Err(EvalError {
                line: node.value.line,
                message: format!(
                    "wrong number of arguments for '{}': {} required but {} given",
                    node.value.value,
                    mcr.args.len(),
                    nargs
                ),
                global: false,
            });
        }

        // If there are arguments defined by the macro, set their values now.
        if nargs > 0 {
            let mut margs = mcr.args.iter();

            for arg in args.unwrap().iter() {
                let obj = Object {
                    bundle: self.evaluate_node(arg)?,
                    mapping: self.current_mapping,
                    segment: self.current_segment,
                    object_type: ObjectType::Value,
                };
                self.context
                    .set_variable(margs.next().unwrap(), &obj, false)?;
            }
        }

        // And now replicate the nodes as contained inside of the macro
        // definition.
        for node in nodes
            .get(mcr.nodes.start..=mcr.nodes.end)
            .unwrap_or_default()
        {
            let bundle = self.evaluate_node(node)?;
            self.push_bundle(bundle, node)?;
        }

        Ok(())
    }

    fn push_bundle(&mut self, mut bundle: Bundle, node: &PNode) -> Result<(), EvalError> {
        let current = &mut self.mappings[self.current_mapping];
        bundle.address = current.start as usize + current.offset;
        current.offset += bundle.size as usize;
        current.segments[self.current_segment].offset += bundle.size as usize;

        if !bundle.resolved {
            self.pending.push(PendingNode {
                mapping: self.current_mapping,
                segment: self.current_segment,
                context: self.context.name().to_string(),
                bundle_index: current.segments[self.current_segment].bundles.len(),
                node: node.to_owned(),
                labels_seen: self.context.labels_seen(),
            });
        }
        current.segments[self.current_segment].bundles.push(bundle);

        Ok(())
    }

    fn evaluate_node(&mut self, node: &PNode) -> Result<Bundle, EvalError> {
        match node.node_type {
            NodeType::Instruction => Ok(self.evaluate_instruction(node)?),
            NodeType::Literal => Ok(self.evaluate_literal(node)?),
            NodeType::Control(_) => Ok(self.evaluate_control_expression(node)?),
            NodeType::Value => match self.literal_mode {
                Some(LiteralMode::Hexadecimal) => Ok(self.evaluate_hexadecimal(node)?),
                Some(LiteralMode::Binary) => Ok(self.evaluate_binary(node)?),
                Some(LiteralMode::Plain) => Ok(self.evaluate_decimal(node)?),
                None => {
                    if self.stage == Stage::Context {
                        // If we are just evaluating the context (e.g. parsing a
                        // variable), we'll assume that non-prefixed literals are
                        // just decimal values.
                        Ok(self.evaluate_decimal(node)?)
                    } else if node.value.is_anonymous_relative_reference() {
                        Ok(self.evaluate_anonymous_relative_reference(node)?)
                    } else if node.value.is_valid_identifier(true).is_err() {
                        // If this is not a valid identifier, just error out.
                        Err(EvalError {
                            message: "no prefix was given to operand".to_string(),
                            line: node.value.line,
                            global: false,
                        })
                    } else {
                        // This is actually a valid identifier! Try to fetch the
                        // variable.
                        match self.evaluate_variable(&node.value) {
                            Ok(v) => {
                                self.literal_mode = Some(LiteralMode::Hexadecimal);
                                Ok(v)
                            }
                            Err(err) => Err(EvalError {
                                message: format!(
                                    "no prefix was given to operand and {} either",
                                    err.message
                                ),
                                line: node.value.line,
                                global: false,
                            }),
                        }
                    }
                }
            },
            _ => Err(EvalError {
                message: format!("unexpected '{}' expression type", node.node_type),
                line: node.value.line,
                global: false,
            }),
        }
    }

    fn evaluate_anonymous_relative_reference(&mut self, node: &PNode) -> Result<Bundle, EvalError> {
        self.literal_mode = Some(LiteralMode::Plain);

        match &self.stage {
            Stage::Bundling => Ok(Bundle {
                bytes: [0, 0, 0],
                size: 2,
                address: 0,
                cycles: 0,
                affected_on_page: false,
                resolved: false,
            }),
            Stage::Crunching => {
                match self.context.get_relative_label(
                    node.value.to_isize(),
                    self.labels_seen,
                    &self.mappings,
                ) {
                    Ok(object) => Ok(object.bundle),
                    Err(e) => Err(EvalError {
                        line: node.value.line,
                        message: e.message,
                        global: false,
                    }),
                }
            }
            _ => panic!("unexpected evaluation of relative reference"),
        }
    }

    fn evaluate_hexadecimal(&mut self, node: &PNode) -> Result<Bundle, EvalError> {
        let mut chars = node.value.value.chars();
        let mut bytes = [0, 0, 0];
        let size: u8;

        match node.value.value.len() {
            1 => {
                bytes[0] = self.char_to_hex(chars.next(), node)?;
                size = 1;
            }
            2 => {
                bytes[0] = self.char_to_hex(chars.next(), node)? * 16;
                bytes[0] += self.char_to_hex(chars.next(), node)?;
                size = 1;
            }
            3 => {
                bytes[1] = self.char_to_hex(chars.next(), node)?;
                bytes[0] = self.char_to_hex(chars.next(), node)? * 16;
                bytes[0] += self.char_to_hex(chars.next(), node)?;
                size = 2;
            }
            4 => {
                bytes[1] = self.char_to_hex(chars.next(), node)? * 16;
                bytes[1] += self.char_to_hex(chars.next(), node)?;
                bytes[0] = self.char_to_hex(chars.next(), node)? * 16;
                bytes[0] += self.char_to_hex(chars.next(), node)?;
                size = 2;
            }
            _ => {
                if self.evaluate_variable(&node.value).is_ok() {
                    return Err(EvalError {
                        message: format!(
                            "you cannot use variables like '{}' in hexadecimal literals",
                            node.value.value
                        ),
                        line: node.value.line,
                        global: false,
                    });
                }
                return Err(EvalError {
                    message: "expecting a number of 1 to 4 hexadecimal digits".to_string(),
                    line: node.value.line,
                    global: false,
                });
            }
        }

        Ok(Bundle {
            bytes,
            size,
            address: 0,
            cycles: 0,
            affected_on_page: false,
            resolved: true,
        })
    }

    fn evaluate_binary(&mut self, node: &PNode) -> Result<Bundle, EvalError> {
        let string = node.value.value.as_str();
        let mut value = 0;
        let mut shift = 0;

        for c in string.chars().rev() {
            if c == '1' {
                let val = 1 << shift;
                value += val;
            } else if c != '0' {
                if self.evaluate_variable(&node.value).is_ok() {
                    return Err(EvalError {
                        message: format!(
                            "you cannot use variables like '{}' in binary literals",
                            string
                        ),
                        line: node.value.line,
                        global: false,
                    });
                }
                return Err(EvalError {
                    message: format!("bad binary format for '{}'", string),
                    line: node.value.line,
                    global: false,
                });
            }

            shift += 1;
        }

        match shift.cmp(&8) {
            Ordering::Less => Err(EvalError {
                message: "missing binary digits to get a full byte".to_string(),
                line: node.value.line,
                global: false,
            }),
            Ordering::Greater => Err(EvalError {
                message: "too many binary digits for a single byte".to_string(),
                line: node.value.line,
                global: false,
            }),
            Ordering::Equal => Ok(Bundle {
                bytes: [value as u8, 0, 0],
                size: 1,
                address: 0,
                cycles: 0,
                affected_on_page: false,
                resolved: true,
            }),
        }
    }

    fn evaluate_decimal(&mut self, node: &PNode) -> Result<Bundle, EvalError> {
        let string = node.value.value.as_str();
        if string.is_empty() {
            return Err(EvalError {
                message: "empty decimal literal".to_string(),
                line: node.value.line,
                global: false,
            });
        }

        let mut value = 0;
        let mut shift = 1;

        for c in string.chars().rev() {
            if shift > 100 {
                return Err(EvalError {
                    message: "decimal value is too big".to_string(),
                    line: node.value.line,
                    global: false,
                });
            }
            if c != '0' {
                match c.to_digit(10) {
                    Some(digit) => {
                        value += digit * shift;
                    }
                    None => {
                        if self.stage == Stage::Context {
                            return Err(EvalError {
                                message: format!(
                                    "variables must come from a constant expression, \
                                                  you cannot use other variables such as '{}' \
                                                  in variable definitions",
                                    string
                                ),
                                line: node.value.line,
                                global: false,
                            });
                        }
                        match self.evaluate_variable(&node.value) {
                            Ok(v) => return Ok(v),
                            Err(err) => {
                                return Err(EvalError {
                                    message: format!(
                                        "'{}' is not a decimal value and {} either",
                                        c, err.message
                                    ),
                                    line: node.value.line,
                                    global: false,
                                })
                            }
                        }
                    }
                }
            }

            shift *= 10;
        }
        if value > 255 {
            return Err(EvalError {
                message: "decimal value is too big".to_string(),
                line: node.value.line,
                global: false,
            });
        }

        Ok(Bundle {
            bytes: [value as u8, 0, 0],
            size: 1,
            address: 0,
            cycles: 0,
            affected_on_page: false,
            resolved: true,
        })
    }

    fn evaluate_literal(&mut self, node: &PNode) -> Result<Bundle, EvalError> {
        // The value of the literal is guaranteed to not be empty by the parser.
        // If that's not the case, then it's a bug.
        let val = node.value.value.as_str();
        assert!(!val.is_empty(), "the value for the literal was empty!");

        // Pick up the left node, which is the node to be further evaluated, and
        // determine the literal mode to be used.
        let left = node.left.as_ref().unwrap();

        let lm;
        if val.starts_with('$') {
            lm = Some(LiteralMode::Hexadecimal);
            if left.node_type == NodeType::Literal {
                return Err(EvalError {
                    message: "literal cannot embed another literal".to_string(),
                    line: node.value.line,
                    global: false,
                });
            }
        } else if val.starts_with('%') {
            lm = Some(LiteralMode::Binary);
            if left.node_type == NodeType::Literal {
                return Err(EvalError {
                    message: "literal cannot embed another literal".to_string(),
                    line: node.value.line,
                    global: false,
                });
            }
        } else {
            lm = Some(LiteralMode::Plain);
        }

        // And evaluate the left node.
        self.literal_mode = lm.clone();
        let expr = self.evaluate_node(left)?;
        self.literal_mode = lm;

        Ok(expr)
    }

    fn char_to_hex(&mut self, oc: Option<char>, source: &PNode) -> Result<u8, EvalError> {
        match oc {
            Some(c) => match c.to_digit(16) {
                Some(c) => Ok(c as u8),
                None => {
                    if (c.is_alphabetic() || c == '_')
                        && self.evaluate_variable(&source.value).is_ok()
                    {
                        return Err(EvalError {
                            message: format!(
                                "you cannot use variables like '{}' in hexadecimal literals",
                                source.value.value
                            ),
                            line: source.value.line,
                            global: false,
                        });
                    }
                    Err(EvalError {
                        message: "could not convert digit to hexadecimal".to_string(),
                        line: source.value.line,
                        global: false,
                    })
                }
            },
            None => Err(EvalError {
                message: "digit out of bounds".to_string(),
                line: source.value.line,
                global: false,
            }),
        }
    }

    fn evaluate_control_statement(&mut self, node: &PNode) -> Result<(), EvalError> {
        let changed;

        // This might just be a statement that changes the context (e.g.
        // ".macro", ".proc", etc.). In this case change the context and leave
        // early.
        (changed, self.can_bundle) = self.context.change_context(node)?;
        if changed {
            return Ok(());
        }

        // Otherwise, check the function that could act as a statement that
        // produces bundles.
        match node.node_type {
            NodeType::Control(ControlType::Byte) => self.push_evaluated_arguments(node, 1),
            NodeType::Control(ControlType::Addr) | NodeType::Control(ControlType::Word) => {
                self.push_evaluated_arguments(node, 2)
            }
            NodeType::Control(ControlType::Segment) => self.switch_to_segment(node),
            _ => Err(EvalError {
                line: node.value.line,
                message: format!(
                    "cannot handle control statement '{}' in this context",
                    node.value.value
                ),
                global: false,
            }),
        }
    }

    fn evaluate_control_expression(&mut self, node: &PNode) -> Result<Bundle, EvalError> {
        match node.node_type {
            NodeType::Control(ControlType::Hibyte) => self.evaluate_byte(node, true),
            NodeType::Control(ControlType::Lobyte) => self.evaluate_byte(node, false),
            _ => Err(EvalError {
                line: node.value.line,
                message: format!(
                    "cannot handle control statement '{}' as an expression in this context",
                    node.value.value
                ),
                global: false,
            }),
        }
    }

    fn evaluate_byte(&mut self, node: &PNode, high: bool) -> Result<Bundle, EvalError> {
        // The parser actually guarantees that the ".hibyte" and ".lobyte"
        // functions have exactly one argument. Hence, if this is not the case,
        // it's fine to let "unwrap" panic: it's a sign that's something is
        // wrong elsewhere.
        let arg = node.args.as_ref().unwrap().first().unwrap();

        // Get the bundle from the argument
        let mut bundle = self.evaluate_node(arg)?;

        // The bundle we got is going to be shuffled if we wanted the high byte.
        // After that, just zero out the rest (not mandatory but let's do it out
        // of consistency) and set the size to just one byte.
        if high {
            bundle.bytes[0] = bundle.bytes[1];
        }
        bundle.bytes[1] = 0x00;
        bundle.bytes[2] = 0x00;
        bundle.size = 1;

        Ok(bundle)
    }

    fn push_evaluated_arguments(&mut self, node: &PNode, nbytes: u8) -> Result<(), EvalError> {
        match &node.args {
            Some(args) => {
                for arg in args {
                    // Evaluate the argument as a node.
                    let mut bundle = self.evaluate_node(arg)?;

                    // If there is a missmatch between the expected number of
                    // bytes and what we got, we might be able to resolve it if
                    // we expected two bytes and only one was received: extend
                    // it by leading zeroes. Otherwise we have to error out:
                    // it's up to the programmer to either call `.hibyte` or
                    // something similar if that's whay they intended.
                    if bundle.size != nbytes {
                        match nbytes {
                            1 => {
                                return Err(EvalError {
                                    line: arg.value.line,
                                    message: "expecting an argument that fits into a byte"
                                        .to_string(),
                                    global: false,
                                })
                            }
                            2 => {
                                bundle.size = 2;
                                bundle.bytes[1] = 0x00;
                                bundle.bytes[2] = 0x00;
                            }
                            _ => panic!("bad argument when evaluating arguments"),
                        }
                    }
                    self.push_bundle(bundle, node)?;
                }
            }
            None => {
                return Err(EvalError {
                    line: node.value.line,
                    message: format!(
                        "expecting at least one argument for '{}'",
                        node.value.value.as_str(),
                    ),
                    global: false,
                })
            }
        }

        Ok(())
    }

    fn switch_to_segment(&mut self, node: &PNode) -> Result<(), EvalError> {
        // First of all, fetch the argument for the ".segment" statement and
        // validate that it has some basic format. Note that the existence of
        // exactly one argument is guaranteed by the parser and, thus,
        // `unwrap()` calls are not dangerous in this context.
        let arg = &node.args.as_ref().unwrap().first().unwrap();
        let val = &arg.value.value;
        if val.len() < 3 || !val.starts_with('"') || !val.ends_with('"') {
            return Err(EvalError {
                line: node.value.line,
                message: format!(
                    "segment declaration has to be written inside of double quotes ('{}' given instead)",
                    val,
                ),
                            global: false,
            });
        }

        // Validate the segment name.
        let name = &val[1..val.len() - 1];
        if name
            .chars()
            .any(|ch| !(ch.is_ascii_alphanumeric() || ch == '_' || ch == '-'))
        {
            return Err(EvalError {
                line: node.value.line,
                message: "segment name contains bad characters".to_string(),
                global: false,
            });
        }

        // You cannot change the segment if you are not in the global context.
        if !self.context.is_global() {
            return Err(EvalError {
                line: node.value.line,
                message: format!(
                    "cannot switch to segment '{}' if we are still inside of a scope ('{}')",
                    name,
                    self.context.name()
                ),
                global: false,
            });
        }

        // Find the segment being referenced and update the
        // `self.current_segment` accordingly.
        let mut found = false;
        for (mapping_idx, mapping) in self.mappings.iter().enumerate() {
            for (segment_idx, segment) in mapping.segments.iter().enumerate() {
                if segment.name == name {
                    self.current_mapping = mapping_idx;
                    self.current_segment = segment_idx;
                    found = true;
                    break;
                }
            }
        }
        if !found {
            return Err(EvalError {
                line: node.value.line,
                message: format!("unknown segment '{}'", name),
                global: false,
            });
        }
        Ok(())
    }

    fn evaluate_variable(&mut self, id: &PString) -> Result<Bundle, EvalError> {
        match self.context.get_variable(id, &self.mappings) {
            Ok(value) => Ok(value.bundle),
            Err(e) => Err(EvalError {
                message: e.message,
                line: id.line,
                global: false,
            }),
        }
    }

    fn evaluate_instruction(&mut self, node: &PNode) -> Result<Bundle, EvalError> {
        self.literal_mode = None;

        let (mode, mut bundle) = match &node.left {
            Some(_) => self.get_addressing_mode_and_bytes(node)?,
            None => (AddressingMode::Implied, Bundle::new(true)),
        };

        let mnemonic = node.value.value.to_lowercase();
        match INSTRUCTIONS.get(&mnemonic) {
            Some(entries) => match entries.get(&mode) {
                Some(values) => {
                    bundle.cycles = values.cycles;
                    bundle.size = values.size;
                    bundle.affected_on_page = values.affected_on_page;
                    bundle.bytes[2] = bundle.bytes[1];
                    bundle.bytes[1] = bundle.bytes[0];
                    bundle.bytes[0] = values.opcode.to_le_bytes()[0];
                }
                None => {
                    return Err(EvalError {
                        message: format!(
                            "cannot use {} addressing mode for the instruction '{}'",
                            mode, mnemonic
                        ),
                        line: node.value.line,
                        global: false,
                    })
                }
            },
            None => {
                return Err(EvalError {
                    message: format!("unknown instruction {}", mnemonic),
                    line: node.value.line,
                    global: false,
                });
            }
        }
        Ok(bundle)
    }

    fn get_addressing_mode_and_bytes(
        &mut self,
        node: &PNode,
    ) -> Result<(AddressingMode, Bundle), EvalError> {
        let left = &node.left;

        if left.as_ref().unwrap().node_type == NodeType::Indirection {
            self.get_from_indirect(node)
        } else if node.right.is_some() {
            self.get_from_indexed(node)
        } else {
            self.get_from_left(node, left.as_ref().unwrap())
        }
    }

    fn get_from_indirect(&mut self, node: &PNode) -> Result<(AddressingMode, Bundle), EvalError> {
        let left = node.left.as_ref().unwrap();

        match node.right.as_ref() {
            Some(right) => {
                if right.value.value.trim().to_lowercase() == "y" {
                    if left.right.is_some() {
                        return Err(EvalError {
                            message:
                                "it has to be either X addressing or Y addressing, not all at once"
                                    .to_string(),
                            line: node.value.line,
                            global: false,
                        });
                    }

                    let val = self.evaluate_node(left.left.as_ref().unwrap())?;
                    if val.size != 1 {
                        return Err(EvalError {
                            message: "address can only be one byte long on indirect Y addressing"
                                .to_string(),
                            line: node.value.line,
                            global: false,
                        });
                    }
                    return Ok((AddressingMode::IndirectY, val));
                }
                Err(EvalError {
                    message: "only the Y index is allowed on indirect Y addressing".to_string(),
                    line: node.value.line,
                    global: false,
                })
            }
            None => match left.right.as_ref() {
                Some(right) => {
                    if right.value.value.trim().to_lowercase() == "x" {
                        let val = self.evaluate_node(left.left.as_ref().unwrap())?;
                        if val.size != 1 {
                            return Err(EvalError {
                                message:
                                    "address can only be one byte long on indirect X addressing"
                                        .to_string(),
                                line: node.value.line,
                                global: false,
                            });
                        }
                        return Ok((AddressingMode::IndirectX, val));
                    }
                    Err(EvalError {
                        message: "only the X index is allowed on indirect X addressing".to_string(),
                        line: node.value.line,
                        global: false,
                    })
                }
                None => {
                    let val = self.evaluate_node(left.left.as_ref().unwrap())?;
                    if val.size != 2 {
                        return Err(EvalError {
                            message: "expecting a full 16-bit address".to_string(),
                            line: node.value.line,
                            global: false,
                        });
                    }
                    Ok((AddressingMode::Indirect, val))
                }
            },
        }
    }

    fn get_from_indexed(&mut self, node: &PNode) -> Result<(AddressingMode, Bundle), EvalError> {
        // Evaluate the left arm of the instruction.
        let left = node.left.as_ref().unwrap();
        let val = self.evaluate_node(left)?;

        // Ensure that the literal mode for the left arm ensures an address
        // instead of some bogus number.
        if let Some(lm) = &self.literal_mode {
            if *lm != LiteralMode::Hexadecimal {
                return Err(EvalError {
                    message: "indexed addressing only works with addresses".to_string(),
                    line: node.value.line,
                    global: false,
                });
            }
        }

        // Check the right arm to know the index being used.
        let right = node.right.as_ref().unwrap();
        match right.value.value.to_lowercase().trim() {
            "x" => {
                if val.size == 1 {
                    Ok((AddressingMode::ZeropageIndexedX, val))
                } else {
                    Ok((AddressingMode::IndexedX, val))
                }
            }
            "y" => {
                if val.size == 1 {
                    Ok((AddressingMode::ZeropageIndexedY, val))
                } else {
                    Ok((AddressingMode::IndexedY, val))
                }
            }
            _ => Err(EvalError {
                message: "can only use X and Y as indices".to_string(),
                line: node.value.line,
                global: false,
            }),
        }
    }

    fn get_from_left(
        &mut self,
        base: &PNode,
        left_arm: &PNode,
    ) -> Result<(AddressingMode, Bundle), EvalError> {
        if left_arm.value.value.to_lowercase().trim() == "a" {
            return Ok((AddressingMode::Implied, Bundle::new(true)));
        }

        let val = self.evaluate_node(left_arm)?;
        match self.literal_mode {
            Some(LiteralMode::Hexadecimal) => {
                if base.is_branch() || val.size == 1 {
                    Ok((AddressingMode::RelativeOrZeropage, val))
                } else {
                    Ok((AddressingMode::Absolute, val))
                }
            }
            Some(LiteralMode::Plain) => {
                if base.is_branch() {
                    Ok((AddressingMode::RelativeOrZeropage, val))
                } else if val.size > 1 {
                    match base.value.value.as_str() {
                        "jmp" | "jsr" => Ok((AddressingMode::Absolute, val)),
                        _ => Err(EvalError {
                            message: "immediate is too big".to_string(),
                            line: left_arm.value.line,
                            global: false,
                        }),
                    }
                } else {
                    Ok((AddressingMode::Immediate, val))
                }
            }
            _ => Err(EvalError {
                message: "left arm of instruction is neither an address nor an immediate"
                    .to_string(),
                line: left_arm.value.line,
                global: false,
            }),
        }
    }

    fn to_relative_address(&self, node: &PNode, bundle: &mut Bundle) -> Result<(), EvalError> {
        if !bundle.resolved {
            return Ok(());
        }

        let next = (bundle.address + 2) as u16;
        let target = u16::from_le_bytes([bundle.bytes[1], bundle.bytes[2]]);

        let byte = if target < next {
            let diff = target as i16 - next as i16;
            if diff < -128 {
                return Err(EvalError {
                    line: node.value.line,
                    message: "you cannot branch to this location: it's too far away".to_string(),
                    global: false,
                });
            }
            diff.to_le_bytes()[0]
        } else {
            let diff = target - next;
            if diff > 127 {
                return Err(EvalError {
                    line: node.value.line,
                    message: "you cannot branch to this location: it's too far away".to_string(),
                    global: false,
                });
            }
            diff.to_le_bytes()[0]
        };

        bundle.bytes[1] = byte;
        bundle.bytes[2] = 0;
        bundle.size = 2;

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::mapping::{SectionType, Segment, EMPTY};

    fn one_two() -> Vec<Mapping> {
        vec![
            Mapping {
                name: String::from("HEADER"),
                start: 0x0000,
                size: 0x0010,
                offset: 0,
                fill: Some(0x00),
                section_type: SectionType::Header,
                segments: vec![Segment {
                    name: String::from("HEADER"),
                    len: 0,
                    offset: 0,
                    bundles: vec![],
                }],
            },
            Mapping {
                name: String::from("ROM0"),
                start: 0x8000,
                size: 0x8000,
                offset: 0,
                fill: None,
                section_type: SectionType::PrgRom,
                segments: vec![
                    Segment {
                        name: String::from("ONE"),
                        len: 0,
                        offset: 0,
                        bundles: vec![],
                    },
                    Segment {
                        name: String::from("TWO"),
                        len: 0,
                        offset: 0,
                        bundles: vec![],
                    },
                ],
            },
        ]
    }

    fn minimal_header() -> Vec<Bundle> {
        vec![
            Bundle::fill(0x4E), // N
            Bundle::fill(0x45), // E
            Bundle::fill(0x53), // S
            Bundle::fill(0x1A), // MS-DOS \0
            Bundle::fill(0x01), // 1 * 8KB of PRG ROM
            Bundle::fill(0x00), // No CHR ROM
        ]
    }

    fn assert_instruction(line: &str, hex: &[u8]) {
        // Set up the empty mapper, but we have to push a minimal header
        // (otherwise an early assertion will fail), and we need to point to the
        // "CODE" segment (which is in the mapping indexed by 1).
        let mut asm = Assembler::new(EMPTY.to_vec());
        asm.mappings[0].segments[0].bundles = minimal_header();
        asm.mappings[0].offset = 6;
        asm.current_mapping = 1;

        // Grab the result passed the initial header.
        let res = &asm.assemble(line.as_bytes()).unwrap()[0x10..];

        assert_eq!(res.len(), 1);

        for i in 0..res[0].size {
            assert_eq!(hex[i as usize], res[0].bytes[i as usize]);
        }
    }

    fn assert_error(line: &str, id: &str, line_num: usize, global: bool, message: &str) {
        let mut asm = Assembler::new(EMPTY.to_vec());
        asm.mappings[0].segments[0].bundles = minimal_header();
        asm.mappings[0].offset = 6;
        asm.current_mapping = 1;

        assert_error_with_assembler(&mut asm, line, id, line_num, global, message);
    }

    fn assert_error_with_assembler(
        asm: &mut Assembler,
        line: &str,
        id: &str,
        line_num: usize,
        global: bool,
        message: &str,
    ) {
        let res = asm.assemble(line.as_bytes());
        let msg = if global {
            format!("{} error: {}.", id, message)
        } else {
            format!("{} error (line {}): {}.", id, line_num, message)
        };
        assert_eq!(res.unwrap_err().first().unwrap().to_string().as_str(), msg);
    }

    fn assert_eval_error(line: &str, message: &str) {
        assert_error(line, "Evaluation", 1, false, message);
    }

    fn assert_context_error(line: &str, message: &str, line_num: usize) {
        assert_error(line, "Context", line_num, false, message);
    }

    // Empty

    #[test]
    fn empty_line() {
        for line in vec!["", "  ", ";; Comment", "  ;; Comment"].into_iter() {
            assert_error(line, "Evaluation", 1, true, "segment 'CODE' is empty");
        }
    }

    // Literal modes

    #[test]
    fn parse_binary() {
        assert_eval_error("adc #%0001", "missing binary digits to get a full byte");
        assert_eval_error("adc #%0001000", "missing binary digits to get a full byte");
        assert_eval_error(
            "adc #%000100001",
            "too many binary digits for a single byte",
        );
        assert_error(
            r#"
Variable = 42
adc %Variable
"#,
            "Evaluation",
            3,
            false,
            "you cannot use variables like 'Variable' in binary literals",
        );
        assert_instruction("adc #%10100010", &[0x69, 0xA2]);
    }

    #[test]
    fn parse_hexadecimal() {
        assert_eval_error(
            "adc #$12345",
            "expecting a number of 1 to 4 hexadecimal digits",
        );
        assert_eval_error("adc $AW", "could not convert digit to hexadecimal");
        assert_error(
            r#"
Variable = 42
adc $Variable
"#,
            "Evaluation",
            3,
            false,
            "you cannot use variables like 'Variable' in hexadecimal literals",
        );
        assert_error(
            r#"
Four = 4
adc $Four
"#,
            "Evaluation",
            3,
            false,
            "you cannot use variables like 'Four' in hexadecimal literals",
        );
        assert_instruction("adc $AA", &[0x65, 0xAA]);
        assert_instruction("adc $10", &[0x65, 0x10]);
        assert_instruction("adc $10AB", &[0x6D, 0xAB, 0x10]);
    }

    #[test]
    fn parse_decimal() {
        assert_eval_error("adc #256", "decimal value is too big");
        assert_eval_error("adc #2000", "decimal value is too big");
        assert_eval_error(
            "adc #2A",
            "'A' is not a decimal value and could not find variable '2A' in the global scope either",
        );
        assert_instruction("adc #1", &[0x69, 0x01]);
    }

    // Variables

    #[test]
    fn scoped_variable() {
        let mut asm = Assembler::new(EMPTY.to_vec());
        asm.mappings[0].segments[0].bundles = minimal_header();
        asm.mappings[0].offset = 6;
        asm.current_mapping = 1;
        let res = &asm
            .assemble(
                r#"
.scope One   ; This is a comment
  adc #Variable

  Variable = $20
.endscope

.scope Another
  Variable = $40
.endscope

Variable = $30
adc #Variable

adc #One::Variable
adc #Another::Variable
"#
                .as_bytes(),
            )
            .unwrap()[0x10..];

        assert_eq!(res.len(), 4);
        let instrs: Vec<[u8; 2]> = vec![[0x69, 0x20], [0x69, 0x30], [0x69, 0x20], [0x69, 0x40]];

        for i in 0..4 {
            assert_eq!(res[i].size, 2);
            assert_eq!(res[i].bytes[0], instrs[i][0]);
            assert_eq!(res[i].bytes[1], instrs[i][1]);
        }
    }

    #[test]
    fn bare_variables() {
        let mut asm = Assembler::new(EMPTY.to_vec());
        asm.mappings[0].segments[0].bundles = minimal_header();
        asm.mappings[0].offset = 6;
        asm.current_mapping = 1;
        let res = &asm
            .assemble(
                r#"
Variable = 4
adc Variable
"#
                .as_bytes(),
            )
            .unwrap()[0x10..];

        assert_eq!(res.len(), 1);

        let instr = res.first().unwrap();
        assert_eq!(instr.size, 2);
        assert_eq!(instr.bytes[0], 0x65);
        assert_eq!(instr.bytes[1], 0x04);
    }

    #[test]
    fn bad_variable_but_valid_identifier_in_instruction() {
        assert_eval_error(
            "adc Variable",
            "no prefix was given to operand and could not find variable 'Variable' in the global scope either",
        );
        assert_eval_error(
            "adc Scoped::Variable",
            "no prefix was given to operand and did not find scope 'Scoped' either",
        );
    }

    #[test]
    fn redefined_variable() {
        assert_context_error(
            r#"
.scope One
  Variable = 1
.endscope

Variable = 1
Yet = 3
Yet = 4
"#,
            "'Yet' already defined in the global scope: you cannot re-assign variables",
            8,
        );
    }

    #[test]
    fn unknown_variables() {
        assert_eval_error(
            "lda #Variable",
            "'e' is not a decimal value and could not find variable \
                      'Variable' in the global scope either",
        );
        assert_eval_error(
            "lda #Scope::Variable",
            "'e' is not a decimal value and did not find scope 'Scope' either",
        );
        assert_error(
            r#"
.scope Scope
.endscope
lda #Scope::Variable
"#,
            "Evaluation",
            4,
            false,
            "'e' is not a decimal value and could not find variable 'Variable' in 'Scope' either",
        );
    }

    // Regular instructions

    #[test]
    fn bad_addressing() {
        assert_eval_error(
            "unknown #$20",
            "could not find a macro with the name 'unknown'",
        );
        assert_eval_error(
            "adc ($2002, x)",
            "address can only be one byte long on indirect X addressing",
        );
        assert_eval_error(
            "adc ($2002), y",
            "address can only be one byte long on indirect Y addressing",
        );
        assert_eval_error(
            "adc ($20, y)",
            "only the X index is allowed on indirect X addressing",
        );
        assert_eval_error(
            "adc ($20), x",
            "only the Y index is allowed on indirect Y addressing",
        );
        assert_eval_error("jmp ($20)", "expecting a full 16-bit address");
        assert_eval_error("adc $20, z", "can only use X and Y as indices");
        assert_eval_error(
            "adc ($2000)",
            "cannot use indirect addressing mode for the instruction 'adc'",
        );
        assert_eval_error("lda 12", "no prefix was given to operand")
    }

    #[test]
    fn adc() {
        assert_instruction("adc #20", &[0x69, 0x14]);
        assert_instruction("adc #$20", &[0x69, 0x20]);
        assert_instruction("adc $2002", &[0x6D, 0x02, 0x20]);
        assert_instruction("adc $20", &[0x65, 0x20]);
        assert_instruction("adc $20, x", &[0x75, 0x20]);
        assert_instruction("adc $2002, x", &[0x7D, 0x02, 0x20]);
        assert_instruction("adc $2002, y", &[0x79, 0x02, 0x20]);
        assert_instruction("adc ($20, x)", &[0x61, 0x20]);
        assert_instruction("adc ($20), y", &[0x71, 0x20]);
    }

    #[test]
    fn sbc() {
        assert_instruction("sbc #$20", &[0xE9, 0x20]);
        assert_instruction("sbc $2002", &[0xED, 0x02, 0x20]);
        assert_instruction("sbc $20", &[0xE5, 0x20]);
        assert_instruction("sbc $20, x", &[0xF5, 0x20]);
        assert_instruction("sbc $2002, x", &[0xFD, 0x02, 0x20]);
        assert_instruction("sbc $2002, y", &[0xF9, 0x02, 0x20]);
        assert_instruction("sbc ($20, x)", &[0xE1, 0x20]);
        assert_instruction("sbc ($20), y", &[0xF1, 0x20]);
    }

    #[test]
    fn shift() {
        // asl
        assert_instruction("asl", &[0x0A]);
        assert_instruction("asl a", &[0x0A]);
        assert_instruction("asl $20", &[0x06, 0x20]);
        assert_instruction("asl $20, x", &[0x16, 0x20]);
        assert_instruction("asl $2002", &[0x0E, 0x02, 0x20]);
        assert_instruction("asl $2002, x", &[0x1E, 0x02, 0x20]);

        // lsr
        assert_instruction("lsr", &[0x4A]);
        assert_instruction("lsr a", &[0x4A]);
        assert_instruction("lsr $20", &[0x46, 0x20]);
        assert_instruction("lsr $20, x", &[0x56, 0x20]);
        assert_instruction("lsr $2002", &[0x4E, 0x02, 0x20]);
        assert_instruction("lsr $2002, x", &[0x5E, 0x02, 0x20]);
    }

    #[test]
    fn rotate() {
        // rol
        assert_instruction("rol", &[0x2A]);
        assert_instruction("rol a", &[0x2A]);
        assert_instruction("rol $20", &[0x26, 0x20]);
        assert_instruction("rol $20, x", &[0x36, 0x20]);
        assert_instruction("rol $2002", &[0x2E, 0x02, 0x20]);
        assert_instruction("rol $2002, x", &[0x3E, 0x02, 0x20]);

        // ror
        assert_instruction("ror", &[0x6A]);
        assert_instruction("ror a", &[0x6A]);
        assert_instruction("ror $20", &[0x66, 0x20]);
        assert_instruction("ror $20, x", &[0x76, 0x20]);
        assert_instruction("ror $2002", &[0x6E, 0x02, 0x20]);
        assert_instruction("ror $2002, x", &[0x7E, 0x02, 0x20]);
    }

    #[test]
    fn and() {
        assert_instruction("and #$20", &[0x29, 0x20]);
        assert_instruction("and $2002", &[0x2D, 0x02, 0x20]);
        assert_instruction("and $20", &[0x25, 0x20]);
        assert_instruction("and $20, x", &[0x35, 0x20]);
        assert_instruction("and $2002, x", &[0x3D, 0x02, 0x20]);
        assert_instruction("and $2002, y", &[0x39, 0x02, 0x20]);
        assert_instruction("and ($20, x)", &[0x21, 0x20]);
        assert_instruction("and ($20), y", &[0x31, 0x20]);
    }

    #[test]
    fn or() {
        // eor
        assert_instruction("eor #$20", &[0x49, 0x20]);
        assert_instruction("eor $20", &[0x45, 0x20]);
        assert_instruction("eor $20, x", &[0x55, 0x20]);
        assert_instruction("eor $2002", &[0x4D, 0x02, 0x20]);
        assert_instruction("eor $2002, x", &[0x5D, 0x02, 0x20]);
        assert_instruction("eor $2002, y", &[0x59, 0x02, 0x20]);
        assert_instruction("eor ($20, x)", &[0x41, 0x20]);
        assert_instruction("eor ($20), y", &[0x51, 0x20]);

        // ora
        assert_instruction("ora #$20", &[0x09, 0x20]);
        assert_instruction("ora $20", &[0x05, 0x20]);
        assert_instruction("ora $20, x", &[0x15, 0x20]);
        assert_instruction("ora $2002", &[0x0D, 0x02, 0x20]);
        assert_instruction("ora $2002, x", &[0x1D, 0x02, 0x20]);
        assert_instruction("ora $2002, y", &[0x19, 0x02, 0x20]);
        assert_instruction("ora ($20, x)", &[0x01, 0x20]);
        assert_instruction("ora ($20), y", &[0x11, 0x20]);
    }

    #[test]
    fn load() {
        // lda
        assert_instruction("lda #$20", &[0xA9, 0x20]);
        assert_instruction("lda $20", &[0xA5, 0x20]);
        assert_instruction("lda $20, x", &[0xB5, 0x20]);
        assert_instruction("lda $2002", &[0xAD, 0x02, 0x20]);
        assert_instruction("lda $2002, x", &[0xBD, 0x02, 0x20]);
        assert_instruction("lda $2002, y", &[0xB9, 0x02, 0x20]);
        assert_instruction("lda ($20, x)", &[0xA1, 0x20]);
        assert_instruction("lda ($20), y", &[0xB1, 0x20]);

        // ldx
        assert_instruction("ldx #$20", &[0xA2, 0x20]);
        assert_instruction("ldx $20", &[0xA6, 0x20]);
        assert_instruction("ldx $20, y", &[0xB6, 0x20]);
        assert_instruction("ldx $2002", &[0xAE, 0x02, 0x20]);
        assert_instruction("ldx $2002, y", &[0xBE, 0x02, 0x20]);

        // ldy
        assert_instruction("ldy #$20", &[0xA0, 0x20]);
        assert_instruction("ldy $20", &[0xA4, 0x20]);
        assert_instruction("ldy $20, x", &[0xB4, 0x20]);
        assert_instruction("ldy $2002", &[0xAC, 0x02, 0x20]);
        assert_instruction("ldy $2002, x", &[0xBC, 0x02, 0x20]);
    }

    #[test]
    fn jump() {
        assert_instruction("jsr $2002", &[0x20, 0x02, 0x20]);

        assert_instruction("jmp $2002", &[0x4C, 0x02, 0x20]);
        assert_instruction("jmp ($2002)", &[0x6C, 0x02, 0x20]);
    }

    #[test]
    fn inc_dec_instructions() {
        // inc
        assert_instruction("inc $10", &[0xE6, 0x10]);
        assert_instruction("inc $1000", &[0xEE, 0x00, 0x10]);
        assert_instruction("inc $10, x", &[0xF6, 0x10]);
        assert_instruction("inc $1000, x", &[0xFE, 0x00, 0x10]);

        assert_instruction("inx", &[0xE8]);

        assert_instruction("iny", &[0xC8]);

        // dec
        assert_instruction("dec $10", &[0xC6, 0x10]);
        assert_instruction("dec $1000", &[0xCE, 0x00, 0x10]);
        assert_instruction("dec $10, x", &[0xD6, 0x10]);
        assert_instruction("dec $1000, x", &[0xDE, 0x00, 0x10]);

        assert_instruction("dex", &[0xCA]);

        assert_instruction("dey", &[0x88]);
    }

    #[test]
    fn transfer_instructions() {
        assert_instruction("tax", &[0xAA]);
        assert_instruction("tay", &[0xA8]);
        assert_instruction("tsx", &[0xBA]);
        assert_instruction("txa", &[0x8A]);
        assert_instruction("txs", &[0x9A]);
        assert_instruction("tya", &[0x98]);
    }

    #[test]
    fn return_instructions() {
        assert_instruction("rti", &[0x40]);
        assert_instruction("rts", &[0x60]);
    }

    #[test]
    fn set_clear_instructions() {
        assert_instruction("clc", &[0x18]);
        assert_instruction("cld", &[0xD8]);
        assert_instruction("cli", &[0x58]);
        assert_instruction("clv", &[0xB8]);

        assert_instruction("sec", &[0x38]);
        assert_instruction("sed", &[0xF8]);
        assert_instruction("sei", &[0x78]);
    }

    #[test]
    fn push_pull_instructions() {
        assert_instruction("pha", &[0x48]);
        assert_instruction("php", &[0x08]);
        assert_instruction("pla", &[0x68]);
        assert_instruction("plp", &[0x28]);
    }

    #[test]
    fn nop_brk() {
        assert_instruction("nop", &[0xEA]);
        assert_instruction("brk", &[0x00]);
    }

    #[test]
    fn cmp() {
        // cmp
        assert_instruction("cmp #$20", &[0xC9, 0x20]);
        assert_instruction("cmp $2002", &[0xCD, 0x02, 0x20]);
        assert_instruction("cmp $20", &[0xC5, 0x20]);
        assert_instruction("cmp $20, x", &[0xD5, 0x20]);
        assert_instruction("cmp $2002, x", &[0xDD, 0x02, 0x20]);
        assert_instruction("cmp $2002, y", &[0xD9, 0x02, 0x20]);
        assert_instruction("cmp ($20, x)", &[0xC1, 0x20]);
        assert_instruction("cmp ($20), y", &[0xD1, 0x20]);

        // cpx
        assert_instruction("cpx #$20", &[0xE0, 0x20]);
        assert_instruction("cpx $2002", &[0xEC, 0x02, 0x20]);
        assert_instruction("cpx $20", &[0xE4, 0x20]);

        // cpy
        assert_instruction("cpy #$20", &[0xC0, 0x20]);
        assert_instruction("cpy $2002", &[0xCC, 0x02, 0x20]);
        assert_instruction("cpy $20", &[0xC4, 0x20]);
    }

    #[test]
    fn store_instructions() {
        //sta
        assert_instruction("sta $20", &[0x85, 0x20]);
        assert_instruction("sta $20, x", &[0x95, 0x20]);
        assert_instruction("sta $2002", &[0x8D, 0x02, 0x20]);
        assert_instruction("sta $2002, x", &[0x9D, 0x02, 0x20]);
        assert_instruction("sta $2002, y", &[0x99, 0x02, 0x20]);
        assert_instruction("sta ($20, x)", &[0x81, 0x20]);
        assert_instruction("sta ($20), y", &[0x91, 0x20]);

        // stx
        assert_instruction("stx $20", &[0x86, 0x20]);
        assert_instruction("stx $20, y", &[0x96, 0x20]);
        assert_instruction("stx $2002", &[0x8E, 0x02, 0x20]);

        // sty
        assert_instruction("sty $20", &[0x84, 0x20]);
        assert_instruction("sty $20, x", &[0x94, 0x20]);
        assert_instruction("sty $2002", &[0x8C, 0x02, 0x20]);
    }

    #[test]
    fn bit() {
        assert_instruction("bit $10", &[0x24, 0x10]);
        assert_instruction("bit $1001", &[0x2C, 0x01, 0x10]);
    }

    // Labels & branching

    #[test]
    fn same_segment_labels() {
        let mut asm = Assembler::new(EMPTY.to_vec());
        asm.mappings[0].segments[0].bundles = minimal_header();
        asm.mappings[0].offset = 6;
        asm.current_mapping = 1;
        let res = &asm
            .assemble(
                r#"
nop
@hello:
    jmp @hello
    jmp @end
@end:
    nop
"#
                .as_bytes(),
            )
            .unwrap()[0x10..];

        assert_eq!(res.len(), 4);

        // jmp @hello
        assert_eq!(res[1].size, 3);
        assert_eq!(res[1].bytes[0], 0x4C);
        assert_eq!(res[1].bytes[1], 0x01);
        assert_eq!(res[1].bytes[2], 0x80);

        // jmp @end
        assert_eq!(res[2].size, 3);
        assert_eq!(res[2].bytes[0], 0x4C);
        assert_eq!(res[2].bytes[1], 0x07);
        assert_eq!(res[2].bytes[2], 0x80);
    }

    #[test]
    fn anonymous_relative_jumps() {
        let mut asm = Assembler::new(EMPTY.to_vec());
        asm.mappings[0].segments[0].bundles = minimal_header();
        asm.mappings[0].offset = 6;
        asm.current_mapping = 1;
        let res = &asm
            .assemble(
                r#"
nop
:
    nop
@hello:
    jmp :--
    jmp :+
    jmp @hello
    jmp :+++
@end:
    nop
:
    nop
: nop
"#
                .as_bytes(),
            )
            .unwrap()[0x10..];

        assert_eq!(res.len(), 9);

        // First two nop's
        assert_eq!(res[0].size, 1);
        assert_eq!(res[0].bytes[0], 0xEA);
        assert_eq!(res[1].size, 1);
        assert_eq!(res[1].bytes[0], 0xEA);

        // jmp :--
        assert_eq!(res[2].size, 3);
        assert_eq!(res[2].bytes[0], 0x4C);
        assert_eq!(res[2].bytes[1], 0x01);
        assert_eq!(res[2].bytes[2], 0x80);

        // jmp :+
        assert_eq!(res[3].size, 3);
        assert_eq!(res[3].bytes[0], 0x4C);
        assert_eq!(res[3].bytes[1], 0x0E);
        assert_eq!(res[3].bytes[2], 0x80);

        // jmp @hello
        assert_eq!(res[4].size, 3);
        assert_eq!(res[4].bytes[0], 0x4C);
        assert_eq!(res[4].bytes[1], 0x02);
        assert_eq!(res[4].bytes[2], 0x80);

        // jmp :+++
        assert_eq!(res[5].size, 3);
        assert_eq!(res[5].bytes[0], 0x4C);
        assert_eq!(res[5].bytes[1], 0x10);
        assert_eq!(res[5].bytes[2], 0x80);

        // Three last nop's.
        assert_eq!(res[6].size, 1);
        assert_eq!(res[6].bytes[0], 0xEA);
        assert_eq!(res[7].size, 1);
        assert_eq!(res[7].bytes[0], 0xEA);
        assert_eq!(res[8].size, 1);
        assert_eq!(res[8].bytes[0], 0xEA);
    }

    #[test]
    fn anonymous_relative_branches() {
        let mut asm = Assembler::new(EMPTY.to_vec());
        asm.mappings[0].segments[0].bundles = minimal_header();
        asm.mappings[0].offset = 6;
        asm.current_mapping = 1;
        let res = &asm
            .assemble(
                r#"
nop
:
    nop
@hello:
    beq :--
    beq :+
    beq @hello
    beq :+++
@end:
    nop
:
    nop
: nop
"#
                .as_bytes(),
            )
            .unwrap()[0x10..];

        assert_eq!(res.len(), 9);

        // First two nop's
        assert_eq!(res[0].size, 1);
        assert_eq!(res[0].bytes[0], 0xEA);
        assert_eq!(res[1].size, 1);
        assert_eq!(res[1].bytes[0], 0xEA);

        // beq :--
        assert_eq!(res[2].size, 2);
        assert_eq!(res[2].bytes[0], 0xF0);
        assert_eq!(res[2].bytes[1], 0xFD);

        // beq :+
        assert_eq!(res[3].size, 2);
        assert_eq!(res[3].bytes[0], 0xF0);
        assert_eq!(res[3].bytes[1], 0x04);

        // beq @hello
        assert_eq!(res[4].size, 2);
        assert_eq!(res[4].bytes[0], 0xF0);
        assert_eq!(res[4].bytes[1], 0xFA);

        // beq :+++
        assert_eq!(res[5].size, 2);
        assert_eq!(res[5].bytes[0], 0xF0);
        assert_eq!(res[5].bytes[1], 0x02);

        // Three last nop's.
        assert_eq!(res[6].size, 1);
        assert_eq!(res[6].bytes[0], 0xEA);
        assert_eq!(res[7].size, 1);
        assert_eq!(res[7].bytes[0], 0xEA);
        assert_eq!(res[8].size, 1);
        assert_eq!(res[8].bytes[0], 0xEA);
    }

    #[test]
    fn conditional_branch_to_labels() {
        let mut asm = Assembler::new(EMPTY.to_vec());
        asm.mappings[0].segments[0].bundles = minimal_header();
        asm.mappings[0].offset = 6;
        asm.current_mapping = 1;
        let res = &asm
            .assemble(
                r#"
nop
@hello:
    beq @hello
    beq @end
@end:
    nop
"#
                .as_bytes(),
            )
            .unwrap()[0x10..];

        assert_eq!(res.len(), 4);

        // beq @hello
        assert_eq!(res[1].size, 2);
        assert_eq!(res[1].bytes[0], 0xF0);
        assert_eq!(res[1].bytes[1], 0xFE);

        // beq @end
        assert_eq!(res[2].size, 2);
        assert_eq!(res[2].bytes[0], 0xF0);
        assert_eq!(res[2].bytes[1], 0x00);
    }

    // TODO: function calls
    // TODO: labels and jumps inside of proc's, macros, etc.

    // Control statements

    #[test]
    fn byte_literals() {
        let mut asm = Assembler::new(EMPTY.to_vec());
        asm.mappings[0].segments[0].bundles = minimal_header();
        asm.mappings[0].offset = 6;
        asm.current_mapping = 1;
        let res = &asm
            .assemble(
                r#"
.scope Vars
    Variable = 4
.endscope

.byte #Vars::Variable
.dw $2001, $02
"#
                .as_bytes(),
            )
            .unwrap()[0x10..];

        assert_eq!(res.len(), 3);

        // .byte
        assert_eq!(res[0].bytes[0], 0x04);
        assert_eq!(res[0].bytes[1], 0x00);
        assert_eq!(res[0].size, 1);

        // First .dw argument.
        assert_eq!(res[1].bytes[0], 0x01);
        assert_eq!(res[1].bytes[1], 0x20);
        assert_eq!(res[1].size, 2);

        // Second .dw argument.
        assert_eq!(res[2].bytes[0], 0x02);
        assert_eq!(res[2].bytes[1], 0x00);
        assert_eq!(res[2].size, 2);
    }

    #[test]
    fn hi_lo_byte() {
        let mut asm = Assembler::new(EMPTY.to_vec());
        asm.mappings[0].segments[0].bundles = minimal_header();
        asm.mappings[0].offset = 6;
        asm.current_mapping = 1;
        let res = &asm
            .assemble(
                r#"
Var = $2002
lda #.lobyte(Var)
lda #.hibyte(Var)
"#
                .as_bytes(),
            )
            .unwrap()[0x10..];

        assert_eq!(res.len(), 2);
        let instrs: Vec<[u8; 2]> = vec![[0xA9, 0x02], [0xA9, 0x20]];

        for i in 0..2 {
            assert_eq!(res[i].size, 2);
            assert_eq!(res[i].bytes[0], instrs[i][0]);
            assert_eq!(res[i].bytes[1], instrs[i][1]);
        }
    }

    // Macros

    #[test]
    fn macro_no_arguments() {
        let mut asm = Assembler::new(EMPTY.to_vec());
        asm.mappings[0].segments[0].bundles = minimal_header();
        asm.mappings[0].offset = 6;
        asm.current_mapping = 1;
        let res = &asm
            .assemble(
                r#"
lda #42

.macro MACRO
    lda #2
.endmacro

lda #1
MACRO
"#
                .as_bytes(),
            )
            .unwrap()[0x10..];

        assert_eq!(res.len(), 3);
        let instrs: Vec<[u8; 2]> = vec![[0xA9, 0x2A], [0xA9, 0x01], [0xA9, 0x02]];

        for i in 0..3 {
            assert_eq!(res[i].size, 2);
            assert_eq!(res[i].bytes[0], instrs[i][0]);
            assert_eq!(res[i].bytes[1], instrs[i][1]);
        }
    }

    #[test]
    fn macro_not_enough_arguments() {
        let mut asm = Assembler::new(EMPTY.to_vec());
        asm.mappings[0].segments[0].bundles = minimal_header();
        asm.mappings[0].offset = 6;
        asm.current_mapping = 1;
        let res = asm
            .assemble(
                r#"
lda #42

.macro MACRO(Var)
    lda #Var
.endmacro

lda #1
MACRO
"#
                .as_bytes(),
            )
            .unwrap_err();

        assert_eq!(
            res.first().unwrap().to_string(),
            "Evaluation error (line 9): wrong number of arguments for 'MACRO': 1 required but 0 given."
        );
    }

    #[test]
    fn macro_too_many_arguments() {
        let mut asm = Assembler::new(EMPTY.to_vec());
        asm.mappings[0].segments[0].bundles = minimal_header();
        asm.mappings[0].offset = 6;
        asm.current_mapping = 1;
        let res = asm
            .assemble(
                r#"
lda #42

.macro MACRO(Var)
    lda #Var
.endmacro

lda #1
MACRO(1, 2)
"#
                .as_bytes(),
            )
            .unwrap_err();

        assert_eq!(
            res.first().unwrap().to_string(),
            "Evaluation error (line 9): wrong number of arguments for 'MACRO': 1 required but 2 given."
        );
    }

    #[test]
    fn macro_with_one_argument() {
        let mut asm = Assembler::new(EMPTY.to_vec());
        asm.mappings[0].segments[0].bundles = minimal_header();
        asm.mappings[0].offset = 6;
        asm.current_mapping = 1;
        let res = &asm
            .assemble(
                r#"
lda #42

.macro MACRO(Var)
    lda #Var
.endmacro

lda #1
MACRO(2)
"#
                .as_bytes(),
            )
            .unwrap()[0x10..];

        assert_eq!(res.len(), 3);
        let instrs: Vec<[u8; 2]> = vec![[0xA9, 0x2A], [0xA9, 0x01], [0xA9, 0x02]];

        for i in 0..3 {
            assert_eq!(res[i].size, 2);
            assert_eq!(res[i].bytes[0], instrs[i][0]);
            assert_eq!(res[i].bytes[1], instrs[i][1]);
        }
    }

    #[test]
    fn macro_unknown_arguments() {
        let mut asm = Assembler::new(EMPTY.to_vec());
        asm.mappings[0].segments[0].bundles = minimal_header();
        asm.mappings[0].offset = 6;
        asm.current_mapping = 1;
        let res = asm
            .assemble(
                r#"
lda #42

.macro MACRO(Var)
    lda #Va
.endmacro

lda #1
MACRO(1)
"#
                .as_bytes(),
            )
            .unwrap_err();

        assert_eq!(
            res.first().unwrap().to_string(),
            "Evaluation error (line 5): 'a' is not a decimal value and \
             could not find variable 'Va' in the global scope either."
        );
    }

    #[test]
    fn macro_shadow_argument() {
        let mut asm = Assembler::new(EMPTY.to_vec());
        asm.mappings[0].segments[0].bundles = minimal_header();
        asm.mappings[0].offset = 6;
        asm.current_mapping = 1;
        let res = asm
            .assemble(
                r#"
Var = 3
lda #42

.macro MACRO(Var)
    lda #Va
.endmacro

lda #1
MACRO(1)
"#
                .as_bytes(),
            )
            .unwrap_err();

        assert_eq!(
            res.first().unwrap().to_string(),
            "Evaluation error (line 5): 'Var' already defined in the global scope: \
             you cannot re-assign variables."
        );
    }

    #[test]
    fn macro_multiple_arguments() {
        let mut asm = Assembler::new(EMPTY.to_vec());
        asm.mappings[0].segments[0].bundles = minimal_header();
        asm.mappings[0].offset = 6;
        asm.current_mapping = 1;
        let res = &asm
            .assemble(
                r#"
.macro WRITE_PPU_DATA address, value
    bit $2002                   ; PPUSTATUS
    lda #.HIBYTE(address)
    sta $2006                   ; PPUADDR
    lda #.LOBYTE(address)
    sta $2006                   ; PPUADDR
    lda #value
    sta $2007                   ; PPUDATA
.endmacro

WRITE_PPU_DATA $20B9, $04
"#
                .as_bytes(),
            )
            .unwrap()[0x10..];

        assert_eq!(res.len(), 7);

        // bit $2002
        assert_eq!(res[0].size, 3);
        assert_eq!(res[0].bytes[0], 0x2C);
        assert_eq!(res[0].bytes[1], 0x02);
        assert_eq!(res[0].bytes[2], 0x20);

        // lda #.HIBYTE(address)
        assert_eq!(res[1].size, 2);
        assert_eq!(res[1].bytes[0], 0xA9);
        assert_eq!(res[1].bytes[1], 0x20);

        // sta $2006
        assert_eq!(res[2].size, 3);
        assert_eq!(res[2].bytes[0], 0x8D);
        assert_eq!(res[2].bytes[1], 0x06);
        assert_eq!(res[2].bytes[2], 0x20);

        // lda #.LOBYTE(address)
        assert_eq!(res[3].size, 2);
        assert_eq!(res[3].bytes[0], 0xA9);
        assert_eq!(res[3].bytes[1], 0xB9);

        // sta $2006
        assert_eq!(res[4].size, 3);
        assert_eq!(res[4].bytes[0], 0x8D);
        assert_eq!(res[4].bytes[1], 0x06);
        assert_eq!(res[4].bytes[2], 0x20);

        // lda #value
        assert_eq!(res[5].size, 2);
        assert_eq!(res[5].bytes[0], 0xA9);
        assert_eq!(res[5].bytes[1], 0x04);

        // sta $2007
        assert_eq!(res[6].size, 3);
        assert_eq!(res[6].bytes[0], 0x8D);
        assert_eq!(res[6].bytes[1], 0x07);
        assert_eq!(res[6].bytes[2], 0x20);
    }

    // Segments

    #[test]
    fn error_on_unknown_segment() {
        let mut asm = Assembler::new(one_two().to_vec());
        asm.mappings[0].segments[0].bundles = minimal_header();
        asm.mappings[0].offset = 6;

        let line = r#"
.segment "THREE"

.segment "TWO"
nop
"#;
        assert_error_with_assembler(
            &mut asm,
            line,
            "Evaluation",
            2,
            false,
            "unknown segment 'THREE'",
        )
    }

    #[test]
    fn error_on_empty_segment() {
        let mut asm = Assembler::new(one_two().to_vec());
        asm.mappings[0].segments[0].bundles = minimal_header();
        asm.mappings[0].offset = 6;
        let line = r#"
.segment "ONE"

.segment "TWO"
nop
"#;
        assert_error_with_assembler(
            &mut asm,
            line,
            "Evaluation",
            1,
            true,
            "segment 'ONE' is empty",
        )
    }

    #[test]
    fn jmp_and_beq_inside_segment() {
        let mut asm = Assembler::new(one_two().to_vec());
        asm.mappings[0].segments[0].bundles = minimal_header();
        asm.mappings[0].offset = 6;
        let bundles = &asm
            .assemble(
                r#"
.segment "ONE"
nop

.segment "TWO"
nop
:
    nop
@hello:
    beq :--
    beq :+
    jmp @hello
    beq @hello
    beq :+++
    beq @end
@end:
    nop
:
    nop
: nop
"#
                .as_bytes(),
            )
            .unwrap()[0x11..]; // Ignoring HEADER + nop from ONE

        // First two nop's
        assert_eq!(bundles[0].size, 1);
        assert_eq!(bundles[0].bytes[0], 0xEA);
        assert_eq!(bundles[1].size, 1);
        assert_eq!(bundles[1].bytes[0], 0xEA);

        // beq :--
        assert_eq!(bundles[2].size, 2);
        assert_eq!(bundles[2].bytes[0], 0xF0);
        assert_eq!(bundles[2].bytes[1], 0xFD);

        // beq :+
        assert_eq!(bundles[3].size, 2);
        assert_eq!(bundles[3].bytes[0], 0xF0);
        assert_eq!(bundles[3].bytes[1], 0x09);

        // jmp @hello
        assert_eq!(bundles[4].size, 3);
        assert_eq!(bundles[4].bytes[0], 0x4C);
        assert_eq!(bundles[4].bytes[1], 0x03);
        assert_eq!(bundles[4].bytes[2], 0x80);

        // beq @hello
        assert_eq!(bundles[5].size, 2);
        assert_eq!(bundles[5].bytes[0], 0xF0);
        assert_eq!(bundles[5].bytes[1], 0xF7);

        // beq :+++
        assert_eq!(bundles[6].size, 2);
        assert_eq!(bundles[6].bytes[0], 0xF0);
        assert_eq!(bundles[6].bytes[1], 0x04);

        // beq @end
        assert_eq!(bundles[7].size, 2);
        assert_eq!(bundles[7].bytes[0], 0xF0);
        assert_eq!(bundles[7].bytes[1], 0x00);

        // Three last nop's.
        assert_eq!(bundles[8].size, 1);
        assert_eq!(bundles[8].bytes[0], 0xEA);
        assert_eq!(bundles[9].size, 1);
        assert_eq!(bundles[9].bytes[0], 0xEA);
        assert_eq!(bundles[10].size, 1);
        assert_eq!(bundles[10].bytes[0], 0xEA);
    }

    #[test]
    fn jmp_on_different_segments_intertwined() {
        let mut asm = Assembler::new(one_two().to_vec());
        asm.mappings[0].segments[0].bundles = minimal_header();
        asm.mappings[0].offset = 6;
        let bundles = &asm
            .assemble(
                r#"
.segment "ONE"
lala:
    rts

.segment "TWO"
code:
    jsr lala
    jsr code
    rts

.segment "ONE"
    jsr code
"#
                .as_bytes(),
            )
            .unwrap()[0x11..]; // Ignoring HEADER + rts from ONE

        // "jsr code" from ONE (notice that it's intertwined!)
        assert_eq!(bundles[0].size, 3);
        assert_eq!(bundles[0].bytes[0], 0x20);
        assert_eq!(bundles[0].bytes[1], 0x04);
        assert_eq!(bundles[0].bytes[2], 0x80);

        // "jsr lala" from TWO
        assert_eq!(bundles[1].size, 3);
        assert_eq!(bundles[1].bytes[0], 0x20);
        assert_eq!(bundles[1].bytes[1], 0x00);
        assert_eq!(bundles[1].bytes[2], 0x80);

        // "jsr code" from TWO (again, notice that it's intertwined)
        assert_eq!(bundles[2].size, 3);
        assert_eq!(bundles[2].bytes[0], 0x20);
        assert_eq!(bundles[2].bytes[1], 0x04);
        assert_eq!(bundles[2].bytes[2], 0x80);
    }

    #[test]
    fn cannot_switch_to_segment_inside_of_scope() {
        let mut asm = Assembler::new(EMPTY.to_vec());
        asm.mappings[0].segments[0].bundles = minimal_header();
        asm.mappings[0].offset = 6;
        asm.current_mapping = 1;
        let res = &asm
            .assemble(
                r#"
.scope Vars
.segment "CODE"
  nop
.endscope
"#
                .as_bytes(),
            )
            .unwrap_err();

        assert_eq!(
            res.first().unwrap().to_string(),
            "Evaluation error (line 3): cannot switch to segment 'CODE' \
             if we are still inside of a scope ('Vars')."
        );
    }

    // TODO: jmp/beq outside of allocated PRG ROM
}