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
use crate::compiler::cursor::{FunctionCursor, FunctionCursorMethods};
use crate::compiler::value::parameters::Parameter::Constant;
use crate::compiler::value::parameters::{Parameter, Variable};
use crate::compiler::value::primitives::Primitive::{Boolean, Integer, MyString};
use crate::compiler::value::values::Value::{FunctionNameValue, PrimitiveValue};
use crate::compiler::value::values::Value::{Tuple, TypedValueInstance};
use crate::compiler::value::values::{FunctionDefinitionObject, TypedValue, Value};
use crate::runtime::bytecode::OpCode;
use crate::runtime::bytecode::OpCode::*;
use crate::store::Store;
use crate::{
boolean_to_value, empty_tuple_value, integer_to_value, string_to_value, value_is_integer,
value_is_string, value_to_boolean, value_to_integer, value_to_string, vector_to_value,
};
use std::cell::RefCell;
use std::collections::HashMap;
use std::ops::Add;
use std::rc::Rc;
use crate::runtime::compiled_script::{Bytecode, Executable};
use crate::runtime::disassembler::disassemble_no_lines;
use crate::runtime::sink::Sink;
use crate::runtime::RuntimeError;
use tracing::{debug, trace};
macro_rules! current_stack_mut {
($self:expr) => {{
&mut $self.frame_stack.last_mut().unwrap().value_stack
}};
}
macro_rules! current_stack {
($self:expr) => {{
&$self.frame_stack.last().unwrap().value_stack
}};
}
#[derive(Debug)]
pub struct Frame {
ip: usize,
bytecodes: Bytecode,
name: String,
value_stack: Vec<Value>,
pub variables: Vec<Value>,
pub constants: Vec<Value>,
}
#[derive(Debug)]
pub struct VirtualMachine {
pub frame_stack: Vec<Frame>,
pub global_variables: HashMap<String, Value>,
pub cursors: HashMap<u8, FunctionCursor>,
}
impl Default for VirtualMachine {
fn default() -> Self {
Self::new()
}
}
impl VirtualMachine {
pub fn new() -> VirtualMachine {
VirtualMachine {
frame_stack: vec![],
global_variables: HashMap::new(),
cursors: HashMap::new(),
}
}
fn pop(&mut self) -> Value {
if let Some(result) = current_stack_mut!(self).pop() {
result
} else {
panic!(
"Stack underflow, ip is {}",
self.frame_stack.last().unwrap().ip
)
}
}
fn peek(&mut self) -> &Value {
if let Some(result) = current_stack!(self).last() {
result
} else {
panic!(
"Stack underflow, IP is {}",
self.frame_stack.last().unwrap().ip
);
}
}
// maybe this should return the value if a value match is found. We'll see
pub fn call(
&mut self,
function_name: &str,
function_store: &mut dyn Store,
arguments: &[Value],
) -> Result<(), RuntimeError> {
match function_store
.get_function_value(function_name, arguments)
.unwrap()
{
None => {
// no values for this function
// debug!(
// "Did not find a value mapping for function {} and value {:?}",
// function_name, arguments
// );
}
Some(value) => {
// debug!(
// "Found direct value mapping for function: {} -> {:?}, using it",
// function_name, value
// );
current_stack_mut!(self).push(value.clone());
return Ok(());
}
}
match function_store.get_function_definition(function_name, arguments)? {
Some(definition) => {
self.setup_call_frame(&definition, arguments)?;
}
None => {
// Final attempt, see if this is a native function and call it
match function_store.get_native_function(function_name)? {
Some(function) => {
// debug!(
// "Found native function for name: {}, using it", function_name
// );
let result = function(arguments);
current_stack_mut!(self).push(result);
}
None => {
// debug!(
// "no definitions matched at all, pushing an empty tuple and hoping for the best"
// );
current_stack_mut!(self).push(empty_tuple_value!());
}
}
}
}
Ok(())
}
fn setup_call_frame(
&mut self,
definition: &FunctionDefinitionObject,
arguments: &[Value],
) -> Result<(), RuntimeError> {
if self.frame_stack.len() == 32 {
return Err(RuntimeError::new_stack_error(
format!("Stack overflow, function is {}", definition.name),
self.frame_stack.last().unwrap().ip,
OpCall,
));
}
let mut variables = vec![];
for (index, argument) in arguments.iter().enumerate() {
match definition.formal_arguments[index] {
Constant(_) => continue,
Parameter::Variable(_) => {
variables.push(argument.clone());
}
}
}
let mut constants = vec![];
for constant in &definition.constants {
constants.push(constant.clone());
}
let new_frame = Frame {
ip: 0,
bytecodes: definition.bytecode.clone(),
name: definition.name.clone(),
variables,
constants,
value_stack: Vec::new(),
};
self.frame_stack.push(new_frame);
Ok(())
}
pub fn reset(&mut self) {
self.frame_stack = vec![];
self.cursors.clear();
}
pub fn run(
&mut self,
script: &Executable,
store: &mut impl Store,
sink: &mut impl Sink,
) -> Result<Value, RuntimeError> {
for (name, definitions) in script.function_definitions.iter() {
for definition in definitions {
match store.set_function_definition(
name,
definition.formal_arguments.as_slice(),
definition.clone(),
) {
Ok(_) => {} // cool, keep going
Err(e) => {
return Err(RuntimeError::new_io_error(format!(
"Error during function definition: {}",
e
)))
}
}
}
}
for type_def in &script.type_definitions {
match store.set_type_definition(&type_def.name, type_def.clone()) {
Ok(_) => {}
Err(e) => {
return Err(RuntimeError::new_io_error(format!(
"Error while storing type: {}",
e
)))
}
}
}
self.setup_call_frame(&script.as_fdo(), &[])?;
self.run_inner(&script.script_variables, store, sink)
}
fn dump_stack(stack: &[Value]) {
trace!("Stack:");
for (pos, value) in stack.iter().rev().enumerate() {
trace!("{}:[{}]", pos, value);
}
}
fn run_inner(
&mut self,
global_variables: &[Variable],
store: &mut dyn Store,
sink: &mut impl Sink,
) -> Result<Value, RuntimeError> {
let mut result = empty_tuple_value!();
if self.frame_stack.is_empty() {
// this horrible, I know
trace!("No code to run, returning");
return Ok(result);
}
macro_rules! read_byte {
() => {{
let result = self
.frame_stack
.last()
.unwrap()
.bytecodes
.get(self.frame_stack.last().unwrap().ip);
self.frame_stack.last_mut().unwrap().ip += 1;
result as usize
}};
}
macro_rules! opcode {
() => {{
OpCode::from_byte(
frame_stack_top!()
.bytecodes
.get(self.frame_stack.last().unwrap().ip),
)
}};
}
macro_rules! frame_stack_top_mut {
() => {{
self.frame_stack.last_mut().unwrap()
}};
}
macro_rules! frame_stack_top {
() => {{
self.frame_stack.last().unwrap()
}};
}
loop {
let bytecode = opcode!();
// debug!(
// "Value stack is {} long, executing {}",
// current_stack!(self).len(),
// bytecode
// );
frame_stack_top_mut!().ip += 1;
match bytecode {
OpPop => {
self.pop();
}
OpConst => {
let index = read_byte!();
let value = frame_stack_top!().constants[index].clone();
// trace!("OpConst pushing {:?}", value);
current_stack_mut!(self).push(value);
}
OpTrue => {
current_stack_mut!(self).push(boolean_to_value!(true));
}
OpFalse => {
current_stack_mut!(self).push(boolean_to_value!(false));
}
OpMktuple => {
let mut arity = read_byte!();
let value;
if arity > 0 {
// The 0 is just a random value to populate the vector so it has `arity` size
// and all indexes are valid, which is necessary because we populate it
// backwards. Some unsafe code here would make things faster, I think.
let mut tuple_contents = vec![integer_to_value!(0); arity];
loop {
arity -= 1;
let value1 = self.pop();
tuple_contents[arity] = value1;
if arity == 0 {
break;
}
}
value = vector_to_value!(tuple_contents);
} else {
value = empty_tuple_value!();
}
current_stack_mut!(self).push(value);
}
OpAdd => {
let right = self.pop();
if value_is_integer!(right) {
// trace!("Right value to add is {:?}", right);
let right = value_to_integer!(right);
let left = self.pop();
// trace!("Left value to add is {:?}", left);
let left = value_to_integer!(left);
current_stack_mut!(self).push(integer_to_value!(left + right));
} else if value_is_string!(right) {
let right = value_to_string!(right);
let left = value_to_string!(self.pop());
current_stack_mut!(self).push(string_to_value!(left.add(&right)))
} else {
return Err(RuntimeError::new_value_error(
format!("Value {} does not support addition", right),
frame_stack_top!().ip,
OpAdd,
));
}
}
OpSubtract => {
let right = value_to_integer!(self.pop());
let left = value_to_integer!(self.pop());
current_stack_mut!(self).push(integer_to_value!(left - right));
}
OpMultiply => {
let right = value_to_integer!(self.pop());
let left = value_to_integer!(self.pop());
current_stack_mut!(self).push(integer_to_value!(left * right));
}
OpDivide => {
let right = value_to_integer!(self.pop());
let left = value_to_integer!(self.pop());
current_stack_mut!(self).push(integer_to_value!(left / right));
}
OpNegate => {
let value = value_to_integer!(self.pop());
current_stack_mut!(self).push(integer_to_value!(-value));
}
OpAnd => {
let right = value_to_boolean!(self.pop());
let left = value_to_boolean!(self.pop());
current_stack_mut!(self).push(boolean_to_value!(left && right));
}
OpOr => {
let right = value_to_boolean!(self.pop());
let left = value_to_boolean!(self.pop());
current_stack_mut!(self).push(boolean_to_value!(left || right));
}
OpNot => {
let value = value_to_boolean!(self.pop());
current_stack_mut!(self).push(boolean_to_value!(!value));
}
OpEquals => {
let right = self.pop();
let left = self.pop();
current_stack_mut!(self).push(boolean_to_value!(left.eq(&right)));
}
OpGt => {
let right = value_to_integer!(self.pop());
let left = value_to_integer!(self.pop());
current_stack_mut!(self).push(boolean_to_value!(left > right));
}
OpLt => {
let right = value_to_integer!(self.pop());
let left = value_to_integer!(self.pop());
current_stack_mut!(self).push(boolean_to_value!(left < right));
}
OpReturn => {
if let Some(mut frame) = self.frame_stack.pop() {
if self.frame_stack.is_empty() {
if let Some(return_value) = frame.value_stack.pop() {
result = return_value;
}
break;
}
if let Some(return_value) = frame.value_stack.pop() {
assert_eq!(
0,
frame.value_stack.len(),
"After return from function {}, stack had length {}",
frame.name,
frame.value_stack.len()
);
current_stack_mut!(self).push(return_value);
}
/*
Else should there be a default return value? Probably not, this is a concern with
language semantics, not a runtime issue.
It does assume however that the caller expects a return value.
*/
} else {
panic!("OpReturn could not find current executing frame")
}
}
OpSetGlobal => {
let name_index = read_byte!();
if let Some(var) = global_variables.get(name_index) {
let value = self.peek().clone();
self.global_variables.insert(var.name.to_string(), value);
} else {
return Err(RuntimeError::new_compiler_error(
format!("Global Variable {} not found", name_index),
frame_stack_top!().ip,
OpSetGlobal,
));
}
}
OpGetGlobal => {
let name_index = read_byte!();
let name = &global_variables.get(name_index).unwrap().name;
if let Some(value) = self.global_variables.get(name) {
current_stack_mut!(self).push(value.clone());
} else {
return Err(RuntimeError::new_compiler_error(
format!("Variable {} not found", name),
frame_stack_top!().ip,
OpGetGlobal,
));
}
}
OpSetLocal => {
let index = read_byte!();
if index > frame_stack_top!().variables.len() + 1 {
// This check is probably wrong, but I want to know when it's invalidated.
// It checks that variables are first referenced in strict order and we never skip one
// This may change in the future if variables can be declared before being assigned
// Then they will get an index before they are actually set, so calls to OpSetVar
// will be mixed up
return Err(RuntimeError::new_compiler_error(
format!(
"index was {}, variables length was {}",
index,
frame_stack_top!().variables.len()
),
frame_stack_top!().ip,
OpSetLocal,
));
}
while index >= frame_stack_top!().variables.len() {
// If the index for the variable is missing, create it.
frame_stack_top_mut!().variables.push(integer_to_value!(0));
}
frame_stack_top_mut!().variables[index] = self.peek().clone();
// debug!(
// "Set local variable at index {} to {}",
// index,
// frame_stack_top!().variables[index]
// );
}
OpGetLocal => {
let index = read_byte!();
let val = frame_stack_top!().variables[index].clone();
current_stack_mut!(self).push(val);
// trace!("GetLocal pushed value {} for index {}", self.peek(), index);
}
OpSetFunt => {
let index = read_byte!();
let codomain_value = self.pop();
match self.pop() {
Tuple(tuple) => {
// trace!(
// "SetFunT popped values: codom-> {:?}, tuple-> {:?}",
// codomain_value,
// tuple
// );
let FunctionNameValue(function_name) =
&frame_stack_top_mut!().constants[index]
else {
return Err(RuntimeError::new_value_error(
"Expected FunctionNameValue".to_string(),
frame_stack_top!().ip,
OpSetFunt,
));
};
store.set_function_value(
function_name,
tuple.as_slice(),
codomain_value.clone(),
)?;
// Yeah, this is not good, codomain and domain values should be flipped
current_stack_mut!(self).push(codomain_value);
}
o => {
return Err(RuntimeError::new_value_error(
format!("Expected tuple at top of stack, got {:?} instead", o),
frame_stack_top!().ip,
OpSetFunt,
));
}
}
}
OpCall => {
let mut arg_count = read_byte!();
let FunctionNameValue(function_name) = self.pop() else {
return Err(RuntimeError::new_value_error(
"Expected FunctionNameValue".to_string(),
frame_stack_top!().ip,
OpCall,
));
};
// TODO This is the same code as OpMkTuple, this should be fixed
let mut domain_value = vec![integer_to_value!(0); arg_count];
if arg_count > 0 {
loop {
arg_count -= 1;
let value1 = self.pop();
domain_value[arg_count] = value1;
if arg_count == 0 {
break;
}
}
}
self.call(function_name.as_str(), store, &domain_value)?;
}
OpJump => {
let jump_distance = read_byte!();
frame_stack_top_mut!().ip += jump_distance;
}
OpJumpIfFalse => {
let jump_distance = read_byte!();
let ip = frame_stack_top!().ip;
let value = self.peek();
if !as_boolean(value, ip, OpJumpIfFalse)? {
// trace!("OpJumpIfFalse jumping by {} at ip {}", jump_distance, ip);
frame_stack_top_mut!().ip += jump_distance;
// } else {
// trace!("OpJumpIfFalse not jumping at ip {}", ip);
}
}
OpLoop => {
let jump_distance = read_byte!();
frame_stack_top_mut!().ip -= jump_distance;
}
OpPull => {
let cursor_id = read_byte!();
let cur = self.cursors.get_mut(&(cursor_id as u8)).unwrap();
match cur.next() {
None => {
current_stack_mut!(self).push(empty_tuple_value!());
}
Some(mut row) => {
row.reverse();
for value in row {
// trace!("Pushing value {} from cursor {}", value, cursor_id);
current_stack_mut!(self).push(value);
}
}
}
}
OpProduce => {
let count = read_byte!();
let mut result = Vec::with_capacity(count);
for _ in 0..count {
result.push(self.pop());
}
result.reverse();
sink.accept(&result);
}
OpOpenCursor => {
let cursor_id = read_byte!();
let FunctionNameValue(cursor_name) = self.pop() else {
return Err(RuntimeError::new_value_error(
"Expected FunctionNameValue".to_string(),
frame_stack_top!().ip,
OpOpenCursor,
));
};
self.cursors
.insert(cursor_id as u8, store.function_cursor(&cursor_name));
}
OpCloseCursor => {
// TODO this needs to be implemented, we leak cursors otherwise
let cursor_id = read_byte!();
debug!("Here I would close cursor {}", cursor_id);
}
OpTupleGet => {
let _ = read_byte!();
let stack_top = self.pop();
match stack_top {
Tuple(mut values) => {
if values.is_empty() {
return Err(RuntimeError::new_value_error(
"Expected non empty tuple, got empty one instead".to_string(),
frame_stack_top!().ip,
OpTupleGet,
));
}
let first = values.remove(0);
if values.len() == 1 {
current_stack_mut!(self).push(values.remove(0));
} else {
current_stack_mut!(self).push(Tuple(values));
}
current_stack_mut!(self).push(first);
}
_ => {
current_stack_mut!(self).push(stack_top); // push it back in unchanged
}
}
}
OpNewInstance => {
let constant = read_byte!();
let name = value_to_string!(&frame_stack_top!().constants[constant]);
match store.type_definition_by_name(name)? {
Some(definition) => {
let mut default_field_values = HashMap::new();
for (field_name, field_type) in definition.fields {
match field_type.as_str() {
"int" => {
default_field_values.insert(field_name, Integer(0));
}
"string" => {
default_field_values
.insert(field_name, MyString("".to_string()));
}
"bool" => {
default_field_values.insert(field_name, Boolean(false));
}
_ => {
panic!("Type {} is not a supported field type", field_type)
}
}
}
let value = TypedValueInstance(Rc::new(RefCell::new(TypedValue {
name: definition.name,
fields: default_field_values,
})));
current_stack_mut!(self).push(value);
}
None => {
return Err(RuntimeError::new_schema_error(
format!("There is no type named '{}' defined. You need to define it first with a 'type' statement.", name)
));
}
}
}
OpSetField => {
let stack_top = current_stack_mut!(self).pop();
let field_name = read_byte!();
let field_name =
value_to_string!(&frame_stack_top!().constants[field_name]).to_string();
if let Some(PrimitiveValue(primitive)) = stack_top {
if let Some(TypedValueInstance(ref mut value)) =
current_stack_mut!(self).last_mut()
{
value
.borrow_mut()
.fields
.insert(field_name, primitive.clone());
}
} else {
panic!()
}
}
OpGetField => {
let field_name_const = read_byte!();
let field_name =
value_to_string!(&frame_stack_top!().constants[field_name_const]).clone();
let object = current_stack_mut!(self).pop();
let value = if let Some(TypedValueInstance(value)) = object {
match value.borrow().fields.get(&field_name) {
Some(value) => value.clone(),
None => {
panic!(
"no field with name {} in type {}",
field_name,
value.borrow().name
)
}
}
} else {
panic!()
};
current_stack_mut!(self).push(PrimitiveValue(value));
}
e => {
panic!(
"{:?} opcode not implemented, ip={}",
e,
frame_stack_top!().ip
);
}
}
// VirtualMachine::dump_stack(¤t_stack!(self));
}
// trace!("Execution completed:");
Ok(result)
}
}
fn as_boolean(value: &Value, ip: usize, op_code: OpCode) -> Result<bool, RuntimeError> {
let result = match value {
PrimitiveValue(Boolean(bool)) => !*bool,
PrimitiveValue(_) => false,
FunctionNameValue(_) => {
return Err(RuntimeError::new_value_error(
"Cannot assign boolean to function name value".to_string(),
ip,
op_code,
))
}
Tuple(tuple) => tuple.is_empty(),
TypedValueInstance(_) => false,
};
Ok(!result)
}
#[cfg(test)]
mod tests {
use crate::compiler::value::parameters::{Parameter, Variable};
use crate::compiler::value::primitives::Primitive::{Boolean, Integer, MyString};
use crate::compiler::value::values::Value::{FunctionNameValue, PrimitiveValue};
use crate::compiler::value::values::{FunctionDefinitionObject, TypeDefinition};
use crate::runtime::bytecode::OpCode::{
OpAdd, OpCall, OpCloseCursor, OpConst, OpEquals, OpGetField, OpGetGlobal, OpGetLocal, OpGt,
OpJump, OpJumpIfFalse, OpLoop, OpNewInstance, OpNone, OpNot, OpOpenCursor, OpPop,
OpProduce, OpPull, OpReturn, OpSetField, OpSetGlobal, OpSetLocal,
};
use crate::runtime::compiled_script::Executable;
use crate::runtime::sink::AccumulatingSink;
use crate::runtime::vm::VirtualMachine;
use crate::runtime::RuntimeError;
use crate::store::memory::MemoryStore;
use crate::store::Store;
use crate::{integer_to_value, string_to_value};
#[test]
fn test_addition() -> Result<(), RuntimeError> {
let mut script = Executable::default();
// define two constants
script.script_constants = vec![
PrimitiveValue(Integer(37)), // constant 0
PrimitiveValue(Integer(5)), // constant 1
];
// and add them
#[rustfmt::skip]
{
script.script_bytecode.bytes = vec![
OpConst as u8, 0, // push constant 0
OpConst as u8, 1, // push constant 1
OpAdd as u8, // add them
OpReturn as u8, // exit vm
];
}
let mut vm = VirtualMachine::new();
let result = vm.run(
&script,
&mut MemoryStore::new(),
&mut AccumulatingSink::default(),
)?;
assert_eq!(result, PrimitiveValue(Integer(42)));
Ok(())
}
#[test]
fn test_greater_than() -> Result<(), RuntimeError> {
let mut script = Executable::default();
// define two constants
script.script_constants = vec![
PrimitiveValue(Integer(-12)), // constant 0
PrimitiveValue(Integer(55)), // constant 1
];
// and compare them
#[rustfmt::skip]
{
script.script_bytecode.bytes = vec![
OpConst as u8, 0, // push constant 0
OpConst as u8, 1, // push constant 1
OpGt as u8, // compare them
OpReturn as u8, // exit vm
];
}
let mut vm = VirtualMachine::new();
let result = vm.run(
&script,
&mut MemoryStore::new(),
&mut AccumulatingSink::default(),
)?;
assert_eq!(result, PrimitiveValue(Boolean(false)));
Ok(())
}
#[test]
fn create_object() -> Result<(), RuntimeError> {
let mut script = Executable::default();
script.script_variables.push(Variable::new("a".to_string()));
script.script_constants = vec![
PrimitiveValue(MyString("Activity".to_string())),
PrimitiveValue(MyString("field1".to_string())),
PrimitiveValue(MyString("field2".to_string())),
PrimitiveValue(Integer(-12)), // constant 0
PrimitiveValue(Integer(55)), // constant 1
];
#[rustfmt::skip]
{
script.script_bytecode.bytes = vec![
OpNewInstance as u8, 0, // Activity::new()
OpConst as u8, 3, // -12
OpSetField as u8, 1, // .field1 = -12
OpConst as u8, 4, // 55
OpSetField as u8, 2, // .field2 = 55
OpGetField as u8, 1, //
OpSetGlobal as u8, 0, // a = .field1
OpReturn as u8, // exit vm
];
}
let mut vm = VirtualMachine::new();
let mut store = MemoryStore::new();
store.set_type_definition(
"Activity",
TypeDefinition {
name: "Activity".to_string(),
fields: vec![
("field1".to_string(), "int".to_string()),
("field2".to_string(), "int".to_string()),
],
},
)?;
vm.run(&script, &mut store, &mut AccumulatingSink::default())?;
assert_eq!(
&integer_to_value!(-12),
vm.global_variables.get("a").unwrap()
);
Ok(())
}
#[test]
fn test_jump() -> Result<(), RuntimeError> {
let mut script = Executable::default();
script.script_variables.push(Variable::new("a".to_string()));
script.script_variables.push(Variable::new("b".to_string()));
script.script_constants.push(integer_to_value!(11));
script.script_constants.push(integer_to_value!(22));
script
.script_constants
.push(string_to_value!("a".to_string()));
script
.script_constants
.push(string_to_value!("b".to_string()));
#[rustfmt::skip]
{
script.script_bytecode.bytes = vec![
// Op // arg
// set up a = 11
OpConst as u8, 0,
OpSetGlobal as u8, 0,
// jump over next 2 instructions
OpJump as u8, 4,
// set a = 22
OpConst as u8, 1,
OpSetGlobal as u8, 0,
// set b = 22 - this is to make sure that we jump to the correct place
OpConst as u8, 1,
OpSetGlobal as u8, 1,
OpReturn as u8,
];
}
let mut vm = VirtualMachine::new();
vm.run(
&script,
&mut MemoryStore::new(),
&mut AccumulatingSink::default(),
)?;
assert_eq!(
&integer_to_value!(11),
vm.global_variables.get("a").unwrap()
);
assert_eq!(
&integer_to_value!(22),
vm.global_variables.get("b").unwrap()
);
Ok(())
}
#[test]
fn test_jump_to_jump() -> Result<(), RuntimeError> {
let mut script = Executable::default();
script.script_variables.push(Variable::new("a".to_string()));
script.script_variables.push(Variable::new("b".to_string()));
script.script_constants.push(integer_to_value!(11));
script.script_constants.push(integer_to_value!(22));
script
.script_constants
.push(string_to_value!("a".to_string()));
script
.script_constants
.push(string_to_value!("b".to_string()));
#[rustfmt::skip]
{
script.script_bytecode.bytes = vec![
// Op // arg
// set up a = 11
OpConst as u8, 0,
OpSetGlobal as u8, 0,
// jump over next 2 instructions
OpJump as u8, 4,
// set a = 22
OpConst as u8, 1,
OpSetGlobal as u8, 0,
// Jump to here, then jump another 5
OpJump as u8, 5,
OpNone as u8,
OpNone as u8,
OpNone as u8,
OpNone as u8,
OpNone as u8,
// set b = 22
OpConst as u8, 1,
OpSetGlobal as u8, 1,
OpReturn as u8,
];
}
let mut vm = VirtualMachine::new();
vm.run(
&script,
&mut MemoryStore::new(),
&mut AccumulatingSink::default(),
)?;
assert_eq!(
&integer_to_value!(11),
vm.global_variables.get("a").unwrap()
);
assert_eq!(
&integer_to_value!(22),
vm.global_variables.get("b").unwrap()
);
Ok(())
}
#[test]
fn test_jump_if_false() -> Result<(), RuntimeError> {
let mut script = Executable::default();
script.script_variables.push(Variable::new("a".to_string()));
script.script_variables.push(Variable::new("b".to_string()));
script.script_constants.push(integer_to_value!(11));
script.script_constants.push(integer_to_value!(22));
script
.script_constants
.push(string_to_value!("a".to_string()));
script
.script_constants
.push(string_to_value!("b".to_string()));
#[rustfmt::skip]
{
script.script_bytecode.bytes = vec![
// Op // arg
// set up a = 11
OpConst as u8, 0,
OpSetGlobal as u8, 0,
// set up b = 22
OpConst as u8, 1,
OpSetGlobal as u8, 1,
OpGetGlobal as u8, 0,
OpGetGlobal as u8, 1,
OpEquals as u8, // this is false
OpJumpIfFalse as u8, 4,
OpNone as u8,
OpNone as u8,
OpNone as u8,
OpNone as u8,
OpPop as u8,
// set up b = 11
OpConst as u8, 0,
OpSetGlobal as u8, 1,
OpGetGlobal as u8, 0,
OpGetGlobal as u8, 1,
OpEquals as u8,
OpJumpIfFalse as u8, 255, // beyond range, will cause panic if it executes
OpPop as u8,
// set a = 22 so we can assert something
OpConst as u8, 1,
OpSetGlobal as u8, 0,
OpReturn as u8,
];
}
let mut vm = VirtualMachine::new();
vm.run(
&script,
&mut MemoryStore::new(),
&mut AccumulatingSink::default(),
)?;
assert_eq!(
&integer_to_value!(22),
vm.global_variables.get("a").unwrap()
);
assert_eq!(
&integer_to_value!(11),
vm.global_variables.get("b").unwrap()
);
Ok(())
}
#[test]
fn test_loop() -> Result<(), RuntimeError> {
let mut script = Executable::default();
script.script_variables.push(Variable::new("a".to_string()));
script.script_constants.push(integer_to_value!(0));
script.script_constants.push(integer_to_value!(1));
script.script_constants.push(integer_to_value!(13));
#[rustfmt::skip]
{
script.script_bytecode.bytes = vec![
// Op // arg
// set up a = 0
OpConst as u8, 0,
OpSetGlobal as u8, 0,
// check:
// push a and limit
OpGetGlobal as u8, 0,
OpConst as u8, 2,
// Compare
OpEquals as u8,
OpNot as u8,
// Jump over loop body
OpJumpIfFalse as u8, 10,
OpPop as u8,
OpConst as u8, 1,
OpGetGlobal as u8, 0,
OpAdd as u8,
OpSetGlobal as u8, 0,
OpLoop as u8, 18, // check:
OpReturn as u8,
];
}
let mut vm = VirtualMachine::new();
vm.run(
&script,
&mut MemoryStore::new(),
&mut AccumulatingSink::default(),
)?;
assert_eq!(
&integer_to_value!(13),
vm.global_variables.get("a").unwrap()
);
Ok(())
}
#[test]
fn open_pull_close_cursor() -> Result<(), RuntimeError> {
let mut store = MemoryStore::new();
store
.set_function_value("f", &vec![integer_to_value!(1)], integer_to_value!(2))
.unwrap();
let mut script = Executable::default();
script
.script_constants
.push(FunctionNameValue("f".to_string()));
script.script_variables.push(Variable::new("a".to_string()));
script.script_variables.push(Variable::new("b".to_string()));
#[rustfmt::skip]
{
script.script_bytecode.bytes = vec![
OpConst as u8, 0,
OpOpenCursor as u8, 0,
OpPull as u8, 0,
OpSetGlobal as u8, 0,
OpPop as u8,
OpSetGlobal as u8, 1,
OpPop as u8,
OpCloseCursor as u8, 0,
OpReturn as u8,
];
}
let mut vm = VirtualMachine::new();
vm.run(&script, &mut store, &mut AccumulatingSink::default())?;
assert_eq!(&integer_to_value!(1), vm.global_variables.get("a").unwrap());
assert_eq!(&integer_to_value!(2), vm.global_variables.get("b").unwrap());
Ok(())
}
#[test]
fn test_cursor_pull_then_predicate_and_return() -> Result<(), RuntimeError> {
// match f(x) -> (y), eq(x, y+1), return (x, y)
let mut store = MemoryStore::new();
store
.set_function_value("f", &vec![integer_to_value!(1)], integer_to_value!(2))
.unwrap();
store
.set_function_value("f", &vec![integer_to_value!(3)], integer_to_value!(4))
.unwrap();
let mut eq_fdo = FunctionDefinitionObject::new("eq".to_string());
eq_fdo
.formal_arguments
.push(Parameter::Variable("x".to_string()));
eq_fdo
.formal_arguments
.push(Parameter::Variable("y".to_string()));
eq_fdo.variables.push(Variable::new("x".to_string()));
eq_fdo.variables.push(Variable::new("y".to_string()));
#[rustfmt::skip]
{
eq_fdo.bytecode.bytes = vec![
OpGetLocal as u8, 0,
OpGetLocal as u8, 1,
OpEquals as u8,
OpReturn as u8,
];
}
store
.set_function_definition(
"eq",
&vec![
Parameter::Variable("x".to_string()),
Parameter::Variable("y".to_string()),
],
eq_fdo,
)
.unwrap();
let mut script = Executable::default();
script
.script_constants
.push(FunctionNameValue("f".to_string()));
script.script_constants.push(integer_to_value!(1));
script
.script_constants
.push(FunctionNameValue("eq".to_string()));
#[rustfmt::skip]
{
script.script_bytecode.bytes = vec![
// prologue 1
OpConst as u8, 0,
OpOpenCursor as u8, 0,
OpPull as u8, 0,
OpJumpIfFalse as u8, 21, // exit:
// body
OpSetLocal as u8, 0,
OpSetLocal as u8, 1,
// prepare stack for calling eq, push x, y and const 1
OpGetLocal as u8, 0,
OpGetLocal as u8, 1,
OpConst as u8, 1,
OpAdd as u8,
// Function name
OpConst as u8, 2,
OpCall as u8, 2,
OpJumpIfFalse as u8, 2,
OpProduce as u8, 0,
OpLoop as u8, 25,
OpCloseCursor as u8, 0,
// exit:
OpReturn as u8,
];
}
let mut vm = VirtualMachine::new();
vm.run(&script, &mut store, &mut AccumulatingSink::default())?;
Ok(())
}
#[test]
fn test_self_join() -> Result<(), RuntimeError> {
// match f(x), f(y), { print(x) print(y)}
let mut store = MemoryStore::new();
store
.set_function_value("f", &vec![integer_to_value!(1)], integer_to_value!(2))
.unwrap();
store
.set_function_value("f", &vec![integer_to_value!(3)], integer_to_value!(4))
.unwrap();
let mut script = Executable::default();
script
.script_constants
.push(FunctionNameValue("f".to_string()));
/*
Produce { name: "f", name_const: 0, params: [[20, 0]] }
Produce { name: "f", name_const: 0, params: [[20, 1]] }
Block { code: Bytecode { bytes: [21, 0, 24, 21, 1, 24] }
*/
#[rustfmt::skip]
{
script.script_bytecode.bytes = vec![
// prologue 1
OpConst as u8, 0,
OpOpenCursor as u8, 0,
OpPull as u8, 0,
OpJumpIfFalse as u8, 24,
// body 1
OpSetLocal as u8, 0,
OpPop as u8,
// prologue 2
OpConst as u8, 0,
OpOpenCursor as u8, 1,
OpPull as u8, 1,
OpJumpIfFalse as u8, 10,
// body 2
OpSetLocal as u8, 1,
OpPop as u8,
OpGetLocal as u8, 0,
OpGetLocal as u8, 1,
// epilogue 2
OpLoop as u8, 13,
OpCloseCursor as u8, 1,
// epilogue 1
OpLoop as u8, 28,
OpCloseCursor as u8, 0,
// return
OpReturn as u8,
];
}
let mut vm = VirtualMachine::new();
vm.run(&script, &mut store, &mut AccumulatingSink::default())?;
Ok(())
}
}