aboutsummaryrefslogtreecommitdiffstats
path: root/src/compiler.c
blob: ee2c06b4e6b76c7e5934773ea9c064f6be8a1dd1 (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
#ifndef COMPILER_C
#define COMPILER_C

#include "badlib.h"

#include "parser.c"

typedef struct Variable {
    Str name;
    Str type;
    sz size;
    sz offset;
    sz idx;
} Variable;

MAPDEF(StrVarMap, varmap, Str, Variable, str_hash, str_eq)

typedef struct Instruction {
    u8 dst;
    u8 a;
    u8 b;
    u8 op;
} Instruction;

typedef union Constant {
    s64 i;
    u64 u;
    f64 f;
    ptrsize ptr;
} Constant;

typedef struct LineCol {
    sz line;
    sz col;
} LineCol;

typedef struct Function {
    Str name;
    sz param_arity;
    sz return_arity;
    sz index;
} Function;

MAPDEF(FunctionMap, funcmap, Str, Function, str_hash, str_eq)

typedef struct Chunk {
    sz id;
    Str name;
    struct Chunk *parent;

    Instruction *code;
    IntIntMap *labels;      // label -> chunk_index
    IntIntMap *labels_rev;  // chunk_index -> label
    sz labels_idx;

    // Constant values that fit in 64 bits.
    Constant *constants;
    IntIntMap *intmap;
    sz const_idx;

    // Constant strings.
    Str *strings;
    StrIntMap *strmap;
    sz str_idx;

    // Global/Local variables.
    Variable *vars;
    StrVarMap *varmap;
    sz var_off;
    sz param_off;

    // Number of registers currently used in this chunk.
    sz reg_idx;

    // Number of functions currently used in this chunk.
    struct Chunk **functions;
    FunctionMap *funmap;
    sz fun_idx;

    // Debugging.
    Str file_name;
    Arena *storage;
    LineCol *linecol;
} Chunk;

typedef enum OpCode {
    //            OP    DST   A   B
    // ---------------------------------------------------------------
    // VM/high level instructions.
    OP_HALT,  // halt
    // NOTE: LDGVAR/STGVAR* could be obtained in terms of LDGADDR.
    OP_STGVARI,  // stgvari vx, ca
    OP_STGVAR,   // stgvar  vx, ra
    OP_LDGVAR,   // ldgvar  rx, va
    OP_LDGADDR,  // ldgaddr rx, va
    OP_STLVARI,  // stlvari vx, ca
    OP_STLVAR,   // stlvar  vx, ra
    OP_LDLVAR,   // ldlvar  rx, va
    OP_LDLADDR,  // ldladdr rx, va
    // Functions.
    OP_CALL,     // call fx        ; Bumps the stack pointer by cx
    OP_RET,      // ret            ; Returns from current function
    OP_RESERVE,  // reserve cx     ; Increments the stack pointer by cx bytes
    OP_POP,      // pop     rx     ; Pops the last value of the stack into rx.
    OP_PUSH,     // push    rx     ; Push the rx value to the stack.
    OP_PUSHI,    // pushi   cx     ; Push the cx value to the stack.
    OP_PUTRET,   // putret  rx     ; Put rx into the return value memory.
    OP_PUTRETI,  // putreti cx     ; Put cx into the return value memory.
    // Printing values with builtin print/println functions.
    OP_PRINTSTR,   // p  rx
    OP_PRINTS64,   // p  rx
    OP_PRINTF64,   // p  rx
    OP_PRINTS64I,  // p  cx
    OP_PRINTF64I,  // p  cx
    // Load/Store instructions.
    OP_LD8K,   // ld8k   rx, ca      -> u8  rx = ca
    OP_LD16K,  // ld16k  rx, ca      -> u16 rx = ca
    OP_LD32K,  // ld32k  rx, ca      -> u32 rx = ca
    OP_LD64K,  // ld64k  rx, ca      -> u64 rx = ca
    OP_LD8I,   // ld8i   rx, ra, cb  -> u8  *p = ra; rx = p[cb]
    OP_LD16I,  // ld16i  rx, ra, cb  -> u16 *p = ra; rx = p[cb]
    OP_LD32I,  // ld32i  rx, ra, cb  -> u32 *p = ra; rx = p[cb]
    OP_LD64I,  // ld64i  rx, ra, cb  -> u64 *p = ra; rx = p[cb]
    OP_LD8,    // ld8    rx, ra, rb  -> u8  *p = ra; rx = p[rb]
    OP_LD16,   // ld16   rx, ra, rb  -> u16 *p = ra; rx = p[rb]
    OP_LD32,   // ld32   rx, ra, rb  -> u32 *p = ra; rx = p[rb]
    OP_LD64,   // ld64   rx, ra, rb  -> u64 *p = ra; rx = p[rb]
    OP_ST8I,   // st8i   rx, ra, cb  -> u8  *p = ra; p[cb] = rx
    OP_ST16I,  // st16i  rx, ra, cb  -> u16 *p = ra; p[cb] = rx
    OP_ST32I,  // st32i  rx, ra, cb  -> u32 *p = ra; p[cb] = rx
    OP_ST64I,  // st64i  rx, ra, cb  -> u64 *p = ra; p[cb] = rx
    OP_ST8,    // st8    rx, ra, rb  -> u8  *p = ra; p[rb] = rx
    OP_ST16,   // st16   rx, ra, rb  -> u16 *p = ra; p[rb] = rx
    OP_ST32,   // st32   rx, ra, rb  -> u32 *p = ra; p[rb] = rx
    OP_ST64,   // st64   rx, ra, rb  -> u64 *p = ra; p[rb] = rx
    // Integer arithmetic (only int/s64 for now).
    OP_ADDI,  // addk   rx, ra, cb
    OP_SUBI,  // subk   rx, ra, cb
    OP_MULI,  // mulk   rx, ra, cb
    OP_DIVI,  // divk   rx, ra, cb
    OP_MODI,  // modk   rx, ra, cb
    OP_ADD,   // add    rx, ra, rb
    OP_SUB,   // sub    rx, ra, rb
    OP_MUL,   // mul    rx, ra, rb
    OP_DIV,   // div    rx, ra, rb
    OP_MOD,   // mod    rx, ra, rb
    // Floating point arithmetic (only f64 for now).
    OP_ADDFI,  // addfk  rx, ra, cb
    OP_SUBFI,  // subfk  rx, ra, cb
    OP_MULFI,  // mulfk  rx, ra, cb
    OP_DIVFI,  // divfk  rx, ra, cb
    OP_MODFI,  // modfk  rx, ra, cb
    OP_ADDF,   // addf   rx, ra, rb
    OP_SUBF,   // subf   rx, ra, rb
    OP_MULF,   // mulf   rx, ra, rb
    OP_DIVF,   // divf   rx, ra, rb
    OP_MODF,   // modf   rx, ra, rb
    // Register-to-register copy.
    OP_MOV8,   // mov8   rx, ra  -> rx = ra & 0xFF
    OP_MOV16,  // mov16  rx, ra  -> rx = ra & 0xFFFF
    OP_MOV32,  // mov32  rx, ra  -> rx = ra & 0xFFFFFFFF
    OP_MOV64,  // mov64  rx, ra  -> rx = ra & 0xFFFFFFFFFFFFFFFF
    // Logic operations (only 64 bits for now).
    OP_EQI,   // eqk   rx, ra, cb
    OP_NEQI,  // neqk   rx, ra, cb
    OP_LTI,   // ltk   rx, ra, cb
    OP_GTI,   // gtk   rx, ra, cb
    OP_LEI,   // lek   rx, ra, cb
    OP_GEI,   // gek   rx, ra, cb
    OP_ANDI,  // andk   rx, ra, cb
    OP_ORI,   // ork    rx, ra, cb
    OP_NOTI,  // noti  rx, ra
    OP_EQ,    // eq    rx, ra, rb
    OP_NEQ,   // neq    rx, ra, rb
    OP_LT,    // lt    rx, ra, rb
    OP_GT,    // gt    rx, ra, rb
    OP_LE,    // le    rx, ra, rb
    OP_GE,    // ge    rx, ra, rb
    OP_AND,   // and   rx, ra, rb
    OP_OR,    // or    rx, ra, rb
    OP_NOT,   // not   rx, ra
    // Bitwise operations.
    OP_BITLSHIFTI,  // shli   rx, ra, cb
    OP_BITRSHIFTI,  // shri   rx, ra, cb
    OP_BITANDI,     // bandi  rx, ra, cb
    OP_BITORI,      // bori   rx, ra, cb
    OP_BITNOTI,     // bnoti  rx, ca
    OP_BITLSHIFT,   // shl    rx, ra, rb
    OP_BITRSHIFT,   // shr    rx, ra, rb
    OP_BITAND,      // band   rx, ra, rb
    OP_BITOR,       // bor    rx, ra, rb
    OP_BITNOT,      // bnot   rx, ra
    // Jump instructions.
    OP_JMP,    // jmp  lx     ; jmp to label lx
    OP_JMPF,   // jmpf lx, rx ; jmp to label lx if rx is false
    OP_JMPT,   // jmpt lx, rx ; jmp to label lx if rx is true
    OP_JMPFI,  // jmpf lx, cx ; jmp to label lx if rx is false
    OP_JMPTI,  // jmpt lx, cx ; jmp to label lx if rx is true
} OpCode;

Str op_str[] = {
    // High level ops.
    [OP_HALT] = cstr("HALT    "),
    [OP_STGVAR] = cstr("STGVAR  "),
    [OP_STGVARI] = cstr("STGVARI "),
    [OP_LDGVAR] = cstr("LDGVAR  "),
    [OP_LDGADDR] = cstr("LDGADDR "),
    [OP_STLVAR] = cstr("STLVAR  "),
    [OP_STLVARI] = cstr("STLVARI "),
    [OP_LDLVAR] = cstr("LDLVAR  "),
    [OP_LDLADDR] = cstr("LDLADDR "),
    [OP_PRINTSTR] = cstr("PRNTSTR "),
    [OP_PRINTS64] = cstr("PRNTS64 "),
    [OP_PRINTF64] = cstr("PRNTF64 "),
    [OP_PRINTS64I] = cstr("PRNTS64I"),
    [OP_PRINTF64I] = cstr("PRNTF64I"),
    [OP_PUTRET] = cstr("PUTRET  "),
    [OP_PUTRETI] = cstr("PUTRETI "),
    // Functions.
    [OP_CALL] = cstr("CALL    "),
    [OP_RET] = cstr("RET     "),
    [OP_RESERVE] = cstr("RESERVE "),
    [OP_POP] = cstr("POP     "),
    [OP_PUSH] = cstr("PUSH    "),
    [OP_PUSHI] = cstr("PUSHI   "),
    // Load ops.
    [OP_LD8K] = cstr("LD8K    "),
    [OP_LD16K] = cstr("LD16K   "),
    [OP_LD32K] = cstr("LD32K   "),
    [OP_LD64K] = cstr("LD64K   "),
    [OP_LD8I] = cstr("LD8I    "),
    [OP_LD16I] = cstr("LD16I   "),
    [OP_LD32I] = cstr("LD32I   "),
    [OP_LD64I] = cstr("LD64I   "),
    [OP_LD8] = cstr("LD8     "),
    [OP_LD16] = cstr("LD16    "),
    [OP_LD32] = cstr("LD32    "),
    [OP_LD64] = cstr("LD64    "),
    // Store ops.
    [OP_ST8I] = cstr("ST8I    "),
    [OP_ST16I] = cstr("ST16I   "),
    [OP_ST32I] = cstr("ST32I   "),
    [OP_ST64I] = cstr("ST64I   "),
    [OP_ST8] = cstr("ST8     "),
    [OP_ST16] = cstr("ST16    "),
    [OP_ST32] = cstr("ST32    "),
    [OP_ST64] = cstr("ST64    "),
    // Arithmetic.
    [OP_ADDI] = cstr("ADDI    "),
    [OP_SUBI] = cstr("SUBI    "),
    [OP_MULI] = cstr("MULI    "),
    [OP_DIVI] = cstr("DIVI    "),
    [OP_MODI] = cstr("MODI    "),
    [OP_ADD] = cstr("ADD     "),
    [OP_SUB] = cstr("SUB     "),
    [OP_MUL] = cstr("MUL     "),
    [OP_DIV] = cstr("DIV     "),
    [OP_MOD] = cstr("MOD     "),
    [OP_ADDFI] = cstr("ADDFI   "),
    [OP_SUBFI] = cstr("SUBFI   "),
    [OP_MULFI] = cstr("MULFI   "),
    [OP_DIVFI] = cstr("DIVFI   "),
    [OP_MODFI] = cstr("MODFI   "),
    [OP_ADDF] = cstr("ADDF    "),
    [OP_SUBF] = cstr("SUBF    "),
    [OP_MULF] = cstr("MULF    "),
    [OP_DIVF] = cstr("DIVF    "),
    // Reg copy/move.
    [OP_MODF] = cstr("MODF    "),
    [OP_MOV8] = cstr("MOV8    "),
    [OP_MOV16] = cstr("MOV16   "),
    [OP_MOV32] = cstr("MOV32   "),
    [OP_MOV64] = cstr("MOV64   "),
    // Logic operations.
    [OP_EQI] = cstr("EQI     "),
    [OP_NEQI] = cstr("NEQI    "),
    [OP_LTI] = cstr("LTI     "),
    [OP_GTI] = cstr("GTI     "),
    [OP_LEI] = cstr("LEI     "),
    [OP_GEI] = cstr("GEI     "),
    [OP_ANDI] = cstr("ANDI    "),
    [OP_ORI] = cstr("ORI     "),
    [OP_NOTI] = cstr("NOTI    "),
    [OP_EQ] = cstr("EQ      "),
    [OP_NEQ] = cstr("NEQ     "),
    [OP_LT] = cstr("LT      "),
    [OP_GT] = cstr("GT      "),
    [OP_LE] = cstr("LE      "),
    [OP_GE] = cstr("GE      "),
    [OP_AND] = cstr("AND     "),
    [OP_OR] = cstr("OR      "),
    [OP_NOT] = cstr("NOT     "),
    // Bitwise operations.
    [OP_BITLSHIFTI] = cstr("LSHI    "),
    [OP_BITRSHIFTI] = cstr("RSHI    "),
    [OP_BITANDI] = cstr("BANDI   "),
    [OP_BITORI] = cstr("BORI    "),
    [OP_BITNOTI] = cstr("BNOTI   "),
    [OP_BITLSHIFT] = cstr("LSH     "),
    [OP_BITRSHIFT] = cstr("RSH     "),
    [OP_BITAND] = cstr("BAND    "),
    [OP_BITOR] = cstr("BOR     "),
    [OP_BITNOT] = cstr("BNOT    "),
    // Jump instructions.
    [OP_JMP] = cstr("JMP     "),
    [OP_JMPF] = cstr("JMPF    "),
    [OP_JMPT] = cstr("JMPT    "),
    [OP_JMPFI] = cstr("JMPFI   "),
    [OP_JMPTI] = cstr("JMPTI   "),
};

typedef enum {
    COMP_NIL,
    COMP_CONST,
    COMP_STRING,
    COMP_REG,
    COMP_RET,
    COMP_ERR,
} CompResultType;

typedef struct CompResult {
    sz idx;
    CompResultType type;
} CompResult;

CompResult compile_expr(Chunk *chunk, Node *node, sz lab_pre, sz lab_post);

#define EMIT_OP(OP, DST, A, B, NODE, CHUNK)                              \
    do {                                                                 \
        Instruction inst = (Instruction){                                \
            .op = (OP),                                                  \
            .dst = (DST),                                                \
            .a = (A),                                                    \
            .b = (B),                                                    \
        };                                                               \
        array_push((CHUNK)->code, inst, (CHUNK)->storage);               \
        LineCol linecol = (LineCol){0};                                  \
        if (NODE) {                                                      \
            Node *_node = (NODE);                                        \
            linecol = (LineCol){.line = _node->line, .col = _node->col}; \
        }                                                                \
        array_push((CHUNK)->linecol, linecol, (CHUNK)->storage);         \
    } while (0)

CompResult
compile_binary(Chunk *chunk, Node *node, sz lab_pre, sz lab_post) {
    OpCode op = OP_HALT;
    OpCode opi = OP_HALT;
    OpCode ldop = OP_LD64K;
    switch (node->kind) {
        // Arithmetic.
        case NODE_ADD: {
            if (str_eq(node->type, cstr("int"))) {
                op = OP_ADD;
                opi = OP_ADDI;
            } else if (str_eq(node->type, cstr("f64"))) {
                op = OP_ADDF;
                opi = OP_ADDFI;
            }
        } break;
        case NODE_SUB: {
            if (str_eq(node->type, cstr("int"))) {
                op = OP_SUB;
                opi = OP_SUBI;
            } else if (str_eq(node->type, cstr("f64"))) {
                op = OP_SUBF;
                opi = OP_SUBFI;
            }
        } break;
        case NODE_MUL: {
            if (str_eq(node->type, cstr("int"))) {
                op = OP_MUL;
                opi = OP_MULI;
            } else if (str_eq(node->type, cstr("f64"))) {
                op = OP_MULF;
                opi = OP_MULFI;
            }
        } break;
        case NODE_DIV: {
            if (str_eq(node->type, cstr("int"))) {
                op = OP_DIV;
                opi = OP_DIVI;
            } else if (str_eq(node->type, cstr("f64"))) {
                op = OP_DIVF;
                opi = OP_DIVFI;
            }
        } break;
        case NODE_MOD: {
            if (str_eq(node->type, cstr("int"))) {
                op = OP_MOD;
                opi = OP_MODI;
            } else if (str_eq(node->type, cstr("f64"))) {
                op = OP_MODF;
                opi = OP_MODFI;
            }
        } break;
        // Logic.
        case NODE_EQ: {
            op = OP_EQ;
            opi = OP_EQI;
        } break;
        case NODE_NEQ: {
            op = OP_NEQ;
            opi = OP_NEQI;
        } break;
        case NODE_LT: {
            op = OP_LT;
            opi = OP_LTI;
        } break;
        case NODE_GT: {
            op = OP_GT;
            opi = OP_GTI;
        } break;
        case NODE_LE: {
            op = OP_LE;
            opi = OP_LEI;
        } break;
        case NODE_GE: {
            op = OP_GE;
            opi = OP_GEI;
        } break;
        case NODE_AND: {
            op = OP_AND;
            opi = OP_ANDI;
        } break;
        case NODE_OR: {
            op = OP_OR;
            opi = OP_ORI;
        } break;
        // Bitwise.
        case NODE_BITOR: {
            op = OP_BITOR;
            opi = OP_BITORI;
        } break;
        case NODE_BITAND: {
            op = OP_BITAND;
            opi = OP_BITANDI;
        } break;
        case NODE_BITLSHIFT: {
            op = OP_BITLSHIFT;
            opi = OP_BITLSHIFTI;
        } break;
        case NODE_BITRSHIFT: {
            op = OP_BITRSHIFT;
            opi = OP_BITRSHIFTI;
        } break;
        default: break;
    }
    CompResult comp_a = compile_expr(chunk, node->left, lab_pre, lab_post);
    CompResult comp_b = compile_expr(chunk, node->right, lab_pre, lab_post);
    sz reg_a;
    sz reg_b;
    switch (comp_a.type) {
        case COMP_CONST: {
            reg_a = chunk->reg_idx++;
            EMIT_OP(ldop, reg_a, comp_a.idx, 0, node, chunk);
        } break;
        case COMP_REG: {
            reg_a = comp_a.idx;
        } break;
        default: {
            return (CompResult){.type = COMP_ERR};
        } break;
    }
    switch (comp_b.type) {
        case COMP_CONST: {
            reg_b = comp_b.idx;
            op = opi;
        } break;
        case COMP_REG: {
            reg_b = comp_b.idx;
        } break;
        default: {
            return (CompResult){.type = COMP_ERR};
        } break;
    }
    sz reg_dst = chunk->reg_idx++;  // Better for optimization
    EMIT_OP(op, reg_dst, reg_a, reg_b, node, chunk);
    return (CompResult){.type = COMP_REG, .idx = reg_dst};
}

CompResult
compile_unary(Chunk *chunk, Node *node, sz lab_pre, sz lab_post) {
    OpCode op = OP_HALT;
    OpCode opi = OP_HALT;
    switch (node->kind) {
        case NODE_NOT: {
            op = OP_NOT;
            opi = OP_NOTI;
        } break;
        case NODE_BITNOT: {
            op = OP_BITNOT;
            opi = OP_BITNOTI;
        } break;
        default: break;
    }
    CompResult comp_a = compile_expr(chunk, node->left, lab_pre, lab_post);
    sz reg_a;
    switch (comp_a.type) {
        case COMP_CONST: {
            reg_a = comp_a.idx;
            op = opi;
        } break;
        case COMP_REG: {
            reg_a = comp_a.idx;
        } break;
        default: {
            return (CompResult){.type = COMP_ERR};
        } break;
    }
    sz reg_dst = chunk->reg_idx++;
    EMIT_OP(op, reg_dst, reg_a, 0, node, chunk);
    return (CompResult){.type = COMP_REG, .idx = reg_dst};
}

sz
add_constant(Chunk *chunk, sz value) {
    IntIntMap *map = intintmap_lookup(&chunk->intmap, value);
    // Make sure we don't have duplicated constants.
    if (!map) {
        map = intintmap_insert(&chunk->intmap, value, chunk->const_idx++,
                               chunk->storage);
        Constant c = (Constant){.i = value};
        array_push(chunk->constants, c, chunk->storage);
    }
    return map->val;
}

sz
add_string(Chunk *chunk, Str string) {
    // Make sure we don't have duplicated string.
    StrIntMap *map = strintmap_lookup(&chunk->strmap, string);
    if (!map) {
        map = strintmap_insert(&chunk->strmap, string, chunk->str_idx++,
                               chunk->storage);
        array_push(chunk->strings, string, chunk->storage);
    }
    return map->val;
}

sz
add_variable(Chunk *chunk, Str name, Str type, sz arr_size) {
    sz idx = array_size(chunk->vars);
    sz size = 8;
    // TODO: get type storage from a table to consider all the basic
    // types as well as user defined ones.
    if (str_eq(type, cstr("str"))) {
        size = 16;
    }
    if (arr_size) {
        // TODO: get the proper storage size for the multiplication.
        size *= arr_size;
        // FIXME: this should be done on the static analysis, plus,
        // we shouldn't be checking all these types by hand, but
        // using the symbol tables.
        type = str_remove_prefix(type, cstr("@"));
        type = str_concat(cstr("[]"), type, chunk->storage);
    }
    Variable var = (Variable){
        .name = name,
        .type = type,
        .size = size,
        .offset = chunk->var_off,
        .idx = idx,
    };
    varmap_insert(&chunk->varmap, name, var, chunk->storage);
    array_push(chunk->vars, var, chunk->storage);
    chunk->var_off += size;
    return idx;
}

CompResult
compile_if(Chunk *chunk, Node *node, sz lab_pre, sz lab_post) {
    CompResult cond = compile_expr(chunk, node->cond_if, lab_pre, lab_post);
    OpCode jmpop;
    switch (cond.type) {
        case COMP_CONST: {
            jmpop = OP_JMPFI;
        } break;
        case COMP_REG: {
            jmpop = OP_JMPF;
        } break;
        default: {
            return (CompResult){.type = COMP_ERR};
        } break;
    }

    if (!str_eq(node->type, cstr("nil")) &&
        !str_has_prefix(node->type, cstr("ret:")) &&
        !str_has_prefix(node->type, cstr("flow:"))) {
        sz reg_dst = chunk->reg_idx++;

        // Jump to the `false` branch.
        sz lab0 = chunk->labels_idx++;
        EMIT_OP(jmpop, lab0, cond.idx, 0, node->cond_if, chunk);

        // Condition is true.
        CompResult then_expr =
            compile_expr(chunk, node->cond_expr, lab_pre, lab_post);
        switch (then_expr.type) {
            case COMP_CONST: {
                EMIT_OP(OP_LD64K, reg_dst, then_expr.idx, 0, node->cond_if,
                        chunk);
            } break;
            case COMP_REG: {
                EMIT_OP(OP_MOV64, reg_dst, then_expr.idx, 0, node->cond_if,
                        chunk);
            } break;
            case COMP_RET: break;
            default: {
                return (CompResult){.type = COMP_ERR};
            } break;
        }

        // Jump to the end of the expression.
        sz pos0 = array_size(chunk->code);
        sz lab1 = chunk->labels_idx++;
        EMIT_OP(OP_JMP, lab1, 0, 0, node->cond_else, chunk);

        // Else expression.
        CompResult else_expr =
            compile_expr(chunk, node->cond_else, lab_pre, lab_post);
        switch (else_expr.type) {
            case COMP_CONST: {
                EMIT_OP(OP_LD64K, reg_dst, else_expr.idx, 0, node->cond_else,
                        chunk);
            } break;
            case COMP_REG: {
                EMIT_OP(OP_MOV64, reg_dst, else_expr.idx, 0, node->cond_else,
                        chunk);
            } break;
            case COMP_RET: break;
            default: {
                return (CompResult){.type = COMP_ERR};
            } break;
        }
        sz pos1 = array_size(chunk->code);

        // Update labels.
        intintmap_insert(&chunk->labels, lab0, pos0 + 1, chunk->storage);
        intintmap_insert(&chunk->labels, lab1, pos1, chunk->storage);
        intintmap_insert(&chunk->labels_rev, pos0 + 1, lab0, chunk->storage);
        intintmap_insert(&chunk->labels_rev, pos1, lab1, chunk->storage);
        return (CompResult){.type = COMP_REG, .idx = reg_dst};
    }

    // Jump to the `false` branch.
    sz lab0 = chunk->labels_idx++;
    EMIT_OP(jmpop, lab0, cond.idx, 0, node->cond_if, chunk);

    // Condition is true.
    compile_expr(chunk, node->cond_expr, lab_pre, lab_post);

    // Jump to the end of the expression.
    sz pos0 = array_size(chunk->code);
    sz lab1 = chunk->labels_idx++;
    EMIT_OP(OP_JMP, lab1, 0, 0, node->cond_else, chunk);

    // Else expression.
    if (node->cond_else) {
        compile_expr(chunk, node->cond_else, lab_pre, lab_post);
    }
    sz pos1 = array_size(chunk->code);

    // Update labels.
    intintmap_insert(&chunk->labels, lab0, pos0 + 1, chunk->storage);
    intintmap_insert(&chunk->labels_rev, pos0 + 1, lab0, chunk->storage);
    intintmap_insert(&chunk->labels, lab1, pos1, chunk->storage);
    intintmap_insert(&chunk->labels_rev, pos1, lab1, chunk->storage);

    return (CompResult){.type = COMP_NIL};
}

CompResult
compile_cond(Chunk *chunk, Node *node, sz lab_pre, sz lab_post) {
    if (str_eq(node->type, cstr("nil"))) {
        sz lab1 = chunk->labels_idx++;
        for (sz i = 0; i < array_size(node->match_cases); i++) {
            // condition = expression
            Node *expr = node->match_cases[i];
            if (expr->case_value) {
                CompResult cond =
                    compile_expr(chunk, expr->case_value, lab_pre, lab_post);
                OpCode jmpop;
                switch (cond.type) {
                    case COMP_CONST: {
                        jmpop = OP_JMPFI;
                    } break;
                    case COMP_REG: {
                        jmpop = OP_JMPF;
                    } break;
                    default: {
                        return (CompResult){.type = COMP_ERR};
                    } break;
                }
                // Jump to the `next` branch.
                sz lab0 = chunk->labels_idx++;
                EMIT_OP(jmpop, lab0, cond.idx, 0, expr->case_expr, chunk);

                // Condition is true.
                compile_expr(chunk, expr->case_expr, lab_pre, lab_post);
                if (i != array_size(node->match_cases) - 1) {
                    // Jump to the end of the expression.
                    sz pos0 = array_size(chunk->code);
                    EMIT_OP(OP_JMP, lab1, 0, 0, node->cond_else, chunk);
                    intintmap_insert(&chunk->labels, lab0, pos0 + 1,
                                     chunk->storage);
                    intintmap_insert(&chunk->labels_rev, pos0 + 1, lab0,
                                     chunk->storage);
                }
            } else {
                compile_expr(chunk, expr->case_expr, lab_pre, lab_post);
                break;
            }
        }
        sz pos1 = array_size(chunk->code);
        intintmap_insert(&chunk->labels, lab1, pos1, chunk->storage);
        intintmap_insert(&chunk->labels_rev, pos1, lab1, chunk->storage);
        return (CompResult){.type = COMP_NIL};
    }

    sz reg_dst = chunk->reg_idx++;
    sz lab1 = chunk->labels_idx++;
    for (sz i = 0; i < array_size(node->match_cases); i++) {
        // condition = expression
        Node *expr = node->match_cases[i];
        if (expr->case_value) {
            CompResult cond =
                compile_expr(chunk, expr->case_value, lab_pre, lab_post);
            OpCode jmpop;
            switch (cond.type) {
                case COMP_CONST: {
                    jmpop = OP_JMPFI;
                } break;
                case COMP_REG: {
                    jmpop = OP_JMPF;
                } break;
                default: {
                    return (CompResult){.type = COMP_ERR};
                } break;
            }
            // Jump to the `next` branch.
            sz lab0 = chunk->labels_idx++;
            EMIT_OP(jmpop, lab0, cond.idx, 0, expr->case_expr, chunk);

            // Condition is true.
            CompResult then_expr =
                compile_expr(chunk, expr->case_expr, lab_pre, lab_post);
            switch (then_expr.type) {
                case COMP_CONST: {
                    EMIT_OP(OP_LD64K, reg_dst, then_expr.idx, 0,
                            expr->case_expr, chunk);
                } break;
                case COMP_REG: {
                    EMIT_OP(OP_MOV64, reg_dst, then_expr.idx, 0,
                            expr->case_expr, chunk);
                } break;
                case COMP_RET: break;
                default: {
                    return (CompResult){.type = COMP_ERR};
                } break;
            }
            if (i != array_size(node->match_cases) - 1) {
                // Jump to the end of the expression.
                sz pos0 = array_size(chunk->code);
                EMIT_OP(OP_JMP, lab1, 0, 0, node->cond_else, chunk);
                intintmap_insert(&chunk->labels, lab0, pos0 + 1,
                                 chunk->storage);
                intintmap_insert(&chunk->labels_rev, pos0 + 1, lab0,
                                 chunk->storage);
            }
        } else {
            CompResult then_expr =
                compile_expr(chunk, expr->case_expr, lab_pre, lab_post);
            switch (then_expr.type) {
                case COMP_CONST: {
                    EMIT_OP(OP_LD64K, reg_dst, then_expr.idx, 0,
                            expr->case_expr, chunk);
                } break;
                case COMP_REG: {
                    EMIT_OP(OP_MOV64, reg_dst, then_expr.idx, 0,
                            expr->case_expr, chunk);
                } break;
                case COMP_RET: break;
                default: {
                    return (CompResult){.type = COMP_ERR};
                } break;
            }
            break;
        }
    }
    sz pos1 = array_size(chunk->code);
    intintmap_insert(&chunk->labels, lab1, pos1, chunk->storage);
    intintmap_insert(&chunk->labels_rev, pos1, lab1, chunk->storage);
    return (CompResult){.type = COMP_REG, .idx = reg_dst};
}

CompResult
compile_break(Chunk *chunk, Node *node, sz lab_pre, sz lab_post) {
    (void)lab_pre;
    EMIT_OP(OP_JMP, lab_post, 0, 0, node, chunk);
    return (CompResult){.type = COMP_NIL};
}

CompResult
compile_continue(Chunk *chunk, Node *node, sz lab_pre, sz lab_post) {
    (void)lab_post;
    EMIT_OP(OP_JMP, lab_pre, 0, 0, node, chunk);
    return (CompResult){.type = COMP_NIL};
}

CompResult
compile_while(Chunk *chunk, Node *node, sz lab_pre, sz lab_post) {
    sz lab0 = chunk->labels_idx++;
    sz lab1 = chunk->labels_idx++;
    sz pos1 = array_size(chunk->code);
    CompResult cond = compile_expr(chunk, node->while_cond, lab_pre, lab_post);
    OpCode jmpop;
    switch (cond.type) {
        case COMP_CONST: {
            jmpop = OP_JMPFI;
        } break;
        case COMP_REG: {
            jmpop = OP_JMPF;
        } break;
        default: {
            return (CompResult){.type = COMP_ERR};
        } break;
    }

    // Jump to the `end of the loop` branch.
    EMIT_OP(jmpop, lab0, cond.idx, 0, node->while_cond, chunk);

    // Condition is true.
    compile_expr(chunk, node->while_expr, lab1, lab0);
    sz pos0 = array_size(chunk->code);
    EMIT_OP(OP_JMP, lab1, 0, 0, node, chunk);

    // Update labels.
    intintmap_insert(&chunk->labels, lab0, pos0 + 1, chunk->storage);
    intintmap_insert(&chunk->labels_rev, pos0 + 1, lab0, chunk->storage);
    intintmap_insert(&chunk->labels, lab1, pos1, chunk->storage);
    intintmap_insert(&chunk->labels_rev, pos1, lab1, chunk->storage);

    // Return.
    return (CompResult){.type = COMP_NIL};
}

CompResult
compile_funcall(Chunk *chunk, Node *node, sz lab_pre, sz lab_post) {
    Str name = node->value.str;

    // Builtins.
    if (str_eq(name, cstr("print")) || str_eq(name, cstr("println"))) {
        for (sz i = 0; i < array_size(node->elements); i++) {
            Node *expr = node->elements[i];
            CompResult result = compile_expr(chunk, expr, lab_pre, lab_post);
            if (str_eq(expr->type, cstr("int"))) {
                switch (result.type) {
                    case COMP_CONST: {
                        EMIT_OP(OP_PRINTS64I, result.idx, 0, 0, expr, chunk);
                    } break;
                    case COMP_REG: {
                        EMIT_OP(OP_PRINTS64, result.idx, 0, 0, expr, chunk);
                    } break;
                    default: {
                        return (CompResult){.type = COMP_ERR};
                    } break;
                }
            } else if (str_eq(expr->type, cstr("f64"))) {
                switch (result.type) {
                    case COMP_CONST: {
                        EMIT_OP(OP_PRINTF64I, result.idx, 0, 0, expr, chunk);
                    } break;
                    case COMP_REG: {
                        EMIT_OP(OP_PRINTF64, result.idx, 0, 0, expr, chunk);
                    } break;
                    default: {
                        return (CompResult){.type = COMP_ERR};
                    } break;
                }
            } else if (str_eq(expr->type, cstr("str"))) {
                switch (result.type) {
                    case COMP_STRING: {
                        EMIT_OP(OP_PRINTSTR, result.idx, 0, 0, expr, chunk);
                    } break;
                    default: {
                        return (CompResult){.type = COMP_ERR};
                    } break;
                }
            }
        }
        if (str_eq(name, cstr("println"))) {
            sz idx = add_string(chunk, cstr("\n"));
            EMIT_OP(OP_PRINTSTR, idx, 0, 0, node, chunk);
        }
        return (CompResult){.type = COMP_NIL};
    }

    // TODO: need to find this on the parents, not just in the current chunk.
    FunctionMap *map = funcmap_lookup(&chunk->funmap, node->unique_name);
    if (!map) {
        println("how come?");
        exit(EXIT_FAILURE);
    }
    Function fun = map->val;

    // Reserve space for the return value if needed.
    if (fun.return_arity > 0) {
        // Put the return data into a register
        sz ret_size = add_constant(chunk, 8);
        EMIT_OP(OP_RESERVE, ret_size, 0, 0, node, chunk);
    }

    // Send parameters to the stack.
    for (sz i = 0; i < array_size(node->elements); i++) {
        Node *expr = node->elements[i];
        CompResult result = compile_expr(chunk, expr, lab_pre, lab_post);
        // TODO: Assuming all values are 8 bytes... again.
        switch (result.type) {
            case COMP_CONST: {
                EMIT_OP(OP_PUSHI, result.idx, 0, 0, expr, chunk);
            } break;
            case COMP_REG: {
                EMIT_OP(OP_PUSH, result.idx, 0, 0, expr, chunk);
            } break;
            default: {
                return (CompResult){.type = COMP_ERR};
            } break;
        }
    }

    EMIT_OP(OP_CALL, fun.index, 0, 0, node, chunk);

    // Only one return parameter for now.
    if (fun.return_arity > 0) {
        // Put the return data into a register
        sz reg_dst = chunk->reg_idx++;
        EMIT_OP(OP_POP, reg_dst, 0, 0, node, chunk);
        return (CompResult){.type = COMP_REG, .idx = reg_dst};
    }

    return (CompResult){.type = COMP_NIL};
}

CompResult
compile_return(Chunk *chunk, Node *node, sz lab_pre, sz lab_post) {
    for (sz i = 0; i < array_size(node->elements); i++) {
        Node *expr = node->elements[i];
        CompResult res = compile_expr(chunk, expr, lab_pre, lab_post);

        // TODO: Only one return field for now, but this is the idea.
        // Put return values into memory.
        switch (res.type) {
            case COMP_CONST: {
                EMIT_OP(OP_PUTRETI, res.idx, 0, 0, node, chunk);
            } break;
            case COMP_REG: {
                EMIT_OP(OP_PUTRET, res.idx, 0, 0, node, chunk);
            } break;
            default: {
                return (CompResult){.type = COMP_ERR};
            } break;
        }
        break;
    }

    EMIT_OP(OP_RET, 0, 0, 0, node, chunk);
    return (CompResult){.type = COMP_RET};
}

Chunk *
chunk_alloc(Chunk *parent) {
    static sz chunk_idx = 1;
    Chunk *chunk = arena_calloc((sz)sizeof(Chunk), parent->storage);
    chunk->parent = parent;
    chunk->id = chunk_idx++;
    chunk->storage = parent->storage;
    chunk->file_name = parent->file_name;
    return chunk;
}

CompResult
compile_function(Chunk *chunk, Node *node, sz lab_pre, sz lab_post) {
    // The current activation record procedure for the VM is as follows:
    //
    // [caller][callee                                                ]
    // [ .... ][ RET VAL ][ PARAMS ][ LOCALS ][ REGISTERS ][ RET META ]
    //                    ^
    //                    frame pointer
    //
    //  The caller is responsible for allocating the return memory and the
    //  parameter memory and filling the param data before OP_CALL.
    //
    Chunk *func = chunk_alloc(chunk);
    func->name = node->unique_name;
    Function fun = (Function){
        .name = func->name,
        .index = chunk->fun_idx++,
        .param_arity = array_size(node->func_params),
        .return_arity = array_size(node->func_ret),
    };
    funcmap_insert(&chunk->funmap, func->name, fun, chunk->storage);
    array_push(chunk->functions, func, chunk->storage);

    // Push arguments as locals.
    for (sz i = 0; i < array_size(node->func_params); i++) {
        Node *param = node->func_params[i];
        Str name = param->unique_name;
        Str type = param->type;
        sz arr_size = 0;
        if (str_has_prefix(type, cstr("@"))) {
            if (param->var_type && param->var_type->kind == NODE_ARR_TYPE &&
                param->var_type->arr_size->value.i > 0) {
                arr_size = param->var_type->arr_size->value.i;
            }
        }
        add_variable(func, name, type, arr_size);
    }
    func->param_off = func->var_off;

    // Compiling the body.
    CompResult res = compile_expr(func, node->func_body, lab_pre, lab_post);

    // Put return values into memory.
    switch (res.type) {
        case COMP_CONST: {
            EMIT_OP(OP_PUTRETI, res.idx, 0, 0, node, func);
        } break;
        case COMP_REG: {
            EMIT_OP(OP_PUTRET, res.idx, 0, 0, node, func);
        } break;
        default: break;
    }

    // TODO: handle captured locals/globals?
    EMIT_OP(OP_RET, 0, 0, 0, node, func);
    return (CompResult){.type = COMP_NIL};
}

CompResult
compile_expr(Chunk *chunk, Node *node, sz lab_pre, sz lab_post) {
    switch (node->kind) {
        case NODE_BREAK: return compile_break(chunk, node, lab_pre, lab_post);
        case NODE_CONTINUE:
            return compile_continue(chunk, node, lab_pre, lab_post);
        case NODE_RETURN: return compile_return(chunk, node, lab_pre, lab_post);
        case NODE_FUN: return compile_function(chunk, node, lab_pre, lab_post);
        case NODE_FUNCALL:
            return compile_funcall(chunk, node, lab_pre, lab_post);
        case NODE_WHILE: return compile_while(chunk, node, lab_pre, lab_post);
        case NODE_IF: return compile_if(chunk, node, lab_pre, lab_post);
        case NODE_COND: return compile_cond(chunk, node, lab_pre, lab_post);
        // Logic.
        // case NODE_XOR:
        case NODE_BITNOT:
        case NODE_NOT:
            return compile_unary(chunk, node, lab_pre, lab_post);
            break;
        case NODE_AND:
        case NODE_OR:
        case NODE_EQ:
        case NODE_NEQ:
        case NODE_LT:
        case NODE_GT:
        case NODE_LE:
        // Bitwise ops.
        case NODE_BITAND:
        case NODE_BITOR:
        case NODE_BITLSHIFT:
        case NODE_BITRSHIFT:
        // Arithmetic.
        case NODE_GE:
        case NODE_ADD:
        case NODE_SUB:
        case NODE_MUL:
        case NODE_DIV:
        case NODE_MOD:
            return compile_binary(chunk, node, lab_pre, lab_post);
            break;
        case NODE_TRUE:
        case NODE_FALSE:
        case NODE_NUM_FLOAT:
        case NODE_NUM_UINT:
        case NODE_NUM_INT: {
            sz value = node->value.i;
            sz const_idx = add_constant(chunk, value);
            return (CompResult){
                .type = COMP_CONST,
                .idx = const_idx,
            };
        } break;
        case NODE_STRING: {
            Str string = node->value.str;
            sz str_idx = add_string(chunk, string);
            return (CompResult){
                .type = COMP_STRING,
                .idx = str_idx,
            };
        } break;
        case NODE_LET: {
            u8 op_stvari = OP_STGVARI;
            u8 op_stvar = OP_STGVAR;
            if (!str_eq(chunk->name, cstr(".main"))) {
                op_stvari = OP_STLVARI;
                op_stvar = OP_STLVAR;
            }
            Str name = node->unique_name;
            Str type = node->var_name->type;
            sz arr_size = 0;
            if (str_has_prefix(type, cstr("@"))) {
                if (node->var_type && node->var_type->kind == NODE_ARR_TYPE &&
                    node->var_type->arr_size->value.i > 0) {
                    arr_size = node->var_type->arr_size->value.i;
                }
            }

            sz idx = add_variable(chunk, name, type, arr_size);

            // Value.
            if (node->var_val) {
                CompResult res =
                    compile_expr(chunk, node->var_val, lab_pre, lab_post);
                switch (res.type) {
                    case COMP_CONST: {
                        EMIT_OP(op_stvari, idx, res.idx, 0, node->var_val,
                                chunk);
                    } break;
                    case COMP_REG: {
                        EMIT_OP(op_stvar, idx, res.idx, 0, node->var_val,
                                chunk);
                    } break;
                    default: {
                        return (CompResult){.type = COMP_ERR};
                    } break;
                }
            }

            return (CompResult){.type = COMP_NIL};
        } break;
        case NODE_SET: {
            Str name = node->unique_name;
            StrVarMap *map = NULL;
            Chunk *next = chunk;
            while (next) {
                map = varmap_lookup(&next->varmap, name);
                if (map) {
                    break;
                }
                next = chunk->parent;
            }
            if (!map) {
                println("error: unreachable symbol name: %s", name);
                exit(EXIT_FAILURE);
            }
            u8 op_ldaddr = OP_LDGADDR;
            u8 op_ldvar = OP_LDGVAR;
            u8 op_stvari = OP_STGVARI;
            u8 op_stvar = OP_STGVAR;
            if (!str_eq(next->name, cstr(".main"))) {
                op_ldaddr = OP_LDLADDR;
                op_ldvar = OP_LDLVAR;
                op_stvari = OP_STLVARI;
                op_stvar = OP_STLVAR;
            }
            CompResult res =
                compile_expr(chunk, node->var_val, lab_pre, lab_post);
            if (node->var_name->kind == NODE_SYMBOL_IDX) {
                // Value.
                sz reg_val;
                switch (res.type) {
                    case COMP_CONST: {
                        reg_val = chunk->reg_idx++;
                        EMIT_OP(OP_LD64K, reg_val, res.idx, 0, node, chunk);
                    } break;
                    case COMP_REG: {
                        reg_val = res.idx;
                    } break;
                    default: {
                        return (CompResult){.type = COMP_ERR};
                    } break;
                }

                // Address.
                sz reg_addr = chunk->reg_idx++;
                // Is this a pointer access or an array access?
                if (str_has_prefix(map->val.type, cstr("[]"))) {
                    EMIT_OP(op_ldaddr, reg_addr, map->val.idx, 0, node->var_val,
                            chunk);
                } else {
                    EMIT_OP(op_ldvar, reg_addr, map->val.idx, 0, node->var_val,
                            chunk);
                }

                // Index.
                CompResult idx = compile_expr(chunk, node->var_name->arr_size,
                                              lab_pre, lab_post);
                switch (idx.type) {
                    case COMP_CONST: {
                        EMIT_OP(OP_ST64I, reg_val, reg_addr, idx.idx, node,
                                chunk);
                    } break;
                    case COMP_REG: {
                        EMIT_OP(OP_ST64, reg_val, reg_addr, idx.idx, node,
                                chunk);
                    } break;
                    default: {
                        return (CompResult){.type = COMP_ERR};
                    } break;
                }
                // TODO: offset should be in bytes, in this case we are assuming
                // 64bit types, hence ST64
                return (CompResult){.type = COMP_NIL};
            }
            switch (res.type) {
                case COMP_CONST: {
                    EMIT_OP(op_stvari, map->val.idx, res.idx, 0, node->var_val,
                            chunk);
                } break;
                case COMP_REG: {
                    EMIT_OP(op_stvar, map->val.idx, res.idx, 0, node->var_val,
                            chunk);
                } break;
                default: {
                    return (CompResult){.type = COMP_ERR};
                } break;
            }
            return (CompResult){.type = COMP_NIL};
        } break;
        case NODE_SYMBOL: {
            Str name = node->unique_name;
            StrVarMap *map = NULL;
            Chunk *next = chunk;
            while (next) {
                map = varmap_lookup(&next->varmap, name);
                if (map) {
                    break;
                }
                next = chunk->parent;
            }
            if (!map) {
                println("error: unreachable symbol name: %s", name);
                exit(EXIT_FAILURE);
            }
            u8 op_ldaddr = OP_LDGADDR;
            u8 op_ldvar = OP_LDGVAR;
            if (!str_eq(next->name, cstr(".main"))) {
                op_ldaddr = OP_LDLADDR;
                op_ldvar = OP_LDLVAR;
            }
            Variable var = map->val;
            u8 reg_dst = chunk->reg_idx++;
            if (node->is_ptr || str_has_prefix(var.type, cstr("[]"))) {
                EMIT_OP(op_ldaddr, reg_dst, var.idx, 0, node, chunk);
            } else {
                EMIT_OP(op_ldvar, reg_dst, var.idx, 0, node, chunk);
            }
            return (CompResult){.type = COMP_REG, .idx = reg_dst};
        } break;
        case NODE_SYMBOL_IDX: {
            Str name = node->unique_name;
            StrVarMap *map = NULL;
            Chunk *next = chunk;
            while (next) {
                map = varmap_lookup(&next->varmap, name);
                if (map) {
                    break;
                }
                next = chunk->parent;
            }
            if (!map) {
                println("error: unreachable symbol name: %s", name);
                exit(EXIT_FAILURE);
            }
            u8 op_ldaddr = OP_LDGADDR;
            u8 op_ldvar = OP_LDGVAR;
            if (!str_eq(next->name, cstr(".main"))) {
                op_ldaddr = OP_LDLADDR;
                op_ldvar = OP_LDLVAR;
            }

            // Destination.
            u8 reg_dst = chunk->reg_idx++;

            // Address.
            sz reg_addr = chunk->reg_idx++;
            if (str_has_prefix(map->val.type, cstr("[]"))) {
                EMIT_OP(op_ldaddr, reg_addr, map->val.idx, 0, node->var_val,
                        chunk);
            } else {
                EMIT_OP(op_ldvar, reg_addr, map->val.idx, 0, node->var_val,
                        chunk);
            }

            // Index.
            CompResult idx =
                compile_expr(chunk, node->arr_size, lab_pre, lab_post);
            switch (idx.type) {
                case COMP_CONST: {
                    EMIT_OP(OP_LD64I, reg_dst, reg_addr, idx.idx, node, chunk);
                } break;
                case COMP_REG: {
                    EMIT_OP(OP_LD64, reg_dst, reg_addr, idx.idx, node, chunk);
                } break;
                default: {
                    return (CompResult){.type = COMP_ERR};
                } break;
            }
            // TODO: hardcoding the type size for now (LD64/LD64I).
            return (CompResult){.type = COMP_REG, .idx = reg_dst};
        } break;
        case NODE_BLOCK: {
            CompResult res;
            for (sz i = 0; i < array_size(node->elements); i++) {
                Node *root = node->elements[i];
                res = compile_expr(chunk, root, lab_pre, lab_post);
            }
            return res;
        } break;
        default: {
            eprintln("error: compilation not implemented for node %s",
                     node_str[node->kind]);
            exit(EXIT_FAILURE);
        } break;
    }
    return (CompResult){.type = COMP_ERR};
}

void
disassemble_instruction(Instruction instruction) {
    switch (instruction.op) {
        case OP_CALL:
            println("%s f%d", op_str[instruction.op], instruction.dst,
                    instruction.a, instruction.b);
            break;
        case OP_MOV8:
        case OP_MOV16:
        case OP_MOV32:
        case OP_MOV64:
            println("%s r%d, r%d", op_str[instruction.op], instruction.dst,
                    instruction.a, instruction.b);
            break;
        case OP_JMPF:
        case OP_JMPT:
            println("%s l%d, r%d", op_str[instruction.op], instruction.dst,
                    instruction.a, instruction.b);
            break;
        case OP_LD8K:
        case OP_LD16K:
        case OP_LD32K:
        case OP_LD64K:
            println("%s r%d, c%d", op_str[instruction.op], instruction.dst,
                    instruction.a, instruction.b);
            break;
        case OP_LD8I:
        case OP_LD16I:
        case OP_LD32I:
        case OP_LD64I:
        case OP_ST8I:
        case OP_ST16I:
        case OP_ST32I:
        case OP_ST64I:
        case OP_ADDI:
        case OP_SUBI:
        case OP_MULI:
        case OP_DIVI:
        case OP_MODI:
        case OP_ADDFI:
        case OP_SUBFI:
        case OP_MULFI:
        case OP_DIVFI:
        case OP_MODFI:
        case OP_EQI:
        case OP_NEQI:
        case OP_LTI:
        case OP_GTI:
        case OP_LEI:
        case OP_GEI:
        case OP_ANDI:
        case OP_ORI:
        case OP_BITLSHIFTI:
        case OP_BITRSHIFTI:
        case OP_BITANDI:
        case OP_BITORI:
            println("%s r%d, r%d, c%d", op_str[instruction.op], instruction.dst,
                    instruction.a, instruction.b);
            break;
        case OP_LD8:
        case OP_LD16:
        case OP_LD32:
        case OP_LD64:
        case OP_ST8:
        case OP_ST16:
        case OP_ST32:
        case OP_ST64:
        case OP_ADD:
        case OP_SUB:
        case OP_MUL:
        case OP_DIV:
        case OP_MOD:
        case OP_ADDF:
        case OP_SUBF:
        case OP_MULF:
        case OP_DIVF:
        case OP_MODF:
        case OP_EQ:
        case OP_NEQ:
        case OP_LT:
        case OP_GT:
        case OP_LE:
        case OP_GE:
        case OP_AND:
        case OP_OR:
        case OP_BITLSHIFT:
        case OP_BITRSHIFT:
        case OP_BITAND:
        case OP_BITOR:
            println("%s r%d, r%d, r%d", op_str[instruction.op], instruction.dst,
                    instruction.a, instruction.b);
            break;
        case OP_LDGVAR:
        case OP_LDGADDR:
        case OP_LDLVAR:
        case OP_LDLADDR:
            println("%s r%d, v%d", op_str[instruction.op], instruction.dst,
                    instruction.a, instruction.b);
            break;
        case OP_STGVAR:
        case OP_STLVAR:
            println("%s v%d, r%d", op_str[instruction.op], instruction.dst,
                    instruction.a, instruction.b);
            break;
        case OP_STGVARI:
        case OP_STLVARI:
            println("%s v%d, c%d", op_str[instruction.op], instruction.dst,
                    instruction.a, instruction.b);
            break;
        case OP_BITNOTI:
        case OP_NOTI:
            println("%s r%d, c%d", op_str[instruction.op], instruction.dst,
                    instruction.a, instruction.b);
            break;
        case OP_BITNOT:
        case OP_NOT:
            println("%s r%d, r%d", op_str[instruction.op], instruction.dst,
                    instruction.a, instruction.b);
            break;
        case OP_JMP:
            println("%s l%d", op_str[instruction.op], instruction.dst,
                    instruction.a, instruction.b);
            break;
        case OP_JMPFI:
        case OP_JMPTI:
            println("%s l%d, c%d", op_str[instruction.op], instruction.dst,
                    instruction.a, instruction.b);
            break;
        case OP_PRINTS64:
        case OP_PRINTF64:
        case OP_PRINTSTR:
        case OP_PUSH:
        case OP_POP:
        case OP_PUTRET:
            println("%s r%d", op_str[instruction.op], instruction.dst,
                    instruction.a, instruction.b);
            break;
        case OP_PRINTS64I:
        case OP_PRINTF64I:
        case OP_RESERVE:
        case OP_PUSHI:
        case OP_PUTRETI:
            println("%s c%d", op_str[instruction.op], instruction.dst,
                    instruction.a, instruction.b);
            break;
        case OP_RET:
        case OP_HALT: println("%s", op_str[instruction.op]); break;
        default: println("Unknown opcode %d", instruction.op); break;
    }
}

void
disassemble_chunk(Chunk chunk) {
    println("CHUNK %d: %s%s", chunk.id, chunk.file_name, chunk.name);
    println("n_regs: %d, n_vars: %d, n_strings: %d, n_consts: %d",
            chunk.reg_idx, array_size(chunk.vars), chunk.str_idx,
            chunk.const_idx);
    println("================== code ==================");
    println(" LINE:COL  INUM LABELS OP       OPERANDS  ");
    println("------------------------------------------");
    for (sz i = 0; i < array_size(chunk.code); i++) {
        printf(" %.4ld:%.4ld %.4lx ", chunk.linecol[i].line,
               chunk.linecol[i].col, i);
        IntIntMap *label = intintmap_lookup(&chunk.labels_rev, i);
        if (label) {
            printf(".L%.2ld   ", label->val);
        } else {
            printf("  %2s   ", "");
        }
        disassemble_instruction(chunk.code[i]);
    }
    if (array_size(chunk.constants) > 0) {
        println("================ constants ===============", chunk.file_name);
        for (sz i = 0; i < array_size(chunk.constants); i++) {
            println(" %x{2}:  %x{8}", i, chunk.constants[i]);
        }
    }
    if (array_size(chunk.strings) > 0) {
        println("================= strings ================", chunk.file_name);
        for (sz i = 0; i < array_size(chunk.strings); i++) {
            println(" %x{2}:  %s", i, chunk.strings[i]);
        }
    }
    if (array_size(chunk.vars) > 0) {
        println("================ variables ===============", chunk.file_name);
        for (sz i = 0; i < array_size(chunk.vars); i++) {
            println(" %x{2}: [%x{4}:%x{4}] %s: %s", i, chunk.vars[i].offset,
                    chunk.vars[i].offset + chunk.vars[i].size,
                    chunk.vars[i].name, chunk.vars[i].type);
        }
    }
    if (array_size(chunk.functions) > 0) {
        println("================ functions ===============", chunk.file_name);
        for (sz i = 0; i < array_size(chunk.functions); i++) {
            Chunk *func = chunk.functions[i];
            println(" %x{2}: func%d: %s", i, func->id, func->name);
        }
    }
    println("==========================================");
    for (sz i = 0; i < array_size(chunk.functions); i++) {
        Chunk *func = chunk.functions[i];
        disassemble_chunk(*func);
    }
}

#endif  // COMPILER_C