1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
use crate::gc::{Gc, GcObject, Reg};
use crate::stdlib::load_std;
use std::cell::RefCell;
use std::fmt::Write;
use std::{ffi::OsStr, rc::Rc};
use ahash::{AHashMap, AHashSet};
use codespan_reporting::diagnostic::Label;
use either::Either;
mod error;
mod prelude;
mod register_table;
mod scanner;
mod api;
use crate::file_manager::FileManager;
use crate::vm::op::{
OpGe, OpGetTable, OpGetTuple, OpIndex, OpIs, OpLe, OpLt, OpMakeList, OpMakeTable, OpMakeTuple,
OpNe, OpSetIndex, OpSetMeta, OpSetTable, OpSetTuple,
};
use crate::{
file_manager::{Diagnostic, Loc},
frontend::{
parser::ast::{Const, Expr, OpInfix, OpPrefix, Stmt},
Parser,
},
vm::{
error::VmError,
op::{
OpAdd, OpAllocReg, OpBranchFalse, OpBranchTrue, OpCall, OpDiv, OpDummy, OpEq, OpGt,
OpIDiv, OpJump, OpMakeClosure, OpMove, OpMul, OpNeg, OpNot, OpPow, OpRem, OpRet, OpSub,
OpYield,
},
Instruction, Vm, VmInst,
},
DiatomValue, IoWrite,
};
pub use api::State;
use error::ErrorCode;
use prelude::impl_prelude;
pub use register_table::Capture;
use register_table::{ConstantValue, Loop, RegisterTable};
use self::scanner::{CaptureScanner, ConstScanner};
#[derive(Clone)]
pub struct FutureJump {
condition_reg: Option<(usize, bool)>,
inst_offset: usize,
loc: Loc,
}
impl FutureJump {
/// Insert jump from current loc to previous
pub fn patch_backward(self, func: &mut Func) {
let jump_offset = self.inst_offset as i64 - func.insts.len() as i64;
let op = if let Some((reg, on_false)) = self.condition_reg {
if on_false {
VmInst::OpBranchFalse(OpBranchFalse {
loc: self.loc,
condition: reg,
offset: jump_offset,
})
} else {
VmInst::OpBranchTrue(OpBranchTrue {
loc: self.loc,
condition: reg,
offset: jump_offset,
})
}
} else {
VmInst::OpJump(OpJump {
loc: self.loc,
offset: jump_offset,
})
};
func.insts.push(op);
}
/// Insert jump from previous to current
pub fn patch_forward(self, func: &mut Func) {
let jump_offset = func.insts.len() as i64 - self.inst_offset as i64;
let op = if let Some((reg, on_false)) = self.condition_reg {
if on_false {
VmInst::OpBranchFalse(OpBranchFalse {
loc: self.loc,
condition: reg,
offset: jump_offset,
})
} else {
VmInst::OpBranchTrue(OpBranchTrue {
loc: self.loc,
condition: reg,
offset: jump_offset,
})
}
} else {
VmInst::OpJump(OpJump {
loc: self.loc,
offset: jump_offset,
})
};
func.insts[self.inst_offset] = op;
}
}
pub struct Func {
pub id: usize,
pub parameters: usize,
pub insts: Vec<VmInst>,
}
/// # The Diatom Interpreter
///
/// High performance interpreter for the diatom programming language. This interpreter compiles
/// diatom source code into byte code and executes the byte code with carefully tuned virtual
/// machine. Our benchmark shows it can match or even surpass the execution speed of Lua 5.4 .
///
/// # Example
///
/// ## 1. Run a piece of code
/// ```
/// use diatom::Interpreter;
///
/// // Create a new instance of interpreter
/// // Enable colored output
/// let mut interpreter = Interpreter::with_color(std::io::stdout());
/// // Execute source code
/// let output = interpreter.exec(
/// "print('Hello, world!')",
/// Default::default()
/// ).unwrap();
/// ```
///
/// ## 2. Add call back to the interpreter
/// ```
/// use std::{cell::Cell, rc::Rc};
/// use diatom::{DiatomValue, Interpreter};
///
/// // this value will be modified
/// let value = Rc::new(Cell::new(0));
/// let value_capture = value.clone();
///
/// let mut interpreter = Interpreter::new(std::io::stdout());
/// // add a callback named "set_value"
/// interpreter.add_extern_function("set_value", move |_state, parameters, _out| {
/// if parameters.len() != 1 {
/// return Err("Expected 1 parameter!".to_string());
/// }
/// match parameters[0] {
/// DiatomValue::Int(i) => {
/// value_capture.set(i);
/// Ok(DiatomValue::Unit)
/// }
/// _ => Err("Invalid type".to_string()),
/// }
/// });
///
/// // change value to 5
/// interpreter.exec("set_value(5)", Default::default()).unwrap();
/// assert_eq!(value.get(), 5);
/// ```
pub struct Interpreter<Buffer: IoWrite> {
registers: RegisterTable,
scopes: Vec<AHashSet<String>>,
byte_code: Vec<Func>,
vm: Vm,
gc: Gc<Buffer>,
out: Buffer,
file_manager: FileManager,
color: bool,
}
impl<Buffer: IoWrite> Interpreter<Buffer> {
/// Create a new interpreter instance
pub fn new(buffer: Buffer) -> Self {
Self::init(buffer, false)
}
fn init(buffer: Buffer, color: bool) -> Self {
let main = Func {
id: 0,
parameters: 0,
insts: vec![],
};
let mut interpreter = Self {
registers: RegisterTable::new(0),
scopes: vec![AHashSet::new()],
byte_code: vec![main],
vm: Vm::new(),
gc: Gc::new(),
out: buffer,
file_manager: FileManager::new(),
color,
};
// Initialize int and float meta table
let int = interpreter.registers.declare_variable("Int", None);
interpreter.gc.alloc_reg_file(int + 1);
interpreter.gc.set_main_reg_size(int + 1);
interpreter
.gc
.write_reg(int, Reg::Ref(interpreter.gc.int_meta()));
let float = interpreter.registers.declare_variable("Float", None);
interpreter.gc.alloc_reg_file(float + 1);
interpreter.gc.set_main_reg_size(float + 1);
interpreter
.gc
.write_reg(float, Reg::Ref(interpreter.gc.float_meta()));
let list = interpreter.registers.declare_variable("List", None);
interpreter.gc.alloc_reg_file(list + 1);
interpreter.gc.set_main_reg_size(list + 1);
interpreter
.gc
.write_reg(list, Reg::Ref(interpreter.gc.list_meta()));
let gc = interpreter.registers.declare_variable("Gc", None);
interpreter.gc.alloc_reg_file(gc + 1);
interpreter.gc.set_main_reg_size(gc + 1);
interpreter
.gc
.write_reg(gc, Reg::Ref(interpreter.gc.gc_meta()));
impl_prelude(&mut interpreter);
load_std(&mut interpreter);
interpreter
}
/// Enable ansi colored error message
pub fn with_color(buffer: Buffer) -> Self {
Self::init(buffer, true)
}
/// Register an external rust function
///
/// This function does not accept due to potential recursive calls on a FnMut would violating
/// borrow rules. You may want to use interior mutability if Fn is not flexible enough.
/// External function should **NEVER PANIC**, otherwise it will crush the virtual machine.
///
/// # External function parameters:
/// * `State` - Access state and heap memory of the virtual machine.
/// * `[DiatomValue]` - Parameters passed. The function is expected to check type and the
/// number of parameters it received.
/// * `Buffer` - Output buffer
///
/// # External function return value:
/// * Return a single unboxed value as return value. If the function does not intended to
/// return anything, return an unit type `DiatomValue::Unit`.
/// * If any unrecoverable error happens, return an `Err(String)` that illustrates the error.
/// This will cause virtual machine to enter **panic mode** and stop execution.
/// * If return value is `DiatomValue::Str` or `DiatomValue::Ref`, the reference id is checked.
/// An invalid id would cause virtual machine to enter **panic mode** and stop execution.
///
/// # Examples:
/// ```
/// use std::io::Write;
/// use diatom::{Interpreter, DiatomValue};
///
/// let buffer = Vec::<u8>::new();
/// let mut interpreter = Interpreter::new(buffer);
/// interpreter.add_extern_function(
/// "hello_world",
/// |state, parameters, out| {
/// if !parameters.is_empty(){
/// Err("Too many parameters!".to_string())
/// }else{
/// write!(out, "Hello, world!");
/// Ok(DiatomValue::Unit)
/// }
/// }
/// );
///
/// interpreter.exec("hello_world()", Default::default()).unwrap();
/// let output = interpreter.replace_buffer(Vec::<u8>::new());
/// let output = String::from_utf8(output).unwrap();
/// assert_eq!(output, "Hello, world!")
/// ```
pub fn add_extern_function<F>(&mut self, name: impl Into<String>, f: F)
where
F: Fn(&mut State<Buffer>, &[DiatomValue], &mut Buffer) -> Result<DiatomValue, String>
+ 'static,
{
let f = GcObject::NativeFunction(Rc::new(RefCell::new(f)));
let gc_id = self.gc.alloc_obj(f);
let reg = Reg::Ref(gc_id);
let reg_id = self.registers.declare_variable(name.into(), None);
self.gc.alloc_reg_file(reg_id + 1);
self.gc.set_main_reg_size(reg_id + 1);
self.gc.write_reg(reg_id, reg);
}
/// Check if input is completeness
///
/// Incomplete input usually contains unclosed parentheses, quotes or open expression.
pub fn verify_input_completeness(code: impl AsRef<str>) -> bool {
let mut file_manager = FileManager::new();
let mut parser = Parser::new(&mut file_manager);
let _ = parser.parse_file(Either::Left((OsStr::new(""), code.as_ref())));
!file_manager.input_can_continue()
}
/// Show decompiled byte code for given source code.
///
/// If compilation failed, `Err` will be returned.
pub fn decompile(&mut self, code: impl AsRef<str>, source: &OsStr) -> Result<String, String> {
self.compile(code, source)?;
let mut decompiled = String::new();
for Func {
id,
parameters,
insts,
} in self.byte_code.iter()
{
writeln!(decompiled, "Function: Func@{id}\nParameters: {parameters}").unwrap();
writeln!(decompiled, "Body:").unwrap();
let pad = insts.len().ilog10() as usize + 1;
for (n, inst) in insts.iter().enumerate() {
write!(decompiled, " {n: <pad$} ").unwrap();
inst.decompile(&mut decompiled, &self.gc);
}
writeln!(decompiled).unwrap();
}
Ok(decompiled)
}
/// Replace output buffer and get the old one
pub fn replace_buffer(&mut self, buffer: Buffer) -> Buffer {
std::mem::replace(&mut self.out, buffer)
}
fn compile(&mut self, code: impl AsRef<str>, source: &OsStr) -> Result<(), String> {
self.file_manager.clear_diagnoses();
let mut parser = Parser::new(&mut self.file_manager);
let ast = parser.parse_file(Either::Left((source, code.as_ref())));
if self.file_manager.error_count() > 0 {
return Err(self.file_manager.render(self.color));
}
let registers_prev = self.registers.clone();
// clear all executed code
self.byte_code[0].insts.clear();
self.vm.reset_ip();
let return_value = self.compile_ast(&ast).map_err(|_| {
// restore variable table if compile failed
self.registers = registers_prev;
self.file_manager.render(self.color)
})?;
// return after main
self.byte_code[0].insts.push(VmInst::OpYield(OpYield {
show_id: return_value,
}));
// Alloc registers
self.byte_code[0].insts.insert(
0,
VmInst::OpAllocReg(OpAllocReg {
n_reg: self.registers.assigned,
}),
);
self.gc.set_main_reg_size(self.registers.assigned);
Ok(())
}
/// Run a piece of diatom source code
///
/// # Parameters
/// * `code` - Source code
/// * `source` - name of source code file or where it is from
/// * `color` - render output with ansi color. Set to false if you do not want to print the
/// output to terminal.
///
/// # Return
/// * Return the output of the program
/// * If compilation failed or error occurs durning execution, an `Err(String)` that
/// illustrates the error is returned.
pub fn exec(&mut self, code: impl AsRef<str>, source: &OsStr) -> Result<(), String> {
self.compile(code, source)?;
match self.vm.exec(&self.byte_code, &mut self.gc, &mut self.out) {
(VmError::Yield(_), _) => Ok(()),
(error, trace) => {
self.file_manager.add_diagnostic(error.into(), false);
trace.into_iter().for_each(|loc| {
self.file_manager.add_diagnostic(
Diagnostic::error()
.with_message("Traceback: Panic while invoking")
.with_labels(vec![Label::primary(loc.fid, loc)]),
false,
)
});
Err(self.file_manager.render(self.color))
}
}
}
/// Execute and print last statement's return value
///
/// If return value is unit, then it will not be printed.
pub fn exec_repl(&mut self, code: impl AsRef<str>) -> Result<(), String> {
self.compile(code, OsStr::new("<interactive>"))?;
match self.vm.exec(&self.byte_code, &mut self.gc, &mut self.out) {
(VmError::Yield(None), _) => Ok(()),
(VmError::Yield(Some(reg_id)), _) => {
let reg = self.gc.read_reg(reg_id);
match reg {
Reg::Unit => Ok(()),
_ => {
let content = self.gc.print(reg);
writeln!(self.out, "{content}").map_err(|err| {
let error_code = VmError::IoError {
loc: None,
error: err,
};
self.file_manager.add_diagnostic(error_code.into(), false);
self.file_manager.render(self.color)
})
}
}
}
(error, trace) => {
trace.into_iter().rev().for_each(|loc| {
self.file_manager.add_diagnostic(
Diagnostic::error()
.with_message("Trace back")
.with_labels(vec![Label::primary(loc.fid, loc)]),
false,
)
});
self.file_manager.add_diagnostic(error.into(), false);
Err(self.file_manager.render(self.color))
}
}
}
/// if compile succeeded, return last expression's reg id
fn compile_ast(&mut self, ast: &[Stmt]) -> Result<Option<usize>, ()> {
let mut return_value = None;
let mut has_error = false;
// scan all constant values
let func_id = self.registers.func_id;
let mut const_scanner = ConstScanner {
register_table: &mut self.registers,
gc: &mut self.gc,
insts: &mut self.byte_code[func_id].insts,
};
ast.iter().for_each(|stmt| const_scanner.scan_stmt(stmt));
for (i, stmt) in ast.iter().enumerate() {
match self.compile_stmt(stmt, i != ast.len() - 1, None) {
Ok(ret) => return_value = ret,
Err(code) => {
has_error = true;
self.file_manager
.add_diagnostic(Diagnostic::from(code), false);
}
}
}
if has_error {
Err(())
} else {
Ok(return_value.map(|(reg, _)| reg))
}
}
/// Compile a statement
/// Return value is already properly freed
fn compile_stmt(
&mut self,
stmt: &Stmt,
discard: bool,
target: Option<usize>,
) -> Result<Option<(usize, bool)>, ErrorCode> {
let mut return_value = None;
match stmt {
Stmt::Expr {
loc: _,
expr:
Expr::Infix {
op: OpInfix::Assign,
lhs,
rhs,
..
},
} => self.compile_assignment(lhs, rhs)?,
Stmt::Expr { loc: _, expr } => {
let (reg_id, tmp) = self.compile_expr(expr, discard, target)?;
return_value = Some((reg_id, tmp));
}
Stmt::Loop {
loc,
condition,
body,
} => {
let jump_to_start = FutureJump {
condition_reg: None,
inst_offset: self.get_current_insts().len(),
loc: loc.clone(),
};
let branch_inst = if let Some(condition) = condition {
let (condition_reg, tmp) = self.compile_expr(condition, false, None)?;
if tmp {
self.registers.free_intermediate(condition_reg);
}
self.get_current_insts().push(VmInst::OpDummy(OpDummy));
Some(FutureJump {
condition_reg: Some((condition_reg, false)),
inst_offset: self.get_current_insts().len() - 1,
loc: condition.get_loc(),
})
} else {
None
};
self.enter_block();
let current_inst = self.get_current_insts().len();
self.registers.loops.push(Loop {
start_inst_offset: current_inst,
breaks: vec![],
});
for stmt in body.iter() {
self.compile_stmt(stmt, true, None).map_err(|err| {
self.leave_block();
err
})?;
}
let breaks = self.registers.loops.pop().unwrap().breaks;
self.leave_block();
// patch jump to loop start
jump_to_start.patch_backward(self.get_current_func());
// patch breaks
breaks
.into_iter()
.for_each(|jump| jump.patch_forward(self.get_current_func()));
// patch branch out of loop
if let Some(jump) = branch_inst {
jump.patch_forward(self.get_current_func())
}
}
Stmt::Continue { loc } => {
let Loop {
start_inst_offset,
breaks: _,
} = self
.registers
.loops
.last()
.ok_or(ErrorCode::ContinueOutsideLoop(loc.clone()))?;
let jump = FutureJump {
condition_reg: None,
inst_offset: *start_inst_offset,
loc: loc.clone(),
};
jump.patch_backward(self.get_current_func())
}
Stmt::Break { loc } => {
self.registers
.loops
.last()
.ok_or(ErrorCode::BreakOutsideLoop(loc.clone()))?;
let jump = FutureJump {
condition_reg: None,
inst_offset: self.get_current_insts().len(),
loc: loc.clone(),
};
self.registers.loops.last_mut().unwrap().breaks.push(jump);
self.get_current_insts().push(VmInst::OpDummy(OpDummy));
}
Stmt::Return { loc, value } => {
if self.registers.prev.is_none() {
return Err(ErrorCode::ReturnOutsideFunction(loc.clone()));
}
let return_reg = if let Some(expr) = value {
let (reg, tmp) = self.compile_expr(expr, false, None)?;
if tmp {
self.registers.free_intermediate(reg);
}
reg
} else {
let (reg, _) = self.compile_constant(&Const::Unit, None)?;
reg
};
self.get_current_insts().push(VmInst::OpRet(OpRet {
return_reg,
loc: loc.clone(),
}))
}
Stmt::For {
loc,
loop_variable,
iterator,
body,
} => {
let iter = self.registers.gen_sym();
// iter = iterator.__iter()
let loop_init_expr = Expr::Infix {
loc: iterator.get_loc(),
op: OpInfix::Assign,
lhs: Box::new(Expr::Id {
loc: iterator.get_loc(),
name: iter.clone(),
}),
rhs: Box::new(Expr::Call {
loc: iterator.get_loc(),
lhs: Box::new(Expr::Infix {
loc: iterator.get_loc(),
op: OpInfix::Member,
lhs: iterator.clone(),
rhs: Box::new(Expr::Id {
loc: iterator.get_loc(),
name: "__iter".to_string(),
}),
}),
parameters: vec![],
}),
};
let loop_init_stmt = Stmt::Expr {
loc: iterator.get_loc(),
expr: loop_init_expr,
};
self.compile_stmt(&loop_init_stmt, true, None)?;
let mut loop_body = vec![];
let loop_sym = self.registers.gen_sym();
// loop body
// loop_sym = iter.__next()
loop_body.push(Stmt::Expr {
loc: loc.clone(),
expr: Expr::Infix {
loc: loc.clone(),
op: OpInfix::Assign,
lhs: Box::new(Expr::Id {
loc: iterator.get_loc(),
name: loop_sym.clone(),
}),
rhs: Box::new(Expr::Call {
loc: loop_variable.get_loc(),
lhs: Box::new(Expr::Infix {
loc: iterator.get_loc(),
op: OpInfix::Member,
lhs: Box::new(Expr::Id {
loc: loop_variable.get_loc(),
name: iter,
}),
rhs: Box::new(Expr::Id {
loc: loop_variable.get_loc(),
name: "__next".to_string(),
}),
}),
parameters: vec![],
}),
},
});
//if loop_sym is Option::None then
// break
//else
// x = loop_sym.value
// Body
//end
let if_cond = Expr::Infix {
loc: loop_variable.get_loc(),
op: OpInfix::Is,
lhs: Box::new(Expr::Id {
loc: loop_variable.get_loc(),
name: loop_sym.clone(),
}),
rhs: Box::new(Expr::Infix {
loc: loop_variable.get_loc(),
op: OpInfix::DoubleColon,
lhs: Box::new(Expr::Id {
loc: loop_variable.get_loc(),
name: "Option".to_string(),
}),
rhs: Box::new(Expr::Id {
loc: loop_variable.get_loc(),
name: "None".to_string(),
}),
}),
};
let mut default = vec![Stmt::Expr {
loc: loop_variable.get_loc(),
expr: Expr::Infix {
loc: loop_variable.get_loc(),
op: OpInfix::Assign,
lhs: loop_variable.clone(),
rhs: Box::new(Expr::Infix {
loc: loop_variable.get_loc(),
op: OpInfix::Member,
lhs: Box::new(Expr::Id {
loc: loop_variable.get_loc(),
name: loop_sym,
}),
rhs: Box::new(Expr::Id {
loc: loop_variable.get_loc(),
name: "value".to_string(),
}),
}),
},
}];
default.extend(body.clone());
loop_body.push(Stmt::Expr {
loc: loop_variable.get_loc(),
expr: Expr::If {
loc: loop_variable.get_loc(),
conditional: vec![(if_cond, vec![Stmt::Break { loc: loc.clone() }])],
default: Some(default),
},
});
let stmt = Stmt::Loop {
loc: loc.clone(),
condition: None,
body: loop_body,
};
self.compile_stmt(&stmt, discard, target)?;
}
Stmt::Def {
loc,
variable,
parameters,
body,
} => {
let expr = Expr::Infix {
loc: loc.clone(),
op: OpInfix::Assign,
lhs: variable.clone(),
rhs: Box::new(Expr::Fn {
loc: loc.clone(),
parameters: parameters.clone(),
body: Box::new(Expr::Block {
loc: loc.clone(),
body: body.clone(),
}),
}),
};
self.compile_stmt(
&Stmt::Expr {
loc: loc.clone(),
expr,
},
discard,
target,
)?;
}
Stmt::Error => unreachable!(),
}
Ok(return_value)
}
fn compile_expr(
&mut self,
expr: &Expr,
discard: bool,
target: Option<usize>,
) -> Result<(usize, bool), ErrorCode> {
match expr {
Expr::Prefix { loc, op, rhs } => {
let (rhs_id, rhs_tmp) = self.compile_expr(rhs, false, target)?;
if rhs_tmp {
self.registers.free_intermediate(rhs_id)
};
Ok(self.compile_prefix(op, rhs_id, loc.clone(), target))
}
Expr::Infix {
loc,
op: OpInfix::Comma,
lhs,
rhs,
} => {
let mut items = vec![rhs.as_ref()];
let mut left = lhs.as_ref();
while let Expr::Infix {
loc: _,
op: OpInfix::Comma,
lhs,
rhs,
} = left
{
items.push(rhs);
left = lhs;
}
items.push(left);
let rd = target.unwrap_or_else(|| self.registers.declare_intermediate());
self.get_current_func()
.insts
.push(VmInst::OpMakeTuple(OpMakeTuple {
rd,
size: items.len(),
}));
for (idx, item) in items.into_iter().rev().enumerate() {
let (rs, tmp) = self.compile_expr(item, false, None)?;
if tmp {
self.registers.free_intermediate(rs);
}
self.get_current_func()
.insts
.push(VmInst::OpSetTuple(OpSetTuple {
loc: loc.clone(),
rs,
rd,
idx,
}))
}
Ok((rd, target.is_none()))
}
Expr::Infix {
loc,
op: OpInfix::Range,
lhs,
rhs,
} => {
// Range(lhs, rhs)
let expr = Expr::Call {
loc: loc.clone(),
lhs: Box::new(Expr::Id {
loc: loc.clone(),
name: "Range".to_string(),
}),
parameters: vec![lhs.as_ref().clone(), rhs.as_ref().clone()],
};
self.compile_expr(&expr, false, target)
}
Expr::OpenRange { loc, lhs } => {
// Range(lhs, rhs)
let rhs = Expr::Const {
loc: loc.clone(),
value: Const::Int(i64::MAX),
};
let expr = Expr::Call {
loc: loc.clone(),
lhs: Box::new(Expr::Id {
loc: loc.clone(),
name: "Range".to_string(),
}),
parameters: vec![lhs.as_ref().clone(), rhs],
};
self.compile_expr(&expr, false, target)
}
Expr::Infix {
loc,
op: OpInfix::Member | OpInfix::DoubleColon,
lhs,
rhs,
} => {
let (lhs, tmp) = self.compile_expr(lhs, false, None)?;
if tmp {
self.registers.free_intermediate(lhs);
}
let rd = target.unwrap_or_else(|| self.registers.declare_intermediate());
let op = match rhs.as_ref() {
Expr::Id { loc: _, name } => VmInst::OpGetTable(OpGetTable {
loc: loc.clone(),
rs: lhs,
rd,
attr: self.gc.get_or_insert_table_key(name),
}),
Expr::Const {
loc: _,
value: Const::Int(i),
} => VmInst::OpGetTuple(OpGetTuple {
loc: loc.clone(),
rs: lhs,
rd,
idx: *i as usize,
}),
expr => {
return Err(ErrorCode::InvalidMember(expr.get_loc()));
}
};
self.get_current_insts().push(op);
Ok((rd, target.is_none()))
}
Expr::Infix {
loc,
op: OpInfix::LArrow,
lhs,
rhs,
} => {
if matches!(
lhs.as_ref(),
Expr::Const {
value: Const::Table(_),
..
}
) {
let (lhs_id, lhs_tmp) = self.compile_expr(lhs, false, target)?;
let (rhs_id, rhs_tmp) = self.compile_expr(rhs, false, None)?;
self.get_current_insts().push(VmInst::OpSetMeta(OpSetMeta {
rs: rhs_id,
rd: lhs_id,
loc: loc.clone(),
}));
if rhs_tmp {
self.registers.free_intermediate(rhs_id);
}
Ok((lhs_id, target.is_none() && lhs_tmp))
} else {
Err(ErrorCode::MetaNotAllowed(loc.clone()))
}
}
// prevent use assignment as expression
Expr::Infix {
loc,
op: OpInfix::Assign,
lhs: _,
rhs: _,
} => Err(ErrorCode::InvalidAssignment(loc.clone())),
// short circuit and
Expr::Infix {
loc,
op: OpInfix::And,
lhs,
rhs,
} => {
let rd = target.unwrap_or_else(|| self.registers.declare_intermediate());
self.compile_expr(lhs, false, Some(rd))?;
let br_true_to_end = FutureJump {
condition_reg: Some((rd, true)),
inst_offset: self.get_current_insts().len(),
loc: loc.clone(),
};
self.compile_expr(rhs, false, Some(rd))?;
br_true_to_end.patch_forward(self.get_current_func());
if target.is_none() {
self.registers.free_intermediate(rd);
}
Ok((rd, target.is_none()))
}
// short circuit or
Expr::Infix {
loc,
op: OpInfix::Or,
lhs,
rhs,
} => {
let rd = target.unwrap_or_else(|| self.registers.declare_intermediate());
self.compile_expr(lhs, false, Some(rd))?;
let br_true_to_end = FutureJump {
condition_reg: Some((rd, false)),
inst_offset: self.get_current_insts().len(),
loc: loc.clone(),
};
self.compile_expr(rhs, false, Some(rd))?;
br_true_to_end.patch_forward(self.get_current_func());
if target.is_none() {
self.registers.free_intermediate(rd);
}
Ok((rd, target.is_none()))
}
Expr::Infix { loc, op, lhs, rhs } => {
let (lhs_id, lhs_tmp) = self.compile_expr(lhs, false, None)?;
let (rhs_id, rhs_tmp) = self.compile_expr(rhs, false, None)?;
let ret = self.compile_infix(op, lhs_id, rhs_id, loc.clone(), target);
if lhs_tmp {
self.registers.free_intermediate(lhs_id);
};
if rhs_tmp {
self.registers.free_intermediate(rhs_id);
};
Ok(ret)
}
Expr::Id { loc, name } => match self.registers.lookup_variable(name) {
Some((id, depth, _)) => {
assert!(depth == 0);
Ok(if let Some(target) = target {
self.get_current_func()
.insts
.push(VmInst::OpMove(OpMove { rs: id, rd: target }));
(target, false)
} else {
(id, false)
})
}
None => Err(ErrorCode::NameNotDefined(loc.clone(), name.clone())),
},
Expr::Parentheses { loc: _, content } => self.compile_expr(content, discard, target),
Expr::Const { value, .. } => Ok(self.compile_constant(value, target))?,
Expr::Error => unreachable!(),
Expr::Block { body, .. } => {
self.enter_block();
let mut ret = None;
for (i, stmt) in body.iter().enumerate() {
let reg = self
.compile_stmt(stmt, i != body.len() - 1, target)
.map_err(|err| {
self.leave_block();
err
})?;
ret = reg;
}
self.leave_block();
match (ret, discard) {
(_, true) => Ok((usize::MAX, false)),
(Some((ret, tmp)), false) if target.is_some() => {
if tmp {
self.registers.free_intermediate(ret);
}
let target = target.unwrap();
self.get_current_insts().push(VmInst::OpMove(OpMove {
rs: ret,
rd: target,
}));
Ok((target, false))
}
(Some(ret), false) => Ok(ret),
(None, false) => {
let rd = self.compile_constant(&Const::Unit, target)?;
Ok(rd)
}
}
}
Expr::If {
loc,
conditional,
default,
} => {
assert!(!conditional.is_empty());
let mut branch_op: Option<FutureJump> = None;
let mut jump_to_ends = vec![];
let ret = if discard {
None
} else {
Some(target.unwrap_or_else(|| self.registers.declare_intermediate()))
};
for (condition, body) in conditional {
// patch branch
if let Some(jump) = branch_op {
jump.patch_forward(self.get_current_func())
}
// compile condition
let (condition_reg, tmp) = self.compile_expr(condition, false, None)?;
if tmp {
self.registers.free_intermediate(condition_reg);
}
branch_op = Some(FutureJump {
condition_reg: Some((condition_reg, true)),
inst_offset: self.get_current_insts().len(),
loc: condition.get_loc(),
});
self.get_current_insts().push(VmInst::OpDummy(OpDummy));
// compile body
self.enter_block();
// return unit for empty body
if body.is_empty() && !discard {
// load a unit value
self.compile_constant(&Const::Unit, ret)?;
}
for (i, stmt) in body.iter().enumerate() {
if !discard && i == body.len() - 1 {
let ret_this = self.compile_stmt(stmt, false, ret)?;
// move return value to return reg
if let Some((reg, tmp)) = ret_this {
if tmp {
self.registers.free_intermediate(reg)
};
} else {
// load a unit value
self.compile_constant(&Const::Unit, ret)?;
}
} else {
self.compile_stmt(stmt, true, None)?;
}
}
self.leave_block();
jump_to_ends.push(FutureJump {
condition_reg: None,
inst_offset: self.get_current_insts().len(),
loc: loc.clone(),
});
self.get_current_insts().push(VmInst::OpDummy(OpDummy));
}
// patch branch
if let Some(jump) = branch_op {
jump.patch_forward(self.get_current_func())
}
// compile default else body
if let Some(body) = default {
self.enter_block();
if body.is_empty() && !discard {
// load a unit value
self.compile_constant(&Const::Unit, ret)?;
}
for (i, stmt) in body.iter().enumerate() {
if !discard && i == body.len() - 1 {
let ret_this = self.compile_stmt(stmt, false, ret)?;
// move return value to return reg
if let Some((reg, tmp)) = ret_this {
if tmp {
self.registers.free_intermediate(reg)
};
} else {
// load a unit value
self.compile_constant(&Const::Unit, ret)?;
}
} else {
self.compile_stmt(stmt, true, None)?;
}
}
self.leave_block();
}
// patch all jumps
jump_to_ends
.into_iter()
.for_each(|jump| jump.patch_forward(self.get_current_func()));
Ok(ret
.map(|reg| (reg, target.is_none()))
.unwrap_or((usize::MAX, false)))
}
Expr::Call {
loc,
lhs,
parameters,
} => {
let is_member_call = if let Expr::Infix {
op: OpInfix::Member,
rhs,
..
} = lhs.as_ref()
{
matches!(rhs.as_ref(), Expr::Id { .. })
} else {
false
};
let (lhs_id, frame_start) = if is_member_call {
if let Expr::Infix {
op: OpInfix::Member,
loc,
lhs,
rhs,
} = lhs.as_ref()
{
// add lhs as first parameter
let lhs_id = self.registers.declare_intermediate();
let frame_start = self.registers.prepare_for_call(parameters.len() + 1);
self.compile_expr(lhs, false, Some(frame_start))?;
let op = match rhs.as_ref() {
Expr::Id { loc: _, name } => VmInst::OpGetTable(OpGetTable {
loc: loc.clone(),
rs: frame_start,
rd: lhs_id,
attr: self.gc.get_or_insert_table_key(name),
}),
_ => unreachable!(),
};
self.get_current_insts().push(op);
for (i, para) in parameters.iter().enumerate() {
self.compile_expr(para, false, Some(frame_start + i + 1))?;
}
self.registers.free_intermediate(lhs_id);
(lhs_id, frame_start)
} else {
unreachable!()
}
} else {
let (lhs_id, lhs_tmp) = self.compile_expr(lhs, false, None)?;
let frame_start = self.registers.prepare_for_call(parameters.len());
for (i, para) in parameters.iter().enumerate() {
self.compile_expr(para, false, Some(frame_start + i))?;
}
if lhs_tmp {
self.registers.free_intermediate(lhs_id);
}
(lhs_id, frame_start)
};
let rd = if discard {
None
} else {
Some(target.unwrap_or_else(|| self.registers.declare_intermediate()))
};
self.get_current_insts().push(VmInst::OpCall(OpCall {
reg_id: lhs_id,
parameters: parameters.len() + if is_member_call { 1 } else { 0 },
start: frame_start,
write_back: rd,
loc: loc.clone(),
}));
(frame_start..frame_start + parameters.len() + if is_member_call { 1 } else { 0 })
.into_iter()
.for_each(|reg| self.registers.free_intermediate(reg));
Ok((rd.unwrap_or(usize::MAX), target.is_none()))
}
Expr::Index { loc, lhs, rhs } => {
let rd = target.unwrap_or_else(|| self.registers.declare_intermediate());
self.compile_expr(lhs, false, Some(rd))?;
let (rhs_id, rhs_tmp) = self.compile_expr(rhs, false, None)?;
self.get_current_insts().push(VmInst::OpIndex(OpIndex {
loc: loc.clone(),
lhs: rd,
rhs: rhs_id,
rd,
}));
if rhs_tmp {
self.registers.free_intermediate(rhs_id);
}
Ok((rd, target.is_none()))
}
Expr::Fn {
loc,
parameters,
body,
} => {
let (func_id, parameters, capture, reg_size) =
self.compile_closure(parameters, either::Left(body), loc.clone())?;
let rd = target.unwrap_or_else(|| self.registers.declare_intermediate());
self.get_current_func()
.insts
.push(VmInst::OpMakeClosure(OpMakeClosure {
loc: loc.clone(),
func_id,
parameters,
rd,
capture,
reg_size,
}));
Ok((rd, target.is_none()))
}
Expr::_Module { loc: _, path: _ } => todo!(),
}
}
fn compile_assignment(&mut self, lhs: &Expr, rhs: &Expr) -> Result<(), ErrorCode> {
match lhs {
Expr::Id { loc: id_loc, name } => {
// declare variable
let id = if let Some((id, depth, _)) = self.registers.lookup_variable(name) {
assert!(depth == 0);
id
} else {
self.scopes.last_mut().unwrap().insert(name.clone());
self.registers.declare_variable(name, Some(id_loc.clone()))
};
let (rhs, tmp) = self.compile_expr(rhs, false, Some(id))?;
if tmp {
self.registers.free_intermediate(rhs);
}
Ok(())
}
Expr::Index {
lhs: rd,
rhs: idx,
loc,
} => {
let (rd_id, rd_tmp) = self.compile_expr(rd, false, None)?;
let (idx_id, idx_tmp) = self.compile_expr(idx, false, None)?;
let (rs_id, rs_tmp) = self.compile_expr(rhs, false, None)?;
if rd_tmp {
self.registers.free_intermediate(rd_id);
}
if idx_tmp {
self.registers.free_intermediate(idx_id);
}
if rs_tmp {
self.registers.free_intermediate(rs_id);
}
self.get_current_insts()
.push(VmInst::OpSetIndex(OpSetIndex {
loc: loc.clone(),
rs: rs_id,
idx: idx_id,
rd: rd_id,
}));
Ok(())
}
Expr::Infix {
op: OpInfix::Member,
lhs: rd,
rhs: idx,
loc,
} => {
let (rd_id, rd_tmp) = self.compile_expr(rd, false, None)?;
let (rs_id, rs_tmp) = self.compile_expr(rhs, false, None)?;
if rd_tmp {
self.registers.free_intermediate(rd_id);
}
if rs_tmp {
self.registers.free_intermediate(rs_id);
}
match idx.as_ref() {
Expr::Id { name, .. } => {
let name = self.gc.get_or_insert_table_key(name);
self.get_current_insts()
.push(VmInst::OpSetTable(OpSetTable {
loc: loc.clone(),
rs: rs_id,
rd: rd_id,
attr: name,
}));
}
Expr::Const {
value: Const::Int(i),
..
} => {
assert!(*i >= 0);
self.get_current_insts()
.push(VmInst::OpSetTuple(OpSetTuple {
loc: loc.clone(),
rs: rs_id,
rd: rd_id,
idx: *i as usize,
}));
}
expr => return Err(ErrorCode::CannotAssign(expr.get_loc())),
}
Ok(())
}
_ => Err(ErrorCode::CannotAssign(lhs.get_loc())),
}
}
fn compile_constant(
&mut self,
constant: &Const,
target: Option<usize>,
) -> Result<(usize, bool), ErrorCode> {
let constant = match constant {
Const::Unit => self
.registers
.get_or_alloc_constant(ConstantValue::Unit)
.unwrap(),
Const::Int(i) => self
.registers
.get_or_alloc_constant(ConstantValue::Int(*i))
.unwrap(),
Const::Float(f) => self
.registers
.get_or_alloc_constant(ConstantValue::Float((*f).to_bits()))
.unwrap(),
Const::Str(s) => self
.registers
.get_or_alloc_constant(ConstantValue::Str(s.clone()))
.unwrap(),
Const::Bool(b) => self
.registers
.get_or_alloc_constant(ConstantValue::Bool(*b))
.unwrap(),
Const::List(list) => {
let mut items = vec![];
let rd = target.unwrap_or_else(|| self.registers.declare_intermediate());
for expr in list {
let item = self.compile_expr(expr, false, None)?;
items.push(item);
}
self.get_current_insts()
.push(VmInst::OpMakeList(OpMakeList {
rd,
items: items.iter().map(|(id, _)| *id).collect(),
}));
items.into_iter().for_each(|(id, tmp)| {
if tmp {
self.registers.free_intermediate(id);
}
});
return Ok((rd, target.is_none()));
}
Const::Table(pairs) => {
let rd = target.unwrap_or_else(|| self.registers.declare_intermediate());
self.get_current_func()
.insts
.push(VmInst::OpMakeTable(OpMakeTable { rd }));
for (attr, expr, loc) in pairs.iter() {
let (value, tmp) = self.compile_expr(expr, false, None)?;
if tmp {
self.registers.free_intermediate(value);
}
let attr = self.gc.get_or_insert_table_key(attr);
self.get_current_func()
.insts
.push(VmInst::OpSetTable(OpSetTable {
loc: loc.clone(),
rs: value,
rd,
attr,
}));
}
return Ok((rd, target.is_none()));
}
};
if let Some(target) = target {
self.get_current_insts().push(VmInst::OpMove(OpMove {
rs: constant,
rd: target,
}));
Ok((target, false))
} else {
Ok((constant, false))
}
}
fn compile_infix(
&mut self,
op: &OpInfix,
lhs: usize,
rhs: usize,
loc: Loc,
target: Option<usize>,
) -> (usize, bool) {
match op {
OpInfix::Is => {
let rd = target.unwrap_or_else(|| self.registers.declare_intermediate());
self.get_current_func()
.insts
.push(VmInst::OpIs(OpIs { loc, lhs, rhs, rd }));
(rd, target.is_none())
}
OpInfix::Or | OpInfix::And => unreachable!(),
OpInfix::Eq => {
let rd = target.unwrap_or_else(|| self.registers.declare_intermediate());
self.get_current_func()
.insts
.push(VmInst::OpEq(OpEq { loc, lhs, rhs, rd }));
(rd, target.is_none())
}
OpInfix::Ne => {
let rd = target.unwrap_or_else(|| self.registers.declare_intermediate());
self.get_current_func()
.insts
.push(VmInst::OpNe(OpNe { loc, lhs, rhs, rd }));
(rd, target.is_none())
}
OpInfix::Ge => {
let rd = target.unwrap_or_else(|| self.registers.declare_intermediate());
self.get_current_func()
.insts
.push(VmInst::OpGe(OpGe { loc, lhs, rhs, rd }));
(rd, target.is_none())
}
OpInfix::Gt => {
let rd = target.unwrap_or_else(|| self.registers.declare_intermediate());
self.get_current_func()
.insts
.push(VmInst::OpGt(OpGt { loc, lhs, rhs, rd }));
(rd, target.is_none())
}
OpInfix::Lt => {
let rd = target.unwrap_or_else(|| self.registers.declare_intermediate());
self.get_current_func()
.insts
.push(VmInst::OpLt(OpLt { loc, lhs, rhs, rd }));
(rd, target.is_none())
}
OpInfix::Le => {
let rd = target.unwrap_or_else(|| self.registers.declare_intermediate());
self.get_current_func()
.insts
.push(VmInst::OpLe(OpLe { loc, lhs, rhs, rd }));
(rd, target.is_none())
}
OpInfix::Plus => {
let rd = target.unwrap_or_else(|| self.registers.declare_intermediate());
self.get_current_func()
.insts
.push(VmInst::OpAdd(OpAdd { loc, lhs, rhs, rd }));
(rd, target.is_none())
}
OpInfix::Minus => {
let rd = target.unwrap_or_else(|| self.registers.declare_intermediate());
self.get_current_func()
.insts
.push(VmInst::OpSub(OpSub { loc, lhs, rhs, rd }));
(rd, target.is_none())
}
OpInfix::Mul => {
let rd = target.unwrap_or_else(|| self.registers.declare_intermediate());
self.get_current_func()
.insts
.push(VmInst::OpMul(OpMul { loc, lhs, rhs, rd }));
(rd, target.is_none())
}
OpInfix::Div => {
let rd = target.unwrap_or_else(|| self.registers.declare_intermediate());
self.get_current_func()
.insts
.push(VmInst::OpDiv(OpDiv { loc, lhs, rhs, rd }));
(rd, target.is_none())
}
OpInfix::DivFloor => {
let rd = target.unwrap_or_else(|| self.registers.declare_intermediate());
self.get_current_func()
.insts
.push(VmInst::OpIDiv(OpIDiv { loc, lhs, rhs, rd }));
(rd, target.is_none())
}
OpInfix::Rem => {
let rd = target.unwrap_or_else(|| self.registers.declare_intermediate());
self.get_current_func()
.insts
.push(VmInst::OpRem(OpRem { loc, lhs, rhs, rd }));
(rd, target.is_none())
}
OpInfix::Exp => {
let rd = target.unwrap_or_else(|| self.registers.declare_intermediate());
self.get_current_func()
.insts
.push(VmInst::OpPow(OpPow { loc, lhs, rhs, rd }));
(rd, target.is_none())
}
OpInfix::Assign
| OpInfix::Range
| OpInfix::Comma
| OpInfix::Member
| OpInfix::DoubleColon
| OpInfix::LArrow => {
unreachable!()
}
}
}
fn compile_prefix(
&mut self,
op: &OpPrefix,
rhs: usize,
loc: Loc,
target: Option<usize>,
) -> (usize, bool) {
match op {
OpPrefix::Not => {
let rd = target.unwrap_or_else(|| self.registers.declare_intermediate());
self.get_current_func()
.insts
.push(VmInst::OpNot(OpNot { loc, lhs: rhs, rd }));
(rd, target.is_none())
}
OpPrefix::Neg => {
let rd = target.unwrap_or_else(|| self.registers.declare_intermediate());
self.get_current_func()
.insts
.push(VmInst::OpNeg(OpNeg { loc, lhs: rhs, rd }));
(rd, target.is_none())
}
}
}
/// Return (func_id, parameters len, captured_regs, reg_size)
fn compile_closure(
&mut self,
parameters: &[(String, Loc)],
body: Either<&Expr, &[Stmt]>,
loc: Loc,
) -> std::result::Result<(usize, usize, Vec<Capture>, usize), ErrorCode> {
let func_id = self.byte_code.len();
self.byte_code.push(Func {
id: func_id,
parameters: parameters.len(),
insts: vec![],
});
self.registers.enter_function(func_id);
for (para, loc) in parameters.iter() {
self.registers.declare_variable(para, Some(loc.clone()));
}
let func_id = self.registers.func_id;
// scan all constant values
let mut const_scanner = ConstScanner {
register_table: &mut self.registers,
gc: &mut self.gc,
insts: &mut self.byte_code[func_id].insts,
};
match body {
Either::Left(expr) => const_scanner.scan_expr(expr),
Either::Right(stmts) => stmts.iter().for_each(|stmt| const_scanner.scan_stmt(stmt)),
}
// scan all captured variable (include nested closure)
let mut capture_scanner = CaptureScanner {
register_table: &mut self.registers,
gc: &mut self.gc,
insts: &mut self.byte_code[func_id].insts,
overridden: AHashMap::new(),
};
match body {
Either::Left(expr) => capture_scanner.scan_expr(expr),
Either::Right(stmts) => stmts
.iter()
.for_each(|stmt| capture_scanner.scan_stmt(stmt)),
}
let result = match body {
Either::Left(Expr::Infix {
op: OpInfix::Assign,
lhs,
rhs,
..
}) => {
self.compile_assignment(lhs, rhs).map_err(|err| {
self.registers.leave_function();
err
})?;
(0, false)
}
Either::Left(body) => self.compile_expr(body, false, None).map_err(|err| {
self.registers.leave_function();
err
})?,
Either::Right(body) => {
let mut ret = None;
if body.is_empty() {
// load a unit value
let (reg, _) = self.compile_constant(&Const::Unit, None)?;
ret = Some((reg, false));
}
for (i, stmt) in body.iter().enumerate() {
if i == body.len() - 1 {
let ret_this = self.compile_stmt(stmt, false, None)?;
// move return value to return reg
if let Some(ret_this) = ret_this {
ret = Some(ret_this);
} else {
// load a unit value
let (reg, _) = self.compile_constant(&Const::Unit, None)?;
ret = Some((reg, false));
}
} else {
self.compile_stmt(stmt, true, None)?;
}
}
ret.unwrap()
}
};
// return expression value
self.get_current_insts().push(VmInst::OpRet(OpRet {
return_reg: result.0,
loc,
}));
let reg_size = self.registers.assigned;
let captured_regs = self.registers.leave_function();
Ok((func_id, parameters.len(), captured_regs, reg_size))
}
fn get_current_func(&mut self) -> &mut Func {
let id = self.registers.func_id;
&mut self.byte_code[id]
}
fn get_current_insts(&mut self) -> &mut Vec<VmInst> {
let id = self.registers.func_id;
&mut self.byte_code[id].insts
}
fn enter_block(&mut self) {
self.scopes.push(AHashSet::new());
}
fn leave_block(&mut self) {
let scope = self.scopes.pop().unwrap();
for name in scope.into_iter() {
self.registers.variables.remove(&name);
}
}
}
#[cfg(test)]
mod tests;