-
Notifications
You must be signed in to change notification settings - Fork 1
/
interpreter.rs
1352 lines (1192 loc) · 44.6 KB
/
interpreter.rs
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
//! An AST interpreter, feature complete enough to interpret the bootstrapping compiler.
//!
//! Since we don't have a proper type checker (it will be implemented in the bootstrapped compiler)
//! we don't assume type safety here and always check types.
#![allow(clippy::needless_range_loop, clippy::too_many_arguments)]
mod builtins;
mod heap;
mod init;
use builtins::{call_builtin_fun, BuiltinFun};
use heap::Heap;
use crate::ast::{self, Loc, L};
use crate::collections::{Map, Set};
use crate::interpolation::StringPart;
use crate::record_collector::{collect_records, RecordShape};
use std::cmp::Ordering;
use std::io::Write;
use bytemuck::cast_slice_mut;
use smol_str::SmolStr;
pub fn run<W: Write>(w: &mut W, pgm: Vec<L<ast::TopDecl>>, input: &str) {
let mut heap = Heap::new();
let pgm = Pgm::new(pgm, &mut heap);
// Allocate command line arguments to be passed to the program.
let input = heap.allocate_str(pgm.str_ty_tag, input.as_bytes());
// Find the main function.
let main_fun = pgm
.top_level_funs
.get("main")
.unwrap_or_else(|| panic!("main function not defined"));
call(
w,
&pgm,
&mut heap,
main_fun,
vec![input],
// `main` doesn't have a call site, called by the interpreter.
&Loc {
module: "".into(),
line_start: 0,
col_start: 0,
byte_offset_start: 0,
line_end: 0,
col_end: 0,
byte_offset_end: 0,
},
);
}
macro_rules! generate_tags {
($($name:ident),* $(,)?) => {
generate_tags!(@generate 0, $($name),*);
};
(@generate $index:expr, $name:ident $(, $rest:ident)*) => {
const $name: u64 = $index;
generate_tags!(@generate $index + 1, $($rest),*);
};
(@generate $index:expr,) => {};
}
#[rustfmt::skip]
generate_tags!(
CONSTR_TYPE_TAG, // Constructor closure, e.g. `Option.Some`.
TOP_FUN_TYPE_TAG, // Top-level function closure, e.g. `id`.
ASSOC_FUN_TYPE_TAG, // Associated function closure, e.g. `Value.toString`.
FIRST_TYPE_TAG, // First available type tag for user types.
);
#[derive(Debug, Default)]
struct Pgm {
/// Type constructors by type name.
///
/// These don't include records.
///
/// This can be used when allocating.
ty_cons: Map<SmolStr, TyCon>,
/// Maps object tags to constructor info.
cons_by_tag: Vec<Con>,
/// Type tags of records.
///
/// This can be used to get the tag of a record, from a record pattern, value, or type.
record_ty_tags: Map<RecordShape, u64>,
/// Associated functions, indexed by type tag, then function name.
associated_funs: Vec<Map<SmolStr, Fun>>,
/// Top-level functions, indexed by function name.
top_level_funs: Map<SmolStr, Fun>,
/// Same as `top_level_funs`, but indexed by the function index.
top_level_funs_by_idx: Vec<Fun>,
// Some allocations and type tags for the built-ins.
true_alloc: u64,
false_alloc: u64,
char_ty_tag: u64,
str_ty_tag: u64,
str_view_ty_tag: u64,
i32_ty_tag: u64,
array_ty_tag: u64,
}
#[derive(Debug)]
struct Con {
info: ConInfo,
fields: Fields,
/// For constructors with no fields, this holds the canonical allocation.
alloc: Option<u64>,
}
#[derive(Debug)]
enum ConInfo {
Named {
ty_name: SmolStr,
con_name: Option<SmolStr>,
},
Record {
#[allow(unused)]
shape: RecordShape,
},
}
#[derive(Debug, Clone)]
struct TyCon {
/// Constructors of the type. E.g. `Some` and `None` in `Option`.
///
/// Sorted based on tags.
value_constrs: Vec<ValCon>,
/// Type tag of the first value constructor of this type.
///
/// For product types, this is the only tag values of this type use.
///
/// For sum types, this is the first tag the values use.
type_tag: u64,
}
impl TyCon {
/// First and last tag (inclusive) that values of this type use.
///
/// For product types, the tags will be the same, as there's only one tag.
fn tag_range(&self) -> (u64, u64) {
(
self.type_tag,
self.type_tag + (self.value_constrs.len() as u64) - 1,
)
}
fn get_constr_with_tag(&self, name: &str) -> (u64, &Fields) {
let (idx, constr) = self
.value_constrs
.iter()
.enumerate()
.find(|(_, constr)| constr.name.as_ref().map(|s| s.as_str()) == Some(name))
.unwrap();
(self.type_tag + idx as u64, &constr.fields)
}
}
/// A value constructor, e.g. `Some`, `None`.
#[derive(Debug, Clone)]
struct ValCon {
/// Name of the constructor, e.g. `True` and `False` in `Bool`.
///
/// In product types, there will be only one `ValCon` and the `name` will be `None`.
name: Option<SmolStr>,
/// Fields of the constructor, with names.
///
/// Either all of the fields or none of them should be named.
fields: Fields,
}
#[derive(Debug, Clone)]
struct Fun {
/// Index of the function in `top_level_funs_by_idx` (if top-level function), or
/// `associated_funs_by_idx` (if associated function).
idx: u64,
kind: FunKind,
}
#[derive(Debug, Clone)]
enum FunKind {
Builtin(BuiltinFun),
Source(ast::FunDecl),
}
#[derive(Debug, Clone)]
enum Fields {
Unnamed(u32),
// NB. The vec shouldn't be empty. For nullary constructors use `Unnamed(0)`.
Named(Vec<SmolStr>),
}
impl Fields {
fn is_empty(&self) -> bool {
matches!(self, Fields::Unnamed(0))
}
fn find_named_field_idx(&self, name: &str) -> u64 {
match self {
Fields::Unnamed(_) => panic!(),
Fields::Named(fields) => fields
.iter()
.enumerate()
.find(|(_, f)| f.as_str() == name)
.map(|(idx, _)| idx as u64)
.unwrap(),
}
}
}
const INITIAL_HEAP_SIZE_WORDS: usize = (1024 * 1024 * 1024) / 8; // 1 GiB
#[derive(Debug)]
enum ControlFlow {
/// Continue with the next statement.
Val(u64),
/// Return value from the function.
Ret(u64),
}
macro_rules! val {
($expr:expr) => {
match $expr {
ControlFlow::Val(val) => val,
ControlFlow::Ret(val) => return ControlFlow::Ret(val),
}
};
}
impl Pgm {
fn new(pgm: Vec<L<ast::TopDecl>>, heap: &mut Heap) -> Pgm {
// Initialize `ty_cons`.
let (ty_cons, mut next_type_tag): (Map<SmolStr, TyCon>, u64) = init::collect_types(&pgm);
fn convert_record(shape: &RecordShape) -> Fields {
match shape {
RecordShape::UnnamedFields { arity } => Fields::Unnamed(*arity),
RecordShape::NamedFields { fields } => Fields::Named(fields.clone()),
}
}
let mut cons_by_tag: Vec<Con> = vec![];
let mut ty_cons_sorted: Vec<(SmolStr, TyCon)> = ty_cons
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
ty_cons_sorted.sort_by_key(|(_, ty_con)| ty_con.type_tag);
for (ty_name, ty_con) in ty_cons_sorted {
if ty_con.value_constrs.is_empty() {
// A built-in type with no constructors.
cons_by_tag.push(Con {
info: ConInfo::Named {
ty_name,
con_name: None,
},
fields: Fields::Unnamed(0),
alloc: None,
});
} else {
for constr in ty_con.value_constrs {
let alloc: Option<u64> = if constr.fields.is_empty() {
Some(heap.allocate_tag(cons_by_tag.len() as u64))
} else {
None
};
cons_by_tag.push(Con {
info: ConInfo::Named {
ty_name: ty_name.clone(),
con_name: constr.name.clone(),
},
fields: constr.fields.clone(),
alloc,
});
}
}
}
// Initialize `record_ty_tags`.
let record_shapes: Set<RecordShape> = collect_records(&pgm);
let mut record_ty_tags: Map<RecordShape, u64> = Default::default();
for record_shape in record_shapes {
let fields = convert_record(&record_shape);
cons_by_tag.push(Con {
info: ConInfo::Record {
shape: record_shape.clone(),
},
fields,
alloc: None,
});
record_ty_tags.insert(record_shape, next_type_tag);
next_type_tag += 1;
}
// Initialize `associated_funs` and `top_level_funs`.
let (top_level_funs, associated_funs) = init::collect_funs(pgm);
let mut associated_funs_vec: Vec<Map<SmolStr, Fun>> =
vec![Default::default(); next_type_tag as usize];
for (ty_name, funs) in associated_funs {
let ty_con = ty_cons
.get(&ty_name)
.unwrap_or_else(|| panic!("Type not defined: {}", ty_name));
let first_tag = ty_cons.get(&ty_name).unwrap().type_tag as usize;
let n_constrs = ty_con.value_constrs.len();
if n_constrs == 0 {
// A built-in type with no constructor.
associated_funs_vec[first_tag] = funs;
} else {
for tag in first_tag..first_tag + n_constrs {
associated_funs_vec[tag].clone_from(&funs);
}
}
}
// Initialize `top_level_funs_by_idx`.
let mut top_level_funs_vec: Vec<(SmolStr, Fun)> = top_level_funs
.iter()
.map(|(k, v)| (k.clone(), v.clone()))
.collect();
top_level_funs_vec.sort_by_key(|(_, fun)| fun.idx);
let top_level_funs_by_idx = top_level_funs_vec.into_iter().map(|(_, f)| f).collect();
let bool_ty_con: &TyCon = ty_cons.get("Bool").as_ref().unwrap();
assert_eq!(
bool_ty_con.value_constrs[0].name,
Some(SmolStr::new("False"))
);
assert_eq!(
bool_ty_con.value_constrs[1].name,
Some(SmolStr::new("True"))
);
let false_alloc = cons_by_tag[bool_ty_con.type_tag as usize].alloc.unwrap();
let true_alloc = cons_by_tag[bool_ty_con.type_tag as usize + 1]
.alloc
.unwrap();
let char_ty_tag = ty_cons.get("Char").as_ref().unwrap().type_tag;
let str_ty_tag = ty_cons.get("Str").as_ref().unwrap().type_tag;
let str_view_ty_tag = ty_cons.get("StrView").as_ref().unwrap().type_tag;
let i32_ty_tag = ty_cons.get("I32").as_ref().unwrap().type_tag;
let array_ty_tag = ty_cons.get("Array").as_ref().unwrap().type_tag;
Pgm {
ty_cons,
cons_by_tag,
record_ty_tags,
associated_funs: associated_funs_vec,
top_level_funs,
top_level_funs_by_idx,
false_alloc,
true_alloc,
char_ty_tag,
str_ty_tag,
str_view_ty_tag,
i32_ty_tag,
array_ty_tag,
}
}
fn get_tag_fields(&self, tag: u64) -> &Fields {
&self.cons_by_tag[tag as usize].fields
}
fn bool_alloc(&self, b: bool) -> u64 {
if b {
self.true_alloc
} else {
self.false_alloc
}
}
}
fn call<W: Write>(
w: &mut W,
pgm: &Pgm,
heap: &mut Heap,
fun: &Fun,
args: Vec<u64>,
loc: &Loc,
) -> u64 {
match &fun.kind {
FunKind::Builtin(builtin) => call_builtin_fun(w, pgm, heap, builtin, args, loc),
FunKind::Source(source) => call_source_fun(w, pgm, heap, source, args, loc),
}
}
fn call_method<W: Write>(
w: &mut W,
pgm: &Pgm,
heap: &mut Heap,
receiver: u64,
method: &SmolStr,
mut args: Vec<u64>,
loc: &Loc,
) -> u64 {
let tag = heap[receiver];
let fun = pgm.associated_funs[tag as usize]
.get(method)
.unwrap_or_else(|| panic!("Receiver with tag {} does not have {} method", tag, method));
args.insert(0, receiver);
call(w, pgm, heap, fun, args, loc)
}
fn call_source_fun<W: Write>(
w: &mut W,
pgm: &Pgm,
heap: &mut Heap,
fun: &ast::FunDecl,
args: Vec<u64>,
loc: &Loc,
) -> u64 {
assert_eq!(
fun.num_params(),
args.len() as u32,
"{}, fun: {}",
LocDisplay(loc),
fun.name.node
);
let mut locals: Map<SmolStr, u64> = Default::default();
let mut arg_idx: usize = 0;
if fun.self_ {
locals.insert(SmolStr::new("self"), args[0]);
arg_idx += 1;
}
for (param_name, _param_type) in &fun.params {
let old = locals.insert(param_name.clone(), args[arg_idx]);
assert!(old.is_none());
arg_idx += 1;
}
match exec(w, pgm, heap, &mut locals, &fun.body.as_ref().unwrap().node) {
ControlFlow::Val(val) | ControlFlow::Ret(val) => val,
}
}
/// Allocate an object from type name and optional constructor name.
fn allocate_object_from_names<W: Write>(
w: &mut W,
pgm: &Pgm,
heap: &mut Heap,
locals: &mut Map<SmolStr, u64>,
ty: &SmolStr,
constr_name: Option<SmolStr>,
args: &[ast::CallArg],
loc: &Loc,
) -> ControlFlow {
let ty_con = pgm
.ty_cons
.get(ty)
.unwrap_or_else(|| panic!("Undefined type {} at {}", ty, LocDisplay(loc)));
let constr_idx = match constr_name {
Some(constr_name) => {
let (constr_idx_, _) = ty_con
.value_constrs
.iter()
.enumerate()
.find(|(_, constr)| constr.name.as_ref() == Some(&constr_name))
.unwrap_or_else(|| {
panic!(
"Type {} does not have a constructor named {}",
ty, constr_name
)
});
constr_idx_
}
None => {
assert_eq!(ty_con.value_constrs.len(), 1);
0
}
};
allocate_object_from_tag(
w,
pgm,
heap,
locals,
ty_con.type_tag + constr_idx as u64,
args,
)
}
/// Allocate an object from a constructor tag and fields.
fn allocate_object_from_tag<W: Write>(
w: &mut W,
pgm: &Pgm,
heap: &mut Heap,
locals: &mut Map<SmolStr, u64>,
constr_tag: u64,
args: &[ast::CallArg],
) -> ControlFlow {
let fields = pgm.get_tag_fields(constr_tag);
let mut arg_values = Vec::with_capacity(args.len());
match fields {
Fields::Unnamed(num_fields) => {
// Evaluate in program order and store in the same order.
assert_eq!(*num_fields as usize, args.len());
for arg in args {
assert!(arg.name.is_none());
arg_values.push(val!(eval(w, pgm, heap, locals, &arg.expr)));
}
}
Fields::Named(field_names) => {
// Evalaute in program order, store based on the order of the names
// in the type.
let mut named_values: Map<SmolStr, u64> = Default::default();
for arg in args {
let name = arg.name.as_ref().unwrap().clone();
let value = val!(eval(w, pgm, heap, locals, &arg.expr));
let old = named_values.insert(name.clone(), value);
assert!(old.is_none());
}
for name in field_names {
arg_values.push(*named_values.get(name).unwrap());
}
}
}
let object = heap.allocate(1 + args.len());
heap[object] = constr_tag;
for (arg_idx, arg_value) in arg_values.into_iter().enumerate() {
heap[object + 1 + (arg_idx as u64)] = arg_value;
}
ControlFlow::Val(object)
}
fn exec<W: Write>(
w: &mut W,
pgm: &Pgm,
heap: &mut Heap,
locals: &mut Map<SmolStr, u64>,
stmts: &[L<ast::Stmt>],
) -> ControlFlow {
let mut return_value: u64 = 0;
for stmt in stmts {
return_value = match &stmt.node {
ast::Stmt::Let(ast::LetStmt { lhs, ty: _, rhs }) => {
let val = val!(eval(w, pgm, heap, locals, rhs));
match try_bind_pat(pgm, heap, lhs, val) {
Some(binds) => locals.extend(binds.into_iter()),
None => panic!("Pattern binding at {} failed", LocDisplay(&stmt.loc)),
}
val
}
ast::Stmt::Assign(ast::AssignStmt { lhs, rhs, op }) => {
let rhs = val!(eval(w, pgm, heap, locals, rhs));
val!(assign(w, pgm, heap, locals, lhs, rhs, *op, &stmt.loc))
}
ast::Stmt::Expr(expr) => val!(eval(w, pgm, heap, locals, expr)),
ast::Stmt::While(ast::WhileStmt { cond, body }) => loop {
let cond = val!(eval(w, pgm, heap, locals, cond));
debug_assert!(cond == pgm.true_alloc || cond == pgm.false_alloc);
if cond == pgm.false_alloc {
break 0; // FIXME: Return unit
}
match exec(w, pgm, heap, locals, body) {
ControlFlow::Val(_val) => {}
ControlFlow::Ret(val) => return ControlFlow::Ret(val),
}
},
ast::Stmt::For(ast::ForStmt {
var,
ty: _,
expr,
body,
}) => {
let (from, to, inclusive) = match &expr.node {
ast::Expr::Range(ast::RangeExpr {
from,
to,
inclusive,
}) => (from, to, inclusive),
_ => panic!(
"Interpreter only supports for loops with a range expression in the head"
),
};
let from = val!(eval(w, pgm, heap, locals, from));
debug_assert_eq!(heap[from], pgm.i32_ty_tag);
let from = heap[from + 1] as i32;
let to = val!(eval(w, pgm, heap, locals, to));
debug_assert_eq!(heap[to], pgm.i32_ty_tag);
let to = heap[to + 1] as i32;
if *inclusive {
for i in from..=to {
let iter_value = heap.allocate_i32(pgm.i32_ty_tag, i);
locals.insert(var.clone(), iter_value);
match exec(w, pgm, heap, locals, body) {
ControlFlow::Val(_) => {}
ControlFlow::Ret(val) => {
locals.remove(var);
return ControlFlow::Ret(val);
}
}
}
} else {
for i in from..to {
let iter_value = heap.allocate_i32(pgm.i32_ty_tag, i);
locals.insert(var.clone(), iter_value);
match exec(w, pgm, heap, locals, body) {
ControlFlow::Val(_) => {}
ControlFlow::Ret(val) => {
locals.remove(var);
return ControlFlow::Ret(val);
}
}
}
}
locals.remove(var);
0
}
};
}
ControlFlow::Val(return_value)
}
fn eval<W: Write>(
w: &mut W,
pgm: &Pgm,
heap: &mut Heap,
locals: &mut Map<SmolStr, u64>,
expr: &L<ast::Expr>,
) -> ControlFlow {
match &expr.node {
ast::Expr::Var(var) => match locals.get(var) {
Some(value) => ControlFlow::Val(*value),
None => match pgm.top_level_funs.get(var) {
Some(top_fun) => ControlFlow::Val(heap.allocate_top_fun(top_fun.idx)),
None => panic!("{}: unbound variable: {}", LocDisplay(&expr.loc), var),
},
},
ast::Expr::UpperVar(ty_name) => {
let ty_con = pgm.ty_cons.get(ty_name).unwrap();
let ty_tag = ty_con.type_tag;
let (first_tag, last_tag) = ty_con.tag_range();
assert_eq!(first_tag, last_tag);
ControlFlow::Val(heap.allocate_constr(ty_tag))
}
ast::Expr::FieldSelect(ast::FieldSelectExpr { object, field }) => {
let object = val!(eval(w, pgm, heap, locals, object));
let object_tag = heap[object];
let fields = pgm.get_tag_fields(object_tag);
match fields {
Fields::Unnamed(_) => panic!(
"{}: FieldSelect of {} with unnamed fields, field = {}",
LocDisplay(&expr.loc),
object_tag,
field,
),
Fields::Named(fields) => {
let (field_idx, _) = fields
.iter()
.enumerate()
.find(|(_, field_)| *field_ == field)
.unwrap();
ControlFlow::Val(heap[object + 1 + (field_idx as u64)])
}
}
}
ast::Expr::ConstrSelect(ast::ConstrSelectExpr {
ty,
constr: constr_name,
}) => {
let ty_con = pgm.ty_cons.get(ty).unwrap();
let (constr_idx, constr) = ty_con
.value_constrs
.iter()
.enumerate()
.find(|(_constr_idx, constr)| constr.name.as_ref().unwrap() == constr_name)
.unwrap();
let tag = ty_con.type_tag + (constr_idx as u64);
ControlFlow::Val(if constr.fields.is_empty() {
let addr = heap.allocate(1);
heap[addr] = tag;
addr
} else {
heap.allocate_constr(tag)
})
}
ast::Expr::Call(ast::CallExpr { fun, args }) => {
// See if `fun` is a method or function and avoid tear-off allocations for
// performance (and also because we don't support method tear-offs right now).
let fun: u64 = match &fun.node {
ast::Expr::Var(var) => match locals.get(var) {
Some(val) => *val,
None => match pgm.top_level_funs.get(var) {
Some(fun) => {
let mut arg_values: Vec<u64> = Vec::with_capacity(args.len());
for arg in args {
arg_values.push(val!(eval(w, pgm, heap, locals, &arg.expr)));
}
return ControlFlow::Val(call(
w, pgm, heap, fun, arg_values, &expr.loc,
));
}
None => val!(eval(w, pgm, heap, locals, fun)),
},
},
ast::Expr::FieldSelect(ast::FieldSelectExpr { object, field }) => {
if let ast::Expr::UpperVar(ty) = &object.node {
let ty_con = pgm
.ty_cons
.get(ty)
.unwrap_or_else(|| panic!("Undefined type: {}", ty));
// Handle `Type.Constructor`.
if field.chars().next().unwrap().is_uppercase() {
return allocate_object_from_names(
w,
pgm,
heap,
locals,
ty,
Some(field.clone()),
args,
&expr.loc,
);
} else {
// Handle `Type.associatedFunction`.
let fun = pgm.associated_funs[ty_con.type_tag as usize]
.get(field)
.unwrap_or_else(|| {
panic!(
"Type {} does not have associated function {}",
ty, field
)
});
let mut arg_vals: Vec<u64> = Vec::with_capacity(args.len());
for arg in args {
arg_vals.push(val!(eval(w, pgm, heap, locals, &arg.expr)));
}
return ControlFlow::Val(call(w, pgm, heap, fun, arg_vals, &expr.loc));
}
}
let object = val!(eval(w, pgm, heap, locals, object));
let object_tag = heap[object];
let fun = pgm.associated_funs[object_tag as usize]
.get(field)
.unwrap_or_else(|| {
panic!(
"{}: Object with tag {} doesn't have field or method {:?}",
LocDisplay(&expr.loc),
object_tag,
field
)
});
let mut arg_vals: Vec<u64> = Vec::with_capacity(args.len());
for arg in args {
arg_vals.push(val!(eval(w, pgm, heap, locals, &arg.expr)));
}
arg_vals.insert(0, object);
return ControlFlow::Val(call(w, pgm, heap, fun, arg_vals, &expr.loc));
}
ast::Expr::UpperVar(ty) => {
return allocate_object_from_names(
w, pgm, heap, locals, ty, None, args, &expr.loc,
);
}
_ => val!(eval(w, pgm, heap, locals, fun)),
};
match heap[fun] {
CONSTR_TYPE_TAG => {
let constr_tag = heap[fun + 1];
allocate_object_from_tag(w, pgm, heap, locals, constr_tag, args)
}
TOP_FUN_TYPE_TAG => {
let top_fun_idx = heap[fun + 1];
let top_fun = &pgm.top_level_funs_by_idx[top_fun_idx as usize];
let mut arg_values: Vec<u64> = Vec::with_capacity(args.len());
for arg in args {
assert!(arg.name.is_none());
arg_values.push(val!(eval(w, pgm, heap, locals, &arg.expr)));
}
ControlFlow::Val(call(w, pgm, heap, top_fun, arg_values, &expr.loc))
}
ASSOC_FUN_TYPE_TAG => {
let _ty_tag = heap[fun + 1];
let _fun_tag = heap[fun + 2];
todo!()
}
_ => panic!("Function evaluated to non-callable"),
}
}
ast::Expr::Int(i) => ControlFlow::Val(heap.allocate_i32(pgm.i32_ty_tag, *i)),
ast::Expr::String(parts) => {
let mut bytes: Vec<u8> = vec![];
for part in parts {
match part {
StringPart::Str(str) => bytes.extend(str.as_bytes()),
StringPart::Expr(expr) => {
let part_val = val!(eval(w, pgm, heap, locals, expr));
// Call toStr
let part_str_val =
call_method(w, pgm, heap, part_val, &"toStr".into(), vec![], &expr.loc);
assert_eq!(heap[part_str_val], pgm.str_ty_tag);
let part_bytes = heap.str_bytes(part_str_val);
bytes.extend(part_bytes);
}
}
}
ControlFlow::Val(heap.allocate_str(pgm.str_ty_tag, &bytes))
}
ast::Expr::Self_ => ControlFlow::Val(*locals.get("self").unwrap()),
ast::Expr::BinOp(ast::BinOpExpr { left, right, op }) => {
let left = val!(eval(w, pgm, heap, locals, left));
let right = val!(eval(w, pgm, heap, locals, right));
let method_name = match op {
ast::BinOp::Add => "__add",
ast::BinOp::Subtract => "__sub",
ast::BinOp::Multiply => "__mul",
ast::BinOp::Equal => {
let eq = eq(w, pgm, heap, left, right, &expr.loc);
return ControlFlow::Val(pgm.bool_alloc(eq));
}
ast::BinOp::NotEqual => {
let eq = eq(w, pgm, heap, left, right, &expr.loc);
return ControlFlow::Val(pgm.bool_alloc(!eq));
}
ast::BinOp::Lt => {
let ord = cmp(w, pgm, heap, left, right, &expr.loc);
return ControlFlow::Val(pgm.bool_alloc(matches!(ord, Ordering::Less)));
}
ast::BinOp::Gt => {
let ord = cmp(w, pgm, heap, left, right, &expr.loc);
return ControlFlow::Val(pgm.bool_alloc(matches!(ord, Ordering::Greater)));
}
ast::BinOp::LtEq => {
let ord = cmp(w, pgm, heap, left, right, &expr.loc);
return ControlFlow::Val(
pgm.bool_alloc(matches!(ord, Ordering::Less | Ordering::Equal)),
);
}
ast::BinOp::GtEq => {
let ord = cmp(w, pgm, heap, left, right, &expr.loc);
return ControlFlow::Val(
pgm.bool_alloc(matches!(ord, Ordering::Greater | Ordering::Equal)),
);
}
ast::BinOp::And => "__and",
ast::BinOp::Or => "__or",
};
ControlFlow::Val(call_method(
w,
pgm,
heap,
left,
&method_name.into(),
vec![right],
&expr.loc,
))
}
ast::Expr::UnOp(ast::UnOpExpr { op, expr }) => {
let val = val!(eval(w, pgm, heap, locals, expr));
debug_assert!(val == pgm.true_alloc || val == pgm.false_alloc);
match op {
ast::UnOp::Not => ControlFlow::Val(pgm.bool_alloc(val == pgm.false_alloc)),
}
}
ast::Expr::ArrayIndex(ast::ArrayIndexExpr { array, index }) => {
let array = val!(eval(w, pgm, heap, locals, array));
let index_boxed = val!(eval(w, pgm, heap, locals, index));
let index = heap[index_boxed + 1];
let array_len = heap[array + 1];
if index >= array_len {
panic!("OOB array access, len = {}, index = {}", array_len, index);
}
ControlFlow::Val(heap[array + 2 + index])
}
ast::Expr::Record(exprs) => {
let shape = RecordShape::from_named_things(exprs);
let type_tag = *pgm.record_ty_tags.get(&shape).unwrap();
let record = heap.allocate(exprs.len() + 1);
heap[record] = type_tag;
if !exprs.is_empty() && exprs[0].name.is_some() {
heap[record] = type_tag;
let mut names: Vec<SmolStr> = exprs
.iter()
.map(|ast::Named { name, node: _ }| name.as_ref().unwrap().clone())
.collect();
names.sort();
for (name_idx, name_) in names.iter().enumerate() {
let expr = exprs
.iter()
.find_map(|ast::Named { name, node }| {
if name.as_ref().unwrap() == name_ {
Some(node)
} else {
None
}
})
.unwrap();
let value = val!(eval(w, pgm, heap, locals, expr));
heap[record + (name_idx as u64) + 1] = value;
}
} else {
for (idx, ast::Named { name: _, node }) in exprs.iter().enumerate() {
let value = val!(eval(w, pgm, heap, locals, node));
heap[record + (idx as u64) + 1] = value;
}
}
ControlFlow::Val(record)
}
ast::Expr::Range(_) => {
panic!("Interpreter only supports range expressions in for loops")
}
ast::Expr::Return(expr) => ControlFlow::Ret(val!(eval(w, pgm, heap, locals, expr))),
ast::Expr::Match(ast::MatchExpr { scrutinee, alts }) => {
let scrut = val!(eval(w, pgm, heap, locals, scrutinee));
for ast::Alt {
pattern,
guard,
rhs,
} in alts
{
assert!(guard.is_none()); // TODO
if let Some(binds) = try_bind_pat(pgm, heap, pattern, scrut) {
locals.extend(binds.into_iter());
return exec(w, pgm, heap, locals, rhs);
}
}
panic!("Non-exhaustive pattern match");
}
ast::Expr::If(ast::IfExpr {
branches,