somni 0.2.0

Somni scripting language and VM
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
use std::fmt::{Debug, Display, Write as _};

use indexmap::IndexMap;

use crate::{
    error::CompileError,
    ir,
    string_interner::{StringIndex, StringInterner},
    types::{TypedValue, VmTypeSet},
    variable_tracker::{LocalVariableIndex, RestorePoint, ScopeData, VariableTracker},
};

use somni_parser::{
    ast::{self, FunctionArgument},
    lexer::Token,
    Location,
};

#[derive(Clone, Copy, PartialEq, Debug)]
pub enum Value {
    Void,
    MaybeSignedInt(u64),
    Int(u64),
    SignedInt(i64),
    Float(f64),
    Bool(bool),
    String(StringIndex),
}

impl Value {
    pub(crate) fn into_typed_value(self) -> TypedValue {
        match self {
            ir::Value::Void => TypedValue::Void,
            ir::Value::MaybeSignedInt(value) => TypedValue::MaybeSignedInt(value),
            ir::Value::Int(value) => TypedValue::Int(value),
            ir::Value::SignedInt(value) => TypedValue::SignedInt(value),
            ir::Value::Float(value) => TypedValue::Float(value),
            ir::Value::Bool(value) => TypedValue::Bool(value),
            ir::Value::String(value) => TypedValue::String(value),
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub enum Variable {
    Value(Type),
    Reference(usize, Type),
}

impl Display for Variable {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::Value(ty) => Display::fmt(ty, f),
            Self::Reference(n, ty) => f.write_fmt(format_args!("{amp:n$}{ty}", amp = "&", n = n)),
        }
    }
}
impl Variable {
    pub(crate) fn reference(&self) -> Self {
        match self {
            Self::Value(t) => Self::Reference(1, *t),
            Self::Reference(n, t) => Self::Reference(*n + 1, *t),
        }
    }
    pub(crate) fn dereference(&self) -> Option<Self> {
        match self {
            Self::Value(_) => None,
            Self::Reference(1, t) => Some(Self::Value(*t)),
            Self::Reference(n, t) => Some(Self::Reference(*n - 1, *t)),
        }
    }
    pub(crate) fn maybe_signed_integer(&self) -> bool {
        matches!(
            self,
            Self::Value(Type::MaybeSignedInt) | Self::Reference(_, Type::MaybeSignedInt)
        )
    }

    pub(crate) fn is_integer(&self) -> bool {
        let (Self::Value(t) | Self::Reference(_, t)) = self;
        matches!(t, Type::MaybeSignedInt | Type::Int | Type::SignedInt)
    }
}

impl Value {
    pub fn type_of(&self) -> Type {
        match self {
            Value::Void => Type::Void,
            Value::MaybeSignedInt(_) => Type::MaybeSignedInt,
            Value::Int(_) => Type::Int,
            Value::SignedInt(_) => Type::SignedInt,
            Value::Bool(_) => Type::Bool,
            Value::String(_) => Type::String,
            Value::Float(_) => Type::Float,
        }
    }
}

#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq)]
pub enum Type {
    Void,
    MaybeSignedInt,
    Int,
    SignedInt,
    Float,
    Bool,
    String,
}

impl Display for Type {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Type::Void => write!(f, "void"),
            Type::MaybeSignedInt => write!(f, "{{int/signed}}"),
            Type::Int => write!(f, "int"),
            Type::SignedInt => write!(f, "signed"),
            Type::Bool => write!(f, "bool"),
            Type::String => write!(f, "string"),
            Type::Float => write!(f, "float"),
        }
    }
}

#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct BlockIndex(pub usize);

impl Debug for BlockIndex {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(f, "block {}", self.0)
    }
}

impl BlockIndex {
    const RETURN_BLOCK: Self = BlockIndex(1);
}

// This is a temporary hack for function arguments.
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum AllocationMethod {
    FirstFit,   // Allocate the first free address that fits
    TopOfStack, // Allocate at the top of the stack
}

#[derive(Debug, Clone, Copy, PartialEq)]
pub struct VariableDeclaration {
    pub index: LocalVariableIndex,
    pub name: StringIndex,
    pub allocation_method: AllocationMethod,
    pub is_argument: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum VariableIndex {
    Local(LocalVariableIndex),
    Temporary(LocalVariableIndex),
    Global(GlobalVariableIndex),
}

impl VariableIndex {
    const RETURN_VALUE: Self = VariableIndex::Local(LocalVariableIndex::RETURN_VALUE);

    fn name<'s>(&self, program: &'s Program, function: &Function) -> &'s str {
        match self {
            VariableIndex::Local(idx) => idx.name(program, function),
            VariableIndex::Temporary(idx) => idx.name(program, function),
            VariableIndex::Global(idx) => idx.name(program),
        }
    }

    pub fn local_index(self) -> Option<LocalVariableIndex> {
        match self {
            VariableIndex::Local(idx) | VariableIndex::Temporary(idx) => Some(idx),
            VariableIndex::Global(_) => None,
        }
    }
}

impl LocalVariableIndex {
    fn name<'s>(&self, program: &'s Program, function: &Function) -> &'s str {
        let var = function
            .implementation
            .as_ref()
            .unwrap()
            .variables
            .variable(*self)
            .expect("Local variable index out of bounds");
        program.strings.lookup(var.name)
    }
}

#[derive(Debug, PartialEq)]
pub struct IrWithLocation {
    pub instruction: Ir,
    pub source_location: Location,
}

impl IrWithLocation {
    fn print(&self, program: &Program, function: &Function) -> String {
        self.instruction.print(program, function)
    }
}

#[derive(Debug, Clone, PartialEq)]
pub enum Ir {
    Declare(VariableDeclaration, Option<Value>), // when allocating, may reuse freed addresses
    Assign(VariableIndex, VariableIndex),
    DerefAssign(VariableIndex, VariableIndex),
    FreeVariable(LocalVariableIndex), // only used for temporaries & scope ends

    Call(StringIndex, VariableIndex, Vec<VariableIndex>), // function name, arguments
    BinaryOperator(StringIndex, VariableIndex, VariableIndex, VariableIndex),
    UnaryOperator(StringIndex, VariableIndex, VariableIndex),
}

impl Ir {
    fn print(&self, program: &Program, function: &Function) -> String {
        let mut output = String::new();
        match self {
            Self::Declare(var, init_value) => write!(
                &mut output,
                "var {}: {} = {:?}",
                program.strings.lookup(var.name),
                function
                    .implementation
                    .as_ref()
                    .unwrap()
                    .variables
                    .variable(var.index)
                    .unwrap()
                    .ty
                    .unwrap_or(Variable::Value(Type::Void)),
                init_value
            )
            .unwrap(),
            Self::Assign(dst, src) => {
                let dst = dst.name(program, function);
                let src = src.name(program, function);

                write!(&mut output, "{dst} = {src}").unwrap()
            }
            Self::DerefAssign(dst, src) => {
                let dst = dst.name(program, function);
                let src = src.name(program, function);

                write!(&mut output, "*{dst} = {src}").unwrap()
            }
            Self::FreeVariable(var) => {
                let var = var.name(program, function);

                write!(&mut output, "free({var})").unwrap()
            }
            Self::Call(f, retval, args) => {
                let f = program.strings.lookup(*f);

                let args = args
                    .iter()
                    .map(|arg| arg.name(program, function))
                    .collect::<Vec<_>>()
                    .join(", ");

                let retval = retval.name(program, function);

                write!(&mut output, "{retval} = call {f}({args})").unwrap()
            }
            Self::UnaryOperator(op, dst, operand) => {
                let dst = dst.name(program, function);

                let operand = operand.name(program, function);
                let operator = program.strings.lookup(*op);

                write!(&mut output, "{dst} = {operator}{operand}").unwrap()
            }
            Self::BinaryOperator(op, dst, left, right) => {
                let dst = dst.name(program, function);
                let left = left.name(program, function);
                let right = right.name(program, function);

                let operator = program.strings.lookup(*op);

                write!(&mut output, "{dst} = {left} {operator} {right}").unwrap()
            }
        }
        output
    }
}

#[derive(Debug)]
pub enum Termination {
    Return(Location),
    // Tries to lay out the next block linearly, jumps if its already laid out.
    Jump {
        source_location: Location,
        to: BlockIndex,
    },
    If {
        source_location: Location,
        // The condition is a variable that is true or false
        condition: VariableIndex,
        // If condition == true
        then_block: BlockIndex,
        // If condition == false
        else_block: BlockIndex,
    },
}

impl PartialEq for Termination {
    fn eq(&self, other: &Self) -> bool {
        match (self, other) {
            (Termination::Return(l1), Termination::Return(l2)) => l1 == l2,
            (Termination::Jump { to: t1, .. }, Termination::Jump { to: t2, .. }) => t1 == t2,
            (
                Termination::If {
                    condition: c1,
                    then_block: tb1,
                    else_block: eb1,
                    ..
                },
                Termination::If {
                    condition: c2,
                    then_block: tb2,
                    else_block: eb2,
                    ..
                },
            ) => c1 == c2 && tb1 == tb2 && eb1 == eb2,
            _ => false,
        }
    }
}

#[derive(Debug, PartialEq)]
pub struct Block {
    pub instructions: Vec<IrWithLocation>,
    pub terminator: Termination,
}

/// The compiler expects all globals to have been evaluated, but the IR compiler can't do that.
pub enum GlobalInitializer {
    Value(Value),
    Expression(Vec<IrWithLocation>),
}

pub struct GlobalVariableInfo {
    pub initializer: ast::Expression<VmTypeSet>,
    pub ty: Type,
}

impl GlobalVariableInfo {
    fn print(&self, _program: &Program) -> String {
        format!("global {}", self.ty)
    }
}

/// An index into the global variables in a program. This uniquely identifies a global, but
/// it is not directly related to a variable's address.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct GlobalVariableIndex(pub usize);
impl GlobalVariableIndex {
    fn name<'s>(&self, program: &'s Program) -> &'s str {
        let (name, _) = program
            .globals
            .get_index(self.0)
            .expect("Global variable index out of bounds");
        program.strings.lookup(*name)
    }
}

pub struct Program {
    pub globals: IndexMap<StringIndex, GlobalVariableInfo>,
    pub functions: IndexMap<StringIndex, Function>,
    pub strings: StringInterner,
}

impl Program {
    pub fn print(&self) -> String {
        let mut output = String::new();

        writeln!(&mut output, "Globals:").unwrap();
        for (name, global) in &self.globals {
            let name = self.strings.lookup(*name);
            writeln!(&mut output, "  {name} = {}", global.print(self)).unwrap();
        }

        writeln!(&mut output).unwrap();

        for (_, function) in &self.functions {
            output.push_str(&function.print(self));
            writeln!(&mut output).unwrap();
        }

        output
    }

    pub(crate) fn compile<'s>(
        source: &'s str,
        ast: &ast::Program<VmTypeSet>,
    ) -> Result<Program, CompileError<'s>> {
        let mut strings = StringInterner::new();
        let mut functions = IndexMap::new();
        let mut globals = IndexMap::new();

        // Declare items first
        for item in &ast.items {
            match item {
                ast::Item::GlobalVariable(global_variable) => {
                    let name = global_variable.identifier.source(source);
                    let name_idx = strings.intern(name);
                    if globals.contains_key(&name_idx) {
                        return Err(CompileError {
                            source,
                            location: global_variable.identifier.location,
                            error: format!("Global variable `{name}` is already defined")
                                .into_boxed_str(),
                        });
                    }

                    let ty = match global_variable.type_token.type_name.source(source) {
                        "int" => Type::Int,
                        "signed" => Type::SignedInt,
                        "float" => Type::Float,
                        "bool" => Type::Bool,
                        "string" => Type::String,
                        other => {
                            return Err(CompileError {
                                source,
                                location: global_variable.type_token.type_name.location,
                                error: format!("Unknown type `{other}`").into_boxed_str(),
                            });
                        }
                    };

                    globals.insert(
                        name_idx,
                        GlobalVariableInfo {
                            ty,
                            initializer: global_variable.initializer.clone(),
                        },
                    );
                }
                ast::Item::ExternFunction(function) => {
                    let name = function.name.source(source);
                    let name_idx = strings.intern(name);
                    if functions.contains_key(&name_idx) {
                        return Err(CompileError {
                            source,
                            location: function.name.location,
                            error: format!("Function `{name}` is already defined").into_boxed_str(),
                        });
                    }
                    functions.insert(
                        name_idx,
                        Function::compile_external(source, function, &mut strings)?,
                    );
                }
                ast::Item::Function(function) => {
                    let name = function.name.source(source);
                    let name_idx = strings.intern(name);
                    if functions.contains_key(&name_idx) {
                        return Err(CompileError {
                            source,
                            location: function.name.location,
                            error: format!("Function `{name}` is already defined").into_boxed_str(),
                        });
                    }
                    functions.insert(name_idx, Function::DUMMY);
                }
            }
        }

        for item in &ast.items {
            if let ast::Item::Function(function) = item {
                let func = Function::compile(source, function, &mut strings, &globals)?;
                functions.insert(func.name, func);
            }
        }

        Ok(Program {
            globals,
            functions,
            strings,
        })
    }
}

pub struct Function {
    pub name: StringIndex,
    pub arguments: Vec<Variable>,
    pub return_type: Type,
    pub implementation: Option<FunctionImplementation>,
}

pub struct FunctionImplementation {
    pub variables: ScopeData,
    pub blocks: Vec<Block>,
}

impl Function {
    const DUMMY: Self = Function {
        name: StringIndex::dummy(),
        return_type: Type::Void,
        arguments: vec![],
        implementation: None,
    };

    pub fn print(&self, program: &Program) -> String {
        let mut output = String::new();
        writeln!(
            &mut output,
            "Function: {}",
            program.strings.lookup(self.name)
        )
        .unwrap();
        if let Some(implementation) = self.implementation.as_ref() {
            for (idx, block) in implementation.blocks.iter().enumerate() {
                if idx > 0 {
                    writeln!(&mut output).unwrap();
                }

                writeln!(&mut output, "{:?}", BlockIndex(idx)).unwrap();
                for instruction in &block.instructions {
                    writeln!(&mut output, "  {}", instruction.print(program, self)).unwrap();
                }

                match block.terminator {
                    Termination::Return(_) => writeln!(&mut output, "  -> return").unwrap(),
                    Termination::Jump { to, .. } => writeln!(&mut output, "  -> {to:?}").unwrap(),
                    Termination::If {
                        condition,
                        then_block,
                        else_block,
                        ..
                    } => {
                        let condition = condition.name(program, self);
                        writeln!(
                            &mut output,
                            "  if {condition} -> {then_block:?} else {else_block:?}",
                        )
                        .unwrap()
                    }
                }
            }
        } else {
            writeln!(&mut output, "  External function").unwrap();
        }

        output
    }

    pub fn compile<'s>(
        source: &'s str,
        func: &ast::Function<VmTypeSet>,
        strings: &mut StringInterner,
        globals: &IndexMap<StringIndex, GlobalVariableInfo>,
    ) -> Result<Function, CompileError<'s>> {
        let mut this = FunctionCompiler {
            source,
            blocks: Blocks {
                blocks: vec![
                    // Enter function
                    Block {
                        instructions: vec![],
                        terminator: Termination::Jump {
                            source_location: func.name.location,
                            to: BlockIndex::RETURN_BLOCK,
                        }, // Jump to the first block
                    },
                    // Return from function
                    Block {
                        instructions: vec![],
                        terminator: Termination::Return(func.closing_paren.location),
                    },
                ],
                current_block: BlockIndex(0),
            },
            variables: VariableTracker::new(),
            strings,
            loop_stack: Vec::new(),
            globals,
        };

        Self::validate_arg_names(source, &func.arguments)?;

        // Allocate a return variable, if the function has a return type.
        let (return_type, return_token) = if let Some(return_type) = &func.return_decl {
            (
                FunctionCompiler::compile_type(source, &return_type.return_type)?,
                return_type.return_type.type_name,
            )
        } else {
            (Type::Void, func.fn_token)
        };

        let rp = this.variables.create_restore_point();
        this.declare_variable(
            "return_value",
            Some(Variable::Value(return_type)),
            return_token.location,
            true,
        )?;

        // allocate variables for arguments
        let mut arguments = vec![];
        for argument in func.arguments.iter() {
            let ty = FunctionCompiler::compile_type(source, &argument.arg_type)?;
            let ty = if argument.reference_token.is_some() {
                Variable::Reference(1, ty)
            } else {
                Variable::Value(ty)
            };
            let name = argument.name.source(source);
            this.declare_variable(name, Some(ty), argument.name.location, true)?;
            arguments.push(ty);
        }

        this.compile_body(&func.body, VariableIndex::RETURN_VALUE)?;

        this.rollback_scope(func.closing_paren.location, rp);

        Ok(Function {
            name: this.strings.intern(func.name.source(source)),
            return_type,
            arguments,
            implementation: Some(FunctionImplementation {
                variables: this.variables.finalize(),
                blocks: this.blocks.blocks,
            }),
        })
    }

    pub fn compile_external<'s>(
        source: &'s str,
        func: &ast::ExternalFunction,
        strings: &mut StringInterner,
    ) -> Result<Function, CompileError<'s>> {
        Self::validate_arg_names(source, &func.arguments)?;

        // Allocate a return variable, if the function has a return type.
        let return_type = if let Some(return_type) = &func.return_decl {
            FunctionCompiler::compile_type(source, &return_type.return_type)?
        } else {
            Type::Void
        };

        // allocate variables for arguments
        let mut arguments = vec![];
        for argument in func.arguments.iter() {
            let ty = FunctionCompiler::compile_type(source, &argument.arg_type)?;
            let ty = if argument.reference_token.is_some() {
                Variable::Reference(1, ty)
            } else {
                Variable::Value(ty)
            };
            arguments.push(ty);
        }

        Ok(Function {
            name: strings.intern(func.name.source(source)),
            return_type,
            arguments,
            implementation: None,
        })
    }

    fn validate_arg_names<'s>(
        source: &'s str,
        arguments: &[FunctionArgument],
    ) -> Result<(), CompileError<'s>> {
        // Check that argument names are unique.
        let arg_names = arguments.iter().map(|a| a.name.source(source));
        let mut seen_names = std::collections::HashMap::new();
        const RESERVED_NAMES: &[&str] = &["return_value"];
        for (idx, name) in arg_names.enumerate() {
            if seen_names.insert(name, idx).is_some() {
                return Err(CompileError {
                    source,
                    location: arguments[idx].name.location,
                    error: format!("Duplicate argument name `{name}`").into_boxed_str(),
                });
            }
            if RESERVED_NAMES.contains(&name) {
                return Err(CompileError {
                    source,
                    location: arguments[idx].name.location,
                    error: format!("Argument name `{name}` is reserved").into_boxed_str(),
                });
            }
        }

        Ok(())
    }
}

struct Loop {
    restore_point: RestorePoint,
    body_block: BlockIndex,
    next_block: BlockIndex,
}

struct Blocks {
    blocks: Vec<Block>,
    current_block: BlockIndex,
}

impl Blocks {
    /// Allocates a new block in the function's block list.
    ///
    /// Blocks may be allocated in any order. Codegen will walk through the blocks in order,
    /// and generate code for each block, in order. Codegen will make sure that jumps are
    /// resolved to the correct block.
    fn allocate_block(&mut self, next: BlockIndex) -> BlockIndex {
        let index = BlockIndex(self.blocks.len());
        self.blocks.push(Block {
            instructions: Vec::new(),
            terminator: Termination::Jump {
                source_location: Location::dummy(),
                to: next,
            },
        });
        index
    }

    fn select_block(&mut self, index: BlockIndex) {
        if index.0 >= self.blocks.len() {
            panic!("Block index out of bounds: {}", index.0);
        }
        self.current_block = index;
    }

    fn push_instruction(&mut self, source_location: Location, instruction: Ir) {
        self.blocks[self.current_block.0]
            .instructions
            .push(IrWithLocation {
                instruction,
                source_location,
            });
    }

    fn set_terminator(&mut self, terminator: Termination) {
        self.blocks[self.current_block.0].terminator = terminator;
    }

    fn current(&self) -> BlockIndex {
        self.current_block
    }
}

/// Compiles a function into an intermediate representation (IR).
///
/// The IR is consumed by the bytecode compiler, and the debuginfo compiler.
struct FunctionCompiler<'s, 'c> {
    source: &'s str,
    strings: &'c mut StringInterner,
    globals: &'c IndexMap<StringIndex, GlobalVariableInfo>,

    blocks: Blocks,
    variables: VariableTracker,
    loop_stack: Vec<Loop>,
}

impl<'s> FunctionCompiler<'s, '_> {
    fn declare_variable(
        &mut self,
        name: &str,
        var_ty: Option<Variable>,
        source_location: Location,
        is_argument: bool,
    ) -> Result<LocalVariableIndex, CompileError<'s>> {
        let name_index = self.strings.intern(name);
        let variable = self.variables.declare_variable(name_index, var_ty);
        self.blocks.push_instruction(
            source_location,
            Ir::Declare(
                VariableDeclaration {
                    index: variable,
                    name: name_index,
                    allocation_method: AllocationMethod::FirstFit,
                    is_argument,
                },
                None,
            ),
        );
        Ok(variable)
    }

    fn declare_temporary(
        &mut self,
        location: Location,
        init_value: Value,
        allocation_method: AllocationMethod,
    ) -> VariableIndex {
        let temp_name = self
            .strings
            .intern(&format!("temp{}", self.variables.len()));
        let init_value = (init_value != Value::Void).then_some(init_value);
        let temp = self
            .variables
            .declare_variable(temp_name, init_value.map(|v| Variable::Value(v.type_of())));
        self.blocks.push_instruction(
            location,
            Ir::Declare(
                VariableDeclaration {
                    index: temp,
                    name: temp_name,
                    allocation_method,
                    is_argument: false,
                },
                init_value,
            ),
        );

        VariableIndex::Temporary(temp)
    }

    fn declare_typed_temporary(
        &mut self,
        location: Location,
        ty: Type,
        allocation_method: AllocationMethod,
    ) -> VariableIndex {
        let temp_name = self
            .strings
            .intern(&format!("temp{}", self.variables.len()));
        let temp = self
            .variables
            .declare_variable(temp_name, Some(Variable::Value(ty)));
        self.blocks.push_instruction(
            location,
            Ir::Declare(
                VariableDeclaration {
                    index: temp,
                    name: temp_name,
                    allocation_method,
                    is_argument: false,
                },
                None,
            ),
        );

        VariableIndex::Temporary(temp)
    }

    fn compile_statement(
        &mut self,
        statement: &ast::Statement<VmTypeSet>,
        storage: VariableIndex,
    ) -> Result<(), CompileError<'s>> {
        match statement {
            ast::Statement::VariableDefinition(variable_def) => {
                self.compile_variable_definition(variable_def)?;
            }
            ast::Statement::Return(ret_with_value) => {
                self.compile_return_with_value(ret_with_value)?;
            }
            ast::Statement::EmptyReturn(ret) => self.compile_empty_return(ret)?,
            ast::Statement::If(if_statement) => {
                let expect_void = self.declare_typed_temporary(
                    statement.location(),
                    Type::Void,
                    AllocationMethod::FirstFit,
                );
                self.compile_if_statement(if_statement, expect_void)?
            }
            ast::Statement::Loop(loop_statement) => {
                let expect_void = self.declare_typed_temporary(
                    statement.location(),
                    Type::Void,
                    AllocationMethod::FirstFit,
                );
                self.compile_loop_statement(loop_statement, expect_void)?
            }
            ast::Statement::Break(break_statement) => {
                self.compile_break_statement(break_statement)?
            }
            ast::Statement::Continue(continue_statement) => {
                self.compile_continue_statement(continue_statement)?;
            }
            ast::Statement::Scope(body) => return self.compile_free_scope(body, storage),
            ast::Statement::Expression {
                expression,
                semicolon,
            } => self.compile_expression_statement(expression, semicolon)?,
            ast::Statement::ImplicitReturn(expression) => {
                self.compile_implicit_return(expression, storage)?
            }
        }

        Ok(())
    }

    fn compile_variable_definition(
        &mut self,
        variable_def: &ast::VariableDefinition<VmTypeSet>,
    ) -> Result<(), CompileError<'s>> {
        let ident = variable_def.identifier;
        let ty = variable_def.type_token.as_ref();
        let initializer = &variable_def.initializer;

        let name = ident.source(self.source);
        let var_ty = if let Some(type_token) = ty {
            Some(Variable::Value(Self::compile_type(
                self.source,
                type_token,
            )?))
        } else {
            None
        };
        let variable = self.declare_variable(name, var_ty, ident.location, false)?;

        let rp = self.variables.create_restore_point();
        let expr_result = self.compile_right_hand_expression(initializer)?;
        self.blocks.push_instruction(
            ident.location,
            Ir::Assign(VariableIndex::Local(variable), expr_result),
        );
        self.rollback_scope(initializer.location(), rp);

        Ok(())
    }

    fn compile_if_statement(
        &mut self,
        if_statement: &ast::If<VmTypeSet>,
        if_return_value: VariableIndex,
    ) -> Result<(), CompileError<'s>> {
        let rp = self.variables.create_restore_point();

        // Generate instructions for the condition, allocate then/else blocks and generate conditional jumps
        let condition = self.compile_right_hand_expression(&if_statement.condition)?;

        // Allocate the next block, which is the block that will be executed after the branches.
        // Point to the return block by default.
        let next_block = self.blocks.allocate_block(BlockIndex::RETURN_BLOCK);

        // Save the current block so that we can update it later.
        let condition_block = self.blocks.current();

        // Compile the branches
        let then_block = self.blocks.allocate_block(BlockIndex::RETURN_BLOCK);
        self.blocks.select_block(then_block);
        self.compile_body(&if_statement.body, if_return_value)?;
        self.blocks.set_terminator(Termination::Jump {
            source_location: if_statement.body.closing_brace.location,
            to: next_block,
        });

        let else_block = if let Some(else_branch) = if_statement.else_branch.as_ref() {
            let else_block = self.blocks.allocate_block(BlockIndex::RETURN_BLOCK);
            self.blocks.select_block(else_block);
            self.compile_body(&else_branch.else_body, if_return_value)?;
            self.blocks.set_terminator(Termination::Jump {
                source_location: else_branch.else_body.closing_brace.location,
                to: next_block,
            });
            else_block
        } else {
            // If there is no else branch, we can just jump to the next block.
            next_block
        };

        // Update the condition block's terminator to be a conditional jump.
        self.blocks.select_block(condition_block);
        self.blocks.set_terminator(Termination::If {
            source_location: if_statement.if_token.location,
            condition,
            then_block,
            else_block,
        });

        // Whatever happens, normal execution continues at the next block.
        self.blocks.select_block(next_block);

        self.rollback_scope(if_statement.if_token.location, rp);

        Ok(())
    }

    fn compile_body(
        &mut self,
        body: &ast::Body<VmTypeSet>,
        storage: VariableIndex,
    ) -> Result<(), CompileError<'s>> {
        let restore_point = self.variables.create_restore_point();

        let expect_void =
            self.declare_typed_temporary(body.location(), Type::Void, AllocationMethod::FirstFit);

        let last_idx = body.statements.len().saturating_sub(1);
        for (statement, is_last) in body
            .statements
            .iter()
            .enumerate()
            .map(|(i, stmt)| (stmt, i == last_idx))
        {
            self.compile_statement(statement, if is_last { storage } else { expect_void })?;
        }

        self.rollback_scope(body.closing_brace.location, restore_point);

        Ok(())
    }

    fn compile_loop_statement(
        &mut self,
        loop_statement: &ast::Loop<VmTypeSet>,
        loop_return_value: VariableIndex,
    ) -> Result<(), CompileError<'s>> {
        let next_block = self.blocks.allocate_block(BlockIndex::RETURN_BLOCK);

        // Compile the body of the loop.
        let body_block = self.blocks.allocate_block(next_block);

        // Set up the loop structure.
        self.blocks.set_terminator(Termination::Jump {
            source_location: loop_statement.loop_token.location,
            to: body_block,
        });
        self.loop_stack.push(Loop {
            restore_point: self.variables.create_restore_point(),
            body_block,
            next_block,
        });

        self.blocks.select_block(body_block);
        self.compile_body(&loop_statement.body, loop_return_value)?;
        self.blocks.set_terminator(Termination::Jump {
            source_location: loop_statement.body.closing_brace.location,
            to: body_block,
        });

        self.blocks.select_block(next_block);

        Ok(())
    }

    fn compile_break_statement(
        &mut self,
        break_statement: &ast::Break,
    ) -> Result<(), CompileError<'s>> {
        let Some(loop_entry) = self.loop_stack.last() else {
            return Err(CompileError {
                source: self.source,
                location: break_statement.break_token.location,
                error: "Cannot break outside of a loop."
                    .to_string()
                    .into_boxed_str(),
            });
        };

        self.compile_cleanup_block(
            loop_entry.restore_point,
            loop_entry.next_block,
            break_statement.break_token.location,
        )?;

        Ok(())
    }

    fn compile_continue_statement(
        &mut self,
        continue_statement: &ast::Continue,
    ) -> Result<(), CompileError<'s>> {
        let Some(loop_entry) = self.loop_stack.last() else {
            return Err(CompileError {
                source: self.source,
                location: continue_statement.continue_token.location,
                error: "Cannot continue outside of a loop."
                    .to_string()
                    .into_boxed_str(),
            });
        };

        // The cleanup block jumps to the next block after the loop.
        self.compile_cleanup_block(
            loop_entry.restore_point,
            loop_entry.body_block,
            continue_statement.continue_token.location,
        )?;

        Ok(())
    }

    fn compile_return_with_value(
        &mut self,
        ret: &ast::ReturnWithValue<VmTypeSet>,
    ) -> Result<(), CompileError<'s>> {
        let rp = self.variables.create_restore_point();
        let return_value = self.compile_right_hand_expression(&ret.expression)?;

        // Store variable in the return variable.
        self.blocks.push_instruction(
            ret.location(),
            Ir::Assign(VariableIndex::RETURN_VALUE, return_value),
        );

        self.rollback_scope(ret.semicolon.location, rp);

        self.compile_return(ret.return_token)
    }

    fn compile_implicit_return(
        &mut self,
        expression: &ast::RightHandExpression<VmTypeSet>,
        storage: VariableIndex,
    ) -> Result<(), CompileError<'s>> {
        let return_value = self.compile_right_hand_expression(expression)?;

        // Store variable in the return variable.
        // TODO: each block should have a return temporary, and we should store there.
        self.blocks
            .push_instruction(expression.location(), Ir::Assign(storage, return_value));

        Ok(())
    }

    fn compile_empty_return(&mut self, ret: &ast::EmptyReturn) -> Result<(), CompileError<'s>> {
        self.compile_return(ret.return_token)
    }

    fn compile_return(&mut self, ret: Token) -> Result<(), CompileError<'s>> {
        // The cleanup block jumps to the next block after the loop.
        self.compile_cleanup_block(
            RestorePoint::RETURN_FROM_FN,
            BlockIndex::RETURN_BLOCK,
            ret.location,
        )?;

        Ok(())
    }

    fn compile_cleanup_block(
        &mut self,
        restore_point: RestorePoint,
        next_block: BlockIndex,
        source_location: Location,
    ) -> Result<(), CompileError<'s>> {
        let cleanup_block = self.blocks.allocate_block(next_block);

        self.blocks.set_terminator(Termination::Jump {
            source_location,
            to: cleanup_block,
        });

        self.rollback_scope(source_location, restore_point);

        // The rest of the body is unreachable, so we allocate a new block for the next statements.
        // Nothing will actually jump to this block, but we want to handle compilation errors.
        let next_block = self.blocks.allocate_block(BlockIndex::RETURN_BLOCK);
        self.blocks.select_block(next_block);

        Ok(())
    }

    fn compile_expression_statement(
        &mut self,
        expression: &ast::Expression<VmTypeSet>,
        semicolon: &Token,
    ) -> Result<(), CompileError<'s>> {
        let rp = self.variables.create_restore_point();

        // Compile the expression, which may be a variable assignment, function call,
        // or other expression. Discard the result.
        self.compile_expression(expression)?;

        self.rollback_scope(semicolon.location, rp);

        Ok(())
    }

    fn compile_type(source: &'s str, type_token: &ast::TypeHint) -> Result<Type, CompileError<'s>> {
        match type_token.type_name.source(source) {
            "int" => Ok(Type::Int),
            "signed" => Ok(Type::SignedInt),
            "float" => Ok(Type::Float),
            "bool" => Ok(Type::Bool),
            "string" => Ok(Type::String),
            other => Err(CompileError {
                source,
                location: type_token.type_name.location,
                error: format!("Unknown type `{other}`").into_boxed_str(),
            }),
        }
    }

    fn compile_expression(
        &mut self,
        expression: &ast::Expression<VmTypeSet>,
    ) -> Result<VariableIndex, CompileError<'s>> {
        match &expression {
            ast::Expression::Assignment {
                left_expr,
                operator,
                right_expr,
            } => {
                let rp = self.variables.create_restore_point();

                let left;
                // Compile the right operand.
                let right = self.compile_right_hand_expression(right_expr)?;

                let instruction = match left_expr {
                    ast::LeftHandExpression::Deref { operator: _, name } => {
                        left = self.compile_right_hand_expression(
                            &ast::RightHandExpression::Variable { variable: *name },
                        )?;
                        Ir::DerefAssign(left, right)
                    }
                    ast::LeftHandExpression::Name { variable } => {
                        left = self.compile_right_hand_expression(
                            &ast::RightHandExpression::Variable {
                                variable: *variable,
                            },
                        )?;
                        Ir::Assign(left, right)
                    }
                };

                // Generate the instruction for the assignment.
                self.blocks.push_instruction(operator.location, instruction);

                self.rollback_scope(operator.location, rp);

                // Allocate a temporary variable. For assignments this is not used, but
                // we still need to return something.
                Ok(self.declare_temporary(
                    operator.location,
                    Value::Void,
                    AllocationMethod::FirstFit,
                ))
            }
            ast::Expression::Expression { expression } => {
                self.compile_right_hand_expression(expression)
            }
        }
    }

    fn compile_right_hand_expression(
        &mut self,
        expression: &ast::RightHandExpression<VmTypeSet>,
    ) -> Result<VariableIndex, CompileError<'s>> {
        match &expression {
            ast::RightHandExpression::Literal { value } => {
                let val_type = match value.value {
                    ast::LiteralValue::Integer(_) => Type::MaybeSignedInt,
                    ast::LiteralValue::Float(_) => Type::Float,
                    ast::LiteralValue::Boolean(_) => Type::Bool,
                    ast::LiteralValue::String(_) => Type::String,
                };

                let literal_value = self.compile_literal_value(val_type, value)?;
                let temp = self.declare_temporary(
                    value.location,
                    literal_value,
                    AllocationMethod::FirstFit,
                );

                Ok(temp)
            }
            ast::RightHandExpression::Variable { variable } => {
                let name = variable.source(self.source);
                match self.find_variable_by_name(name) {
                    // If the variable is already declared, we can just return it.
                    Some(index) => Ok(index),
                    None => Err(CompileError {
                        source: self.source,
                        location: variable.location,
                        error: format!("Variable `{name}` is not declared").into_boxed_str(),
                    }),
                }
            }
            ast::RightHandExpression::UnaryOperator { name, operand } => {
                self.compile_unary_operator(*name, operand)
            }
            ast::RightHandExpression::BinaryOperator { name, operands } => {
                self.compile_binary_operator(*name, operands)
            }
            ast::RightHandExpression::FunctionCall { name, arguments } => {
                self.compile_function_call(*name, arguments)
            }
        }
    }

    fn compile_literal_value(
        &mut self,
        literal_type: Type,
        literal: &ast::Literal<VmTypeSet>,
    ) -> Result<Value, CompileError<'s>> {
        let value = match (literal_type, &literal.value) {
            (Type::Int, ast::LiteralValue::Integer(value)) => Value::Int(*value),
            (Type::MaybeSignedInt, ast::LiteralValue::Integer(value)) => {
                Value::MaybeSignedInt(*value)
            }
            (Type::Float, ast::LiteralValue::Float(value)) => Value::Float(*value),
            (Type::Bool, ast::LiteralValue::Boolean(value)) => Value::Bool(*value),
            (Type::String, ast::LiteralValue::String(value)) => {
                let string_index = self.strings.intern(value);
                Value::String(string_index)
            }
            (Type::Void, _) => {
                return Err(CompileError {
                    source: self.source,
                    location: literal.location,
                    error: format!("{literal_type} is not supported in literals").into_boxed_str(),
                });
            }
            _ => {
                return Err(CompileError {
                    source: self.source,
                    location: literal.location,
                    error: format!(
                        "Expected {literal_type}, found {} literal",
                        match literal.value {
                            ast::LiteralValue::Integer(_) => "integer",
                            ast::LiteralValue::Float(_) => "float",
                            ast::LiteralValue::Boolean(_) => "boolean",
                            ast::LiteralValue::String(_) => "string",
                        }
                    )
                    .into_boxed_str(),
                });
            }
        };

        Ok(value)
    }

    fn compile_unary_operator(
        &mut self,
        operator: Token,
        operand: &ast::RightHandExpression<VmTypeSet>,
    ) -> Result<VariableIndex, CompileError<'s>> {
        let op = operator.source(self.source);

        // Allocate a temporary variable for the result.
        let temp =
            self.declare_temporary(operator.location, Value::Void, AllocationMethod::FirstFit);

        let rp = self.variables.create_restore_point();

        // Compile the left and right operands.
        let operand_result = self.compile_right_hand_expression(operand)?;

        if let VariableIndex::Local(local_idx) = operand_result {
            if op == "&" {
                self.variables.reference_variable(local_idx);
            }
        }

        // Generate the instruction for the binary operator.
        self.blocks.push_instruction(
            operator.location,
            Ir::UnaryOperator(self.strings.intern(op), temp, operand_result),
        );
        self.rollback_scope(operator.location, rp);

        Ok(temp)
    }

    fn compile_binary_operator(
        &mut self,
        operator: Token,
        operands: &[ast::RightHandExpression<VmTypeSet>; 2],
    ) -> Result<VariableIndex, CompileError<'s>> {
        let op = operator.source(self.source);

        if op == "&&" {
            let temp = self.declare_temporary(
                operator.location,
                Value::Bool(false),
                AllocationMethod::FirstFit,
            );

            let condition = self.compile_right_hand_expression(&operands[0])?;

            // Allocate the next block, which is the block that will be executed after the branches.
            // Point to the return block by default.
            let next_block = self.blocks.allocate_block(BlockIndex::RETURN_BLOCK);

            // Save the current block so that we can update it later.
            let condition_block = self.blocks.current();

            // Compile the then branch
            let then_block = self.blocks.allocate_block(BlockIndex::RETURN_BLOCK);
            self.blocks.select_block(then_block);
            let rp = self.variables.create_restore_point();
            let rhs = self.compile_right_hand_expression(&operands[1])?;
            self.blocks
                .push_instruction(operator.location, Ir::Assign(temp, rhs));
            self.free_if_temporary(operands[1].location(), rhs);

            self.rollback_scope(operator.location, rp);

            self.blocks.set_terminator(Termination::Jump {
                source_location: operator.location,
                to: next_block,
            });

            // Update the condition block's terminator to be a conditional jump.
            self.blocks.select_block(condition_block);
            self.blocks.set_terminator(Termination::If {
                source_location: operator.location,
                condition,
                then_block,
                else_block: next_block,
            });

            // Whatever happens, normal execution continues at the next block.
            self.blocks.select_block(next_block);
            self.free_if_temporary(operands[0].location(), condition);

            Ok(temp)
        } else if op == "||" {
            let temp = self.declare_temporary(
                operator.location,
                Value::Bool(true),
                AllocationMethod::FirstFit,
            );

            let condition = self.compile_right_hand_expression(&operands[0])?;

            // Allocate the next block, which is the block that will be executed after the branches.
            // Point to the return block by default.
            let next_block = self.blocks.allocate_block(BlockIndex::RETURN_BLOCK);

            // Save the current block so that we can update it later.
            let condition_block = self.blocks.current();

            // Compile the else branch
            let else_block = self.blocks.allocate_block(BlockIndex::RETURN_BLOCK);
            self.blocks.select_block(else_block);
            let rp = self.variables.create_restore_point();
            let rhs = self.compile_right_hand_expression(&operands[1])?;
            self.blocks
                .push_instruction(operator.location, Ir::Assign(temp, rhs));
            self.free_if_temporary(operands[1].location(), rhs);

            self.rollback_scope(operator.location, rp);

            self.blocks.set_terminator(Termination::Jump {
                source_location: operator.location,
                to: next_block,
            });

            // Update the condition block's terminator to be a conditional jump.
            self.blocks.select_block(condition_block);
            self.blocks.set_terminator(Termination::If {
                source_location: operator.location,
                condition,
                then_block: next_block,
                else_block,
            });

            // Whatever happens, normal execution continues at the next block.
            self.blocks.select_block(next_block);
            self.free_if_temporary(operands[0].location(), condition);

            Ok(temp)
        } else {
            // Compile the left and right operands.
            let left = self.compile_right_hand_expression(&operands[0])?;
            let right = self.compile_right_hand_expression(&operands[1])?;

            // Allocate a temporary variable for the result.
            let temp =
                self.declare_temporary(operator.location, Value::Void, AllocationMethod::FirstFit);
            // Generate the instruction for the binary operator.
            self.blocks.push_instruction(
                operator.location,
                Ir::BinaryOperator(self.strings.intern(op), temp, left, right),
            );
            self.free_if_temporary(operands[0].location(), left);
            self.free_if_temporary(operands[1].location(), right);

            Ok(temp)
        }
    }

    fn compile_function_call(
        &mut self,
        name: Token,
        arguments: &[ast::RightHandExpression<VmTypeSet>],
    ) -> Result<VariableIndex, CompileError<'s>> {
        // Allocate a temporary variable for the result.
        let temp = self.declare_temporary(name.location, Value::Void, AllocationMethod::FirstFit);
        let rp = self.variables.create_restore_point();

        // Compile the arguments.
        let arguments = arguments
            .iter()
            .map(|arg| {
                self.compile_right_hand_expression(arg)
                    .map(|val| (val, arg.location()))
            })
            .collect::<Result<Vec<_>, _>>()?;
        let function_name = name.source(self.source);
        let function_index = self.strings.intern(function_name);

        // Generate the instruction for the function call. Here we allocate the stack frame, copy
        // arguments into it, then generate the call. The two temporaries above the stack pointer are
        // used by the call/return instructions. This way the stack pointer
        // still points at the return value.
        // TODO: would be better to declare signature as a structure so that we don't have to
        // treat call-related allocations differently.
        let _pc_temporary =
            self.declare_typed_temporary(name.location, Type::Int, AllocationMethod::TopOfStack);
        let _sp_temporary =
            self.declare_typed_temporary(name.location, Type::Int, AllocationMethod::TopOfStack);
        let retval_temporary =
            self.declare_temporary(name.location, Value::Void, AllocationMethod::TopOfStack);
        let arg_temporaries = arguments
            .iter()
            .map(|(arg, location)| {
                let arg_temp =
                    self.declare_temporary(*location, Value::Void, AllocationMethod::TopOfStack);
                self.blocks
                    .push_instruction(*location, Ir::Assign(arg_temp, *arg));
                arg_temp
            })
            .collect::<Vec<_>>();
        self.blocks.push_instruction(
            name.location,
            Ir::Call(function_index, retval_temporary, arg_temporaries),
        );
        // Copy the return value into the temporary variable.
        self.blocks
            .push_instruction(name.location, Ir::Assign(temp, retval_temporary));

        // Free up the temporaries except for the return value.
        self.rollback_scope(name.location, rp);

        Ok(temp)
    }

    fn find_variable_by_name(&mut self, name: &str) -> Option<VariableIndex> {
        let name = self.strings.intern(name);
        if let Some(local) = self.variables.find(name) {
            // If the variable is already declared, we can just return it.
            Some(VariableIndex::Local(local))
        } else {
            self.globals
                .get_index_of(&name)
                .map(|index| VariableIndex::Global(GlobalVariableIndex(index)))
        }
    }

    fn free_if_temporary(&mut self, location: Location, right: VariableIndex) {
        if let VariableIndex::Temporary(operand) = right {
            self.variables.free_variable(operand);
            self.blocks
                .push_instruction(location, Ir::FreeVariable(operand));
        }
    }

    fn rollback_scope(&mut self, location: Location, rp: RestorePoint) {
        for var in self.variables.rollback_to_restore_point(rp) {
            self.blocks
                .push_instruction(location, Ir::FreeVariable(var));
        }
    }

    fn compile_free_scope(
        &mut self,
        body: &ast::Body<VmTypeSet>,
        storage: VariableIndex,
    ) -> Result<(), CompileError<'s>> {
        let next_block = self.blocks.allocate_block(BlockIndex::RETURN_BLOCK);

        // Compile the body of the scope.
        let body_block = self.blocks.allocate_block(next_block);

        self.blocks.set_terminator(Termination::Jump {
            source_location: body.opening_brace.location,
            to: body_block,
        });
        self.blocks.select_block(body_block);
        self.compile_body(body, storage)?;

        self.blocks.set_terminator(Termination::Jump {
            source_location: body.closing_brace.location,
            to: next_block,
        });

        self.blocks.select_block(next_block);
        Ok(())
    }
}