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
use crate::chunk::OpCode::*;
use crate::chunk::{ClassChunk, FunctionChunk, Instr, ModuleChunk};
use crate::compiler::CompilationResult;
use crate::debug::*;
use crate::gc::GC;
use crate::native::native_functions::*;
use crate::native::native_methods::{NativeMethod, NATIVE_METHODS};
use crate::resolver::UpValue;
use crate::value::{
is_falsey, values_equal, HeapObj, HeapObjType, HeapObjVal, ObjBoundMethod, ObjClosure,
ObjHashMap, ObjInstance, ObjList, ObjString, Value,
};
use crate::{error, phoenix_error, warn, InterpretResult, VERSION};
use std::collections::HashMap;
use std::io::{stdin, stdout, Write};
use std::thread::{sleep};
use std::time::Duration;
const FRAMES_MAX: usize = 255;
#[derive(Debug)]
pub enum ExecutionMode {
Default,
Trace,
}
/// This ended up not being very useful since we usually don't care what kind of deref error we get, they usually mean the same thing, that we tried to use a value in a way it wasn't supposed to be used
#[derive(Debug, Clone, Copy)]
pub enum DerefError {
NotPointer,
WrongType,
}
#[derive(Debug, Clone, PartialEq)]
pub struct CallFrame {
/// Index into the VM.modules Vec for which module is being called
pub module: usize,
/// Index into the VM.functions Vec for which function is being called
function: usize,
pub ip: usize,
frame_start: usize,
}
#[derive(Debug, PartialEq, Clone)]
pub enum Global {
Init(Value),
Uninit,
}
// Is it good rust to split these into two very coupled but separate structs or is there a way to keep them together while not angering the borrow checker?
//
// I think this setup worked quite well, but I'm sure there's a better way to do it
/// Manages all the state involved with the VM's execution, namely the stack, global variables, the heap, and the call frames
#[derive(PartialEq, Debug, Clone)]
pub struct VMState {
pub current_frame: CallFrame,
stack: Vec<Value>,
frames: Vec<CallFrame>,
// we have a Vec of Vecs because each module has its own set of globals
pub(crate) globals: Vec<Vec<Global>>,
gc: GC,
// Not implemented due to it destroying my code => multiple upvalues pointing to the same original value in a function will NOT affect each other. This is a small enough edge case that I'm willing to just let it go
// upvalues: Vec<Value>,
/// stack of called modules for returning home after entering a new module for a function call
module_stack: Vec<usize>,
}
impl VMState {
fn pop(&mut self) -> Value {
match self.stack.pop() {
Some(x) => x,
None => {
phoenix_error!("VM panic! Attempted to pop a value when the value stack was empty");
}
}
}
// Note to future self: peek_mut SHOULD NEVER BE IMPLEMENTED!
// Values on the stack are always implicit copy/cloned, any persistent values must be allocated with the Gc and represented with PhoenixPointers instead
fn peek(&self) -> &Value {
self.peek_at(0)
}
fn peek_at(&self, dist: usize) -> &Value {
match self.stack.get(self.stack.len() - dist - 1) {
Some(x) => x,
None => {
phoenix_error!(
"VM panic! Attempted to peek a value when the value stack was empty"
);
}
}
}
fn alloc(&mut self, val: HeapObj) -> Value {
self.gc
.alloc(val, &self.stack, &self.globals[self.current_frame.module])
}
fn alloc_string(&mut self, string: String) -> Value {
self.alloc(HeapObj::new_string(ObjString::new(string)))
}
// Fixme: Figure out how to not copy paste this code for mut and immut
pub fn deref(&self, pointer: usize) -> &HeapObj {
match self.gc.instances.get(pointer) {
Some(x) => x,
None => {
phoenix_error!("VM panic! Invalid pointer");
}
}
}
pub fn deref_mut(&mut self, pointer: usize) -> &mut HeapObj {
match self.gc.instances.get_mut(pointer) {
Some(x) => x,
None => {
phoenix_error!("VM panic! Invalid pointer");
}
}
}
pub fn deref_list(&self, pointer: usize) -> &ObjList {
let obj = self.deref(pointer);
if let HeapObjType::PhoenixList = obj.obj_type {
obj.obj.as_list()
} else {
phoenix_error!("VM panic! Attempted to deref a non-list object as a list");
}
}
pub fn deref_list_mut(&mut self, pointer: usize) -> &ObjList {
let obj = self.deref_mut(pointer);
if let HeapObjType::PhoenixList = obj.obj_type {
obj.obj.as_list_mut()
} else {
phoenix_error!("VM panic! Attempted to deref a non-list object as a list");
}
}
pub fn deref_string(&self, pointer: usize) -> &ObjString {
let obj = self.deref(pointer);
if let HeapObjType::PhoenixString = obj.obj_type {
obj.obj.as_string()
} else {
phoenix_error!("VM panic! Attempted to deref a non-string object as a string");
}
}
pub fn deref_string_mut(&mut self, pointer: usize) -> &mut ObjString {
let obj = self.deref_mut(pointer);
if let HeapObjType::PhoenixString = obj.obj_type {
obj.obj.as_string_mut()
} else {
phoenix_error!("VM panic! Attempted to deref a non-string object as a string");
}
}
pub fn create_string(&mut self, s: String) {
let string_obj = ObjString::new(s);
let string_ptr = self.alloc(HeapObj::new_string(string_obj));
self.stack.push(string_ptr);
}
/// Attempts to
/// 1. Take the given Value as a PhoenixPointer
/// 2. Deref it into a HeapObj
/// 3. Match the obj_types
fn deref_into(
&self,
pointer_val: &Value,
obj_type: HeapObjType,
) -> Result<&HeapObjVal, DerefError> {
if let Value::PhoenixPointer(pointer) = pointer_val {
let obj = self.deref(*pointer);
if obj.obj_type == obj_type {
Ok(&obj.obj)
} else {
Err(DerefError::WrongType)
}
} else {
Err(DerefError::NotPointer)
}
}
fn deref_into_mut(
&mut self,
pointer_val: &Value,
obj_type: HeapObjType,
) -> Result<&mut HeapObjVal, DerefError> {
if let Value::PhoenixPointer(pointer) = pointer_val {
let obj = self.deref_mut(*pointer);
if obj.obj_type == obj_type {
Ok(&mut obj.obj)
} else {
Err(DerefError::WrongType)
}
} else {
Err(DerefError::NotPointer)
}
}
fn current_closure(&self) -> &ObjClosure {
let pointer_val = match self.stack.get(self.current_frame.frame_start) {
Some(x) => x,
None => {
phoenix_error!("VM panic! Unable to get current closure?");
}
};
match self.deref_into(pointer_val, HeapObjType::PhoenixClosure) {
Ok(closure_obj) => closure_obj.as_closure(),
Err(x) => {
phoenix_error!("VM panic! Unable to get current closure? {:?}", x);
}
}
}
fn current_closure_mut(&mut self) -> &mut ObjClosure {
let pointer_val = match self.stack.get(self.current_frame.frame_start) {
Some(x) => x,
None => {
phoenix_error!("VM panic! Unable to get current closure?");
}
}
.clone();
match self.deref_into_mut(&pointer_val, HeapObjType::PhoenixClosure) {
Ok(closure_obj) => closure_obj.as_closure_mut(),
Err(x) => {
phoenix_error!("VM panic! Unable to get current closure? {:?}", x);
}
}
}
fn increment_ip(&mut self) {
self.current_frame.ip += 1;
}
fn jump(&mut self, offset: usize) {
self.current_frame.ip += offset - 1;
}
fn jump_back(&mut self, neg_offset: usize) {
self.current_frame.ip -= neg_offset + 1;
}
fn capture_upvalue(&self, upvalue: &UpValue) -> Value {
if upvalue.is_local {
// Just copy the value from the current stack frame (which is the parents)
self.stack[self.current_frame.frame_start + upvalue.index].clone()
} else {
// Look at the current frame's closure's upvalue vec and copy it from there
let parent_closure = self.current_closure();
parent_closure.values[upvalue.index].clone()
}
}
/// Push an upvalue onto the stack
fn push_upvalue(&mut self, index: usize) {
let closure = self.current_closure();
let val = match closure.values.get(index) {
Some(x) => x,
None => {
phoenix_error!("VM panic! Attempted to push an upvalue that doesn't exist");
}
}
.clone();
self.stack.push(val);
}
/// Set an upvalue with the top value of the stack
fn set_upvalue(&mut self, index: usize) {
let val = self.peek().clone();
let closure = self.current_closure_mut();
closure.values[index] = val;
}
/// Checks if the targeted Value is callable {PhoenixPointer to a PhoenixClosure, NativeFn, PhoenixClass, PhoenixBoundMethod}, passes it to call() to continue attempting the call if necessary.
///
/// Note: This function or call() must fulfill the promise made in Resolver about what value sits in slot 0 of the local variables.
/// Whether that's 'this' or a placeholder
///
/// Returns a String containing an error message or None
fn call_value(
&mut self,
arg_count: usize,
function_defs: &[FunctionChunk],
class_defs: &[ClassChunk],
_module: &ModuleChunk,
vm: &VM,
modules: &[ModuleChunk],
) -> Option<String> {
let init_slot = vm.init_slot;
let callee = self.peek_at(arg_count);
if let Value::PhoenixPointer(_) = callee {
match self.deref_into(callee, HeapObjType::PhoenixClosure) {
Ok(closure) => {
let closure = closure.as_closure();
let fn_index = closure.function;
self.call(fn_index, arg_count, function_defs)
}
Err(_) => Some(String::from("Can only call functions and classes")),
}
} else if let Value::PhoenixFunction(fn_index) = callee {
let index = *fn_index;
self.call(index, arg_count, function_defs)
} else if let Value::PhoenixBoundMethod(method) = callee {
let fn_index = method.method;
let index = self.stack.len() - arg_count - 1; // Index to put the PhoenixPointer to represent the "this" variable
self.stack[index] = Value::PhoenixPointer(method.pointer);
self.call(fn_index, arg_count, function_defs)
} else if let Value::PhoenixClass(class) = callee {
let instance_obj = ObjInstance::new(*class);
let class_def = &class_defs[*class];
let ptr = self.alloc(HeapObj::new_instance(instance_obj));
let index = self.stack.len() - arg_count - 1;
self.stack[index] = ptr; // Replace the PhoenixClass with the pointer
// Call the initializer if it exists
// If the PhoenixClass was called with arguments the stack will look like this: PhoenixClass | arg1 | arg2
// So we want to call with the stack as: PhoenixPointer => PhoenixInstance | arg1 | arg2
// And we need the init() fn to return the PhoenixInstance
if class_def.has_init {
if init_slot.is_none() {
phoenix_error!("VM panic! Attempted to call a custom initializer without it existing as a method identifier?");
}
self.call(
*class_def.methods.get(&init_slot.unwrap()).unwrap(),
arg_count,
function_defs,
)
} else if arg_count != 0 {
Some(format!(
"Expected 0 arguments but got {} instead",
arg_count
))
} else {
// hacky fix because class definitions dont return with a classic return opcode
Some("back".to_string())
}
} else if let Value::NativeFunction(native_arg_count, native_fn) = callee {
let native_fn = *native_fn;
self.call_native(&native_fn, arg_count, *native_arg_count, vm, modules)
} else {
Some(String::from("Can only call functions and classes"))
}
}
/// Attempts to call a function with the values on the stack, with the given # of arguments
fn call(
&mut self,
fn_index: usize,
arg_count: usize,
function_defs: &[FunctionChunk],
) -> Option<String> {
let target_fn = match function_defs.get(fn_index) {
Some(x) => x,
None => return Some(format!("Function with index {} does not exist", fn_index)),
};
if arg_count != target_fn.arity {
return Some(format!(
"Expected {} arguments but got {} instead",
target_fn.arity, arg_count
));
}
if self.frames.len() == FRAMES_MAX {
return Some(String::from("Stack overflow"));
}
let mut frame = CallFrame {
module: self.current_frame.module,
function: fn_index,
ip: 0,
frame_start: self.stack.len() - arg_count - 1,
};
// Swap on the new call frame for the old one
std::mem::swap(&mut self.current_frame, &mut frame);
// Put the old one onto the stack
self.frames.push(frame);
None
}
/// Attempts to call a native (rust) function
fn call_native(
&mut self,
native_fn: &NativeFn,
arg_count: usize,
native_arg_count: Option<usize>,
vm: &VM,
modules: &[ModuleChunk],
) -> Option<String> {
let mut args: Vec<Value> = Vec::new();
for _ in 0..arg_count {
args.push(self.pop());
}
self.pop(); // Pop off the Value::NativeFunction
args.reverse();
if let Some(n_a_count) = native_arg_count {
if arg_count != n_a_count {
return Some(format!(
"Expected {} arguments but got {} instead",
n_a_count, arg_count
));
}
}
let result = match native_fn(args, vm, self, modules) {
Ok(x) => x,
Err(e) => return Some(e),
};
// check if the value is a PhoneixString and if yes call state.create_string
if let Value::PhoenixString(s) = result {
self.create_string(s);
} else {
self.stack.push(result);
}
// self.stack.push(result);
None
}
/// Attempts to call a native (rust) method
/// returns: If first Option is None, the method doesnt support this type, if the second Option is None, the function was successfully
fn call_method(
&mut self,
native_method: &NativeMethod,
arg_count: usize,
native_arg_count: Option<usize>,
vm: &VM,
modules: &[ModuleChunk],
) -> Option<Option<String>> {
// println!(
// "calling method, arg_count: {}, stack: {:?}",
// arg_count, self.stack
// );
// we need know the stack looks like this: self | arg1 | arg2 | ... | argn
let mut args: Vec<Value> = Vec::new();
for _ in 0..arg_count {
args.push(self.pop());
}
// self.pop(); // Pop off the Value::NativeFunction
args.reverse();
let this = self.pop();
if let Some(n_a_count) = native_arg_count {
if arg_count != n_a_count {
return Some(Some(format!(
"Expected {} arguments but got {} instead",
n_a_count, arg_count
)));
}
}
let result = match native_method(this, args, vm, self, modules) {
Some(x) => match x {
Ok(x) => x,
Err(e) => return Some(Some(e)),
},
None => return None,
};
// check if the value is a PhoenixString and if yes call state.create_string
if let Value::PhoenixString(s) = result {
self.create_string(s);
} else {
self.stack.push(result);
}
// self.stack.push(result);
Some(None)
}
/// Defines all native functions
///
/// Searches for references to native functions and adds them in if they're used in the program
fn define_std_lib(&mut self, identifiers: &[String]) {
for (str, nf) in match NATIVE_FUNCTIONS.lock() {
Ok(x) => x,
Err(_) => phoenix_error!("Failed to lock native functions mutex"),
}
.iter()
{
if let Some(index) = identifiers.iter().position(|x| x == str) {
self.globals[self.current_frame.module][index] =
Global::Init(Value::NativeFunction(nf.0, nf.1));
}
}
}
/// Initializes the VMState with:
///
/// - A CallFrame for function #0 and module #0 (should be the main module)
/// - Defined global variables for the native functions
/// - A Value::PhoenixFunction for function #0 pushed onto the stack => Satisfies the resolver assumption that the first locals slot is filled with something
/// update the globals each time a new module is loaded
fn new(identifiers: &Vec<String>) -> VMState {
let first_fn = CallFrame {
module: 0,
function: 0,
ip: 0,
frame_start: 0,
};
let first_val = Value::PhoenixFunction(0);
let stack = vec![first_val];
let mut state = VMState {
current_frame: first_fn,
stack,
frames: Vec::new(),
// globals: vec![Global::Uninit; identifiers.len()],
globals: vec![vec![Global::Uninit; identifiers.len()]],
gc: GC::new(),
module_stack: vec![0],
};
// todo: make this work with modules
state.define_std_lib(identifiers);
state
}
}
/// Contains all the information outputted by the compiler
/// ie: All function and class definitions
pub struct VM {
quiet_mode: bool,
mode: ExecutionMode,
pub modules_cache: Vec<ModuleChunk>,
pub modules_table: HashMap<String, usize>,
init_slot: Option<usize>,
}
impl VM {
pub fn new(mode: ExecutionMode, result: CompilationResult, quiet: bool) -> VM {
// compare version of the compilationResult and the VM
if result.version != *VERSION {
warn!(
"Version mismatch! Expected {} but got {}",
VERSION, result.version
);
}
let init_slot = result
.modules
.get(0)
.and_then(|x| x.clone().identifiers.iter().position(|x| x == "init"));
let modules = result.modules;
VM {
quiet_mode: quiet,
mode,
modules_cache: modules,
init_slot,
modules_table: result.modules_table,
}
}
pub fn append(&mut self, result: CompilationResult) {
let init_slot = result.modules[0]
.clone()
.identifiers
.iter()
.position(|x| x == "init");
if !self.modules_cache.is_empty() {
self.modules_cache[0].functions[0].chunk.code.pop();
}
self.modules_cache.extend(result.modules);
self.modules_table.extend(result.modules_table);
self.init_slot = init_slot;
}
fn runtime_error(&self, msg: &str, state: &VMState, modules: &[ModuleChunk]) {
if self.quiet_mode {
return;
}
error!("{}", msg);
for call_frame in [state.current_frame.clone()]
.iter()
.chain(state.frames.iter().rev())
{
let function = &modules[state.current_frame.module]
.functions
.get(call_frame.function)
.unwrap();
eprint!(
"[{}:{}] in ",
modules[state.current_frame.module].file,
function.chunk.code.get(call_frame.ip).unwrap().line_num + 1
);
match &function.name {
Some(name) => eprintln!("{}", name),
None => eprintln!("script"),
}
}
}
// /// Returns the current module
// pub(crate) fn current_module(state: &VMState, modules: &Vec<ModuleChunk>) -> &ModuleChunk {
// &modules[state.current_frame.module]
// }
/// Should only be used for getting debugging and error reporting
///
/// * For the global instructions, just the index should suffice
/// * For instance properties and fields, the hashmaps are keyed on the usize corresponding to the identifier string
/// * Local variable names are erased completely by the resolver at compile time
fn get_variable_name<'a>(
index: usize,
state: &VMState,
modules: &'a [ModuleChunk],
) -> &'a String {
let name_val = &modules[state.current_frame.module].identifiers.get(index);
if let Some(var_name) = name_val {
var_name
} else {
panic!("VM panic: Found a non PhoenixString value for a variable name");
}
}
// fn get_current_code(&self, state: &VMState, modules: &Vec<ModuleChunk>) -> &Vec<Instr> {
// &modules[state.current_frame.module]
// .functions
// .get(state.current_frame.function)
// .unwrap()
// .chunk
// .code
// }
pub fn run(&mut self) -> InterpretResult {
self.run_state(None, Vec::new())
}
pub fn run_state(&mut self, state: Option<VMState>, m: Vec<ModuleChunk>) -> InterpretResult {
if let ExecutionMode::Trace = self.mode {
eprintln!("== Starting execution | Mode: {:?} ==", self.mode);
debug_print_constants(&self.modules_cache);
}
// look at the functions in the first module
let mut state = if let Some(s) = state {
s
} else {
VMState::new(&self.modules_cache[0].identifiers)
};
state.define_std_lib(&self.modules_cache[0].identifiers);
// todo: maybe move this to VMState
let modules = self.modules_cache.clone();
self.modules_cache = m;
// todo: make this work with modules
// modules[0].define_std_lib(&modules[0].identifiers, &modules[0]);
// let mut states = vec![&mut state];
// let mut parent_states = Vec::new();
// Makes getting new instructions faster
// Update this vec whenever
let mut current_code = &modules[state.current_frame.module]
.functions
.get(state.current_frame.function)
.unwrap()
.chunk
.code[..];
// Move this into a match arm that matches all the binary ops, and then matches on the individual opcodes?
macro_rules! op_binary {
($val_type: path, $oper: tt) => {
{
//if let ($val_type(a), $val_type(b)) = (self.pop(), self.pop()) {
let var_a = state.pop();
let var_b = state.pop();
if let (Value::Float(a), Value::Float(b)) = (var_a.clone(), var_b.clone()) {
state.stack.push($val_type(b $oper a))
} else if let (Value::Long(a), Value::Long(b)) = (var_a, var_b) {
state.stack.push($val_type(b $oper a))
} else {
self.runtime_error("Operands must be numbers", &state, &modules);
return InterpretResult::InterpretRuntimeError;
}
}
};
($val_type: path, $val_type2: path, $oper: tt) => {
{
//if let ($val_type(a), $val_type(b)) = (self.pop(), self.pop()) {
let var_a = state.pop();
let var_b = state.pop();
if let (Value::Float(a), Value::Float(b)) = (var_a.clone(), var_b.clone()) {
state.stack.push($val_type(b $oper a))
} else if let (Value::Long(a), Value::Long(b)) = (var_a.clone(), var_b.clone()) {
state.stack.push($val_type2(b $oper a))
} else if let (Value::Long(_a), Value::Float(_b)) = (var_a.clone(), var_b.clone()) {
self.runtime_error(concat!("Operands must have the same type for the ", stringify!($oper), " operation. (long and float)"), &state, &modules);
return InterpretResult::InterpretRuntimeError;
} else if let (Value::Float(_a), Value::Long(_b)) = (var_a.clone(), var_b.clone()) {
self.runtime_error(concat!("Operands must have the same type for the ", stringify!($oper), " operation. (float and long)"), &state, &modules);
return InterpretResult::InterpretRuntimeError;
} else {
self.runtime_error(concat!("Operands must be numbers for the ", stringify!($oper), " operation"), &state, &modules);
return InterpretResult::InterpretRuntimeError;
}
}
}
}
loop {
let instr = match current_code.get(state.current_frame.ip) {
Some(instr) => instr,
None => {
phoenix_error!(
"Tried to access an invalid instruction, index: {}, length: {}",
state.current_frame.ip,
current_code.len()
);
}
};
state.increment_ip(); // Preincrement the ip so OpLoops to 0 are possible
if let ExecutionMode::Trace = self.mode {
debug_trace(self, instr, &state, &modules);
}
match instr.op_code {
OpImport(module_index) => {
// println!(
// "Importing module: {}, stack len: {}",
// module_index,
// state.stack.len()
// );
if state.frames.len() == FRAMES_MAX {
self.runtime_error("Stack overflow", &state, &modules);
return InterpretResult::InterpretRuntimeError;
}
let mut frame = CallFrame {
module: module_index,
function: 0,
ip: 0,
frame_start: 0,
};
// Swap on the new call frame for the old one
std::mem::swap(&mut state.current_frame, &mut frame);
// Put the old one onto the stack
state.frames.push(frame);
current_code = &modules[state.current_frame.module]
.functions
.get(state.current_frame.function)
.unwrap()
.chunk
.code[..];
if state.globals.len() < module_index + 1 {
// println!("Pushing new globals for module: {:?}", module_index);
let len = modules[module_index].identifiers.len();
state.globals.push(vec![Global::Uninit; len]);
}
}
OpReturn => {
let result = state.pop(); // Save the result (the value on the top of the stack)
for _ in 0..(state.stack.len() - state.current_frame.frame_start) {
// Clean up the call frame part of that stack
state.pop();
}
if state.frames.is_empty() {
return InterpretResult::InterpretOK(state, modules);
} else {
state.current_frame = state.frames.pop().unwrap(); // Update the current frame
if state.module_stack != vec![0] {
state.current_frame.module = state.module_stack.pop().unwrap();
}
current_code = &modules[state.current_frame.module]
.functions
.get(state.current_frame.function)
.unwrap()
.chunk
.code[..]; // Update the current code
state.stack.push(result); // Push the result back
}
}
OpPop => {
state.pop();
}
OpDefineGlobal(index) => {
let var_val = state.pop();
state.globals[state.current_frame.module][index] = Global::Init(var_val);
}
OpCallGlobal(module_index, index, arity) => {
let cur_module = state.current_frame.module;
state.module_stack.push(cur_module);
state.current_frame.module = module_index;
let var_val = &state.globals[state.current_frame.module][index];
match var_val {
Global::Init(x) => {
let new = x.clone();
let index = state.stack.len() - arity;
state.stack.insert(index, new);
let result = state.call_value(
arity,
&modules[state.current_frame.module].functions,
&modules[state.current_frame.module].classes,
&modules[state.current_frame.module],
self,
&modules,
);
if let Some(msg) = result {
if msg == "back" {
// when classes are initialized, there is no return opcode emitted, so we have to return to the old module by ourself
state.current_frame.module = state.module_stack.pop().unwrap();
} else {
self.runtime_error(&msg[..], &state, &modules);
return InterpretResult::InterpretRuntimeError;
}
}
current_code = &modules[state.current_frame.module]
.functions
.get(state.current_frame.function)
.unwrap()
.chunk
.code[..]; // Update the current code
}
_ => {
self.runtime_error(
format!(
"Undefined variable '{}'",
VM::get_variable_name(index, &state, &modules)
)
.as_str(),
&state,
&modules,
);
return InterpretResult::InterpretRuntimeError;
}
}
}
OpGetGlobal(index) => {
let var_val = &state.globals[state.current_frame.module][index];
match var_val {
Global::Init(x) => {
let new = x.clone();
state.stack.push(new)
}
_ => {
self.runtime_error(
format!(
"Undefined variable '{}'",
VM::get_variable_name(index, &state, &modules)
)
.as_str(),
&state,
&modules,
);
return InterpretResult::InterpretRuntimeError;
}
}
}
OpGetModuleVar(module_index, index) => {
// println!("globals: {:?}", state.globals);
let var_val = &state.globals[module_index][index];
match var_val {
Global::Init(x) => {
let new = x.clone();
state.stack.push(new)
}
_ => {
self.runtime_error(
format!(
"Undefined variable '{}'",
VM::get_variable_name(index, &state, &modules)
)
.as_str(),
&state,
&modules,
);
return InterpretResult::InterpretRuntimeError;
}
}
}
OpSetGlobal(index) => {
// We don't want assignment to pop the value since this is an expression
// this will almost always be in a expression statement, which will pop the value
let var_val = state.peek().clone();
match &state.globals[state.current_frame.module][index] {
Global::Init(_) => {
state.globals[state.current_frame.module][index] = Global::Init(var_val)
} // We require it to be initialized (ie defined earlier by OpDefineGlobal)
_ => {
self.runtime_error(
format!(
"Undefined variable '{}'",
VM::get_variable_name(index, &state, &modules)
)
.as_str(),
&state,
&modules,
);
return InterpretResult::InterpretRuntimeError;
}
}
}
OpGetLocal(index) => state
.stack
.push(state.stack[state.current_frame.frame_start + index].clone()), // Note: We gotta clone these values around the stack because our operators pop off the top and we also don't want to modify the variable value
OpSetLocal(index) => {
let dest = state.current_frame.frame_start + index;
state.stack[dest] = state.peek().clone(); // Same idea as OpSetGlobal, don't pop value since it's an expression
}
OpInvoke(name_index, arg_count, module_index) => {
let cur_module = state.current_frame.module;
state.module_stack.push(cur_module);
state.current_frame.module = module_index;
let pointer_val = state.peek_at(arg_count).clone();
let obj = if let Value::PhoenixPointer(pointer) = pointer_val {
state.deref(pointer)
} else {
self.runtime_error(
"Can only invoke methods on instances and lists",
&state,
&modules,
);
return InterpretResult::InterpretRuntimeError;
};
let result =
// match state.deref_into(&pointer_val.clone(), HeapObjType::PhoenixInstance) {
match &obj.obj {
HeapObjVal::PhoenixInstance(_) => {
let instance = obj.obj.as_instance();
let class_def =
&&modules[state.current_frame.module].classes[instance.class];
if instance.fields.contains_key(&name_index) {
// Guard against the weird edge case where instance.thing() is actually calling a closure instance.thing, not a method invocation
let value = instance.fields.get(&name_index).unwrap().clone();
let index = state.stack.len() - 1 - arg_count;
state.stack[index] = value; // Remove the instance and replace with the value
state.call_value(
arg_count,
&modules[state.current_frame.module].functions,
&modules[state.current_frame.module].classes,
&modules[state.current_frame.module],
self,
&modules,
)
// Perform the call
} else if class_def.methods.contains_key(&name_index) {
// We know that the top of the stack is PhoenixPointer | arg1 | arg2
// So we can go ahead and call
let fn_index = class_def.methods.get(&name_index).unwrap();
state.call(
*fn_index,
arg_count,
&modules[state.current_frame.module].functions,
)
} else {
Some(format!(
"Undefined property '{}' in {:?}",
VM::get_variable_name(name_index, &state, &modules),
instance
))
}
}
/*HeapObjVal::PhoenixList(_) => {
// check if its a list
let curr_module = state.current_frame.module;
// we need to deref the pointer to get the actual list
match state.deref_into_mut(&pointer_val, HeapObjType::PhoenixList) {
Ok(&mut ref mut list) => {
match list {
HeapObjVal::PhoenixList(ref mut list) => {
match &*modules[curr_module].identifiers[name_index] {
// "push" => {
// list.values.push(value);
// }
"pop" => {
if let Some(val) = list.values.pop() {
state.stack.push(val);
} else {
self.runtime_error(
"Attempted to pop from an empty list",
&state,
&modules,
);
return InterpretResult::InterpretRuntimeError;
}
None
}
"len" => {
let len = list.values.len() as i64;
state.stack.push(Value::Long(len));
None
}
"sort" => {
list.values.sort_by(|a, b| {
if let Value::Float(a) = a {
if let Value::Float(b) = b {
return a.partial_cmp(b).unwrap();
}
}
if let Value::Long(a) = a {
if let Value::Long(b) = b {
return a.partial_cmp(b).unwrap();
}
}
panic!("Attempted to sort a list with non-numeric values");
});
None
}
_ => {
// self.runtime_error(
// format!("Function {} not found on list", &*modules[curr_module].identifiers[name_index]).as_str(),
// &state,
// &modules,
// );
// return InterpretResult::InterpretRuntimeError;
Some(format!("Function \"{}\" not found on list", &*modules[curr_module].identifiers[name_index]))
}
}
}
_ => {
self.runtime_error(
"Attempted to index a non-indexable value",
&state,
&modules,
);
return InterpretResult::InterpretRuntimeError;
}
}
}
Err(_) => {
Some(String::from(
"Can only invoke methods on class instances and lists",
))
}
}
}*/
_ => Some(format!(
"Can only invoke methods on instances and lists, not {:?}",
obj
)),
};
if let Some(error) = result {
let result = if NATIVE_METHODS.lock().unwrap().contains_key(
modules[state.current_frame.module].identifiers[name_index].as_str(),
) {
// println!("found method in native methods");
let native_methods = NATIVE_METHODS.lock().unwrap();
let native_method = native_methods
.get(
modules[state.current_frame.module].identifiers[name_index]
.as_str(),
)
.unwrap();
if native_method.0.is_some() && native_method.0.unwrap() != arg_count {
Some(format!(
"Expected {} arguments but got {} instead",
native_method.0.unwrap(),
arg_count
))
} else {
let result = state.call_method(
&native_method.1,
arg_count,
native_method.0,
self,
&modules,
);
if result.is_none() {
Some(error)
} else if let Some(Some(msg)) = result {
self.runtime_error(&msg[..], &state, &modules);
return InterpretResult::InterpretRuntimeError;
} else {
None
}
}
} else {
Some(error)
};
if let Some(error) = result {
self.runtime_error(error.as_str(), &state, &modules);
return InterpretResult::InterpretRuntimeError;
}
}
current_code = &modules[state.current_frame.module]
.functions
.get(state.current_frame.function)
.unwrap()
.chunk
.code[..]; // Update the current code
}
OpGetProperty(name_index) => {
let pointer_val = state.peek();
// Todo: Combine this and SetProperty into a macro so it doesn't hurt me everytime i have to read this
match state.deref_into(pointer_val, HeapObjType::PhoenixInstance) {
Ok(instance) => {
let instance = instance.as_instance();
if instance.fields.contains_key(&name_index) {
// See if we tried to get a field
let value = instance.fields.get(&name_index).unwrap().clone();
state.pop(); // Remove the instance
state.stack.push(value); // Replace with the value
} else {
let class_chunk =
&&modules[state.current_frame.module].classes[instance.class]; // if not a field, then we must be getting a function. Create a PhoenixBoundMethod for it
if class_chunk.methods.contains_key(&name_index) {
let bound_value = ObjBoundMethod {
method: *class_chunk.methods.get(&name_index).unwrap(),
pointer: pointer_val.as_pointer(),
};
state.pop(); // Remove the instance
state.stack.push(Value::PhoenixBoundMethod(bound_value));
// Replace with bound method
} else {
self.runtime_error(
format!(
"Undefined property '{}' in {:?}",
VM::get_variable_name(name_index, &state, &modules),
instance
)
.as_str(),
&state,
&modules,
);
return InterpretResult::InterpretRuntimeError;
}
}
}
Err(_) => {
let msg = format!("Only class instances can access properties with '.' Found {} instead", pointer_val.to_string(self, &state, &modules));
self.runtime_error(msg.as_str(), &state, &modules);
return InterpretResult::InterpretRuntimeError;
}
}
}
OpSetProperty(name_index) => {
// Fixme: this is nearly identical to OpGetProperty, is there any way to combine them nicely?
let val = state.pop();
let pointer_val = state.peek().clone();
match state.deref_into_mut(&pointer_val, HeapObjType::PhoenixInstance) {
Ok(instance) => {
let instance = instance.as_instance_mut();
instance.fields.insert(name_index, val.clone());
}
Err(_) => {
let msg = format!("Only class instances can access properties with '.' Found {} instead", pointer_val.to_string(self, &state, &modules));
self.runtime_error(msg.as_str(), &state, &modules);
return InterpretResult::InterpretRuntimeError;
}
}
// We return on an error, so we can clean up the stack now
state.pop(); // Instance
state.stack.push(val); // Return the value to the stack
}
// This is almost identical to OpGetProperty, but it goes one extra jump to get the method from the superclass, and binds it to itself
OpGetSuper(name_index) => {
let pointer_val = state.peek();
let superclass_val = state.peek_at(1);
if let Value::PhoenixClass(superclass) = superclass_val {
// Todo: Combine this and SetProperty into a macro so it doesn't hurt me everytime i have to read this
match state.deref_into(pointer_val, HeapObjType::PhoenixInstance) {
Ok(instance) => {
let instance = instance.as_instance();
let superclass_chunk =
&&modules[state.current_frame.module].classes[*superclass];
if superclass_chunk.methods.contains_key(&name_index) {
let bound_value = ObjBoundMethod {
method: *superclass_chunk.methods.get(&name_index).unwrap(),
pointer: pointer_val.as_pointer(),
};
// println!("Superclass get method found method {:?} ", bound_value);
// println!("Superclass methods {:?}", superclass_chunk.methods);
// println!("Superclass for {:?} is {:?}", instance, class_chunk.superclass);
state.pop(); // Remove the instance
state.stack.push(Value::PhoenixBoundMethod(bound_value));
// Replace with bound method
} else {
self.runtime_error(
format!(
"Undefined superclass method '{}' for {}",
VM::get_variable_name(name_index, &state, &modules),
&modules[state.current_frame.module]
.classes
.get(instance.class)
.unwrap()
.name,
)
.as_str(),
&state,
&modules,
);
return InterpretResult::InterpretRuntimeError;
}
}
Err(_) => {
panic!(
"VM panic! Failed to obtain instance PhoenixPointer for super"
);
}
}
} else {
panic!("VM panic! Failed to obtain superclass index for super, got {:?} instead", superclass_val);
}
}
OpGetUpvalue(index) => {
state.push_upvalue(index);
}
OpSetUpvalue(index) => {
state.set_upvalue(index);
}
OpClosure => {
if let Value::PhoenixFunction(function) = state.pop() {
let mut closure = ObjClosure::new(function); // Capture values into the closure here
let fn_chunk = &modules[state.current_frame.module]
.functions
.get(function)
.unwrap();
for upvalue in fn_chunk.upvalues.as_ref().unwrap().iter() {
closure.values.push(state.capture_upvalue(upvalue))
}
let ptr = state.alloc(HeapObj::new_closure(closure));
state.stack.push(ptr);
} else {
panic!("VM panic! Attempted to wrap a non-function value in a closure");
}
}
OpJump(offset) => state.jump(offset),
OpJumpIfFalse(offset) => {
if is_falsey(state.peek()) {
// Does not pop the value off the top of the stack because we need them for logical operators
state.jump(offset);
}
}
OpLoop(neg_offset) => state.jump_back(neg_offset),
OpCall(arity, module_index) => {
let callee = state.peek_at(arity);
// do we need to switch modules?
if let Value::PhoenixModule(module) = callee {
state.current_frame.module = *module;
// pop the module off the stack
state.pop();
}
let cur_module = state.current_frame.module;
state.module_stack.push(cur_module);
state.current_frame.module = module_index;
let result = state.call_value(
arity,
&modules[state.current_frame.module].functions,
&modules[state.current_frame.module].classes,
&modules[state.current_frame.module],
self,
&modules,
);
current_code = &modules[state.current_frame.module]
.functions
.get(state.current_frame.function)
.unwrap()
.chunk
.code[..]; // Update the current code
if let Some(msg) = result {
self.runtime_error(&msg[..], &state, &modules);
return InterpretResult::InterpretRuntimeError;
}
// state.current_frame.module = cur_module;
}
OpClass(index) => state.stack.push(Value::PhoenixClass(index)),
OpConstant(index) => state
.stack
.push(modules[state.current_frame.module].constants[index].clone()),
OpTrue => state.stack.push(Value::Bool(true)),
OpFalse => state.stack.push(Value::Bool(false)),
OpNil => state.stack.push(Value::Nil),
OpAdd => {
let t = (state.pop(), state.pop());
if let (Value::PhoenixPointer(a), Value::PhoenixPointer(b)) = t {
let ptr = state.alloc_string(format!(
"{}{}",
state.deref_string(b).value,
state.deref_string(a).value
));
state.stack.push(ptr)
} else if let (Value::Float(a), Value::Float(b)) = t {
state.stack.push(Value::Float(a + b))
} else if let (Value::Long(a), Value::Long(b)) = t {
state.stack.push(Value::Long(a + b))
} else {
self.runtime_error(
"Operands must be numbers or strings and must have the same type",
&state,
&modules,
);
return InterpretResult::InterpretRuntimeError;
}
}
OpDivide => op_binary!(Value::Float, Value::Long, /),
OpSubtract => op_binary!(Value::Float, Value::Long, -),
OpMultiply => op_binary!(Value::Float, Value::Long, *),
OpGreater => op_binary!(Value::Bool, >),
OpLess => op_binary!(Value::Bool, <),
OpEqual => {
let t = (&state.pop(), &state.pop());
state.stack.push(Value::Bool(values_equal(t)));
}
OpNot => {
let val = Value::Bool(is_falsey(&state.pop()));
state.stack.push(val);
}
OpNegate => {
let value = state.pop().as_float();
match value {
Some(x) => state.stack.push(Value::Float(x * -1.0)),
None => {
let value = state.pop().as_long();
match value {
Some(x) => state.stack.push(Value::Long(-x)),
None => {
self.runtime_error(
"Attempted to negate a non-number value",
&state,
&modules,
);
return InterpretResult::InterpretRuntimeError;
}
}
}
}
}
OpPrint => {
println!("{}", state.pop().to_string(self, &state, &modules));
}
OpGetIndex => {
let index = match state.pop() {
Value::Long(i) => i as usize,
Value::Float(i) => i as usize,
_ => {
self.runtime_error(
"Attempted to index a non-iterable value",
&state,
&modules,
);
return InterpretResult::InterpretRuntimeError;
}
};
let value = state.pop();
match value {
Value::PhoenixPointer(list_index) => {
// get the list from the allocated lists
let v = state.deref_mut(list_index);
let value = match v.obj {
HeapObjVal::PhoenixList(ref mut list) => {
if list.values.len() <= index {
self.runtime_error(
format!("Attempted to index a list with an out-of-bounds index (index: {}, length: {})", index, list.values.len()).as_str(),
&state,
&modules,
);
return InterpretResult::InterpretRuntimeError;
}
list.values[index].clone()
}
HeapObjVal::PhoenixString(ref s) => {
let val = match s.value.chars().nth(index) {
Some(c) => c,
None => {
self.runtime_error(
format!("Attempted to index a string with an out-of-bounds index (index: {}, length: {})", index, s.value.len()).as_str(),
&state,
&modules,
);
return InterpretResult::InterpretRuntimeError;
}
};
// todo: think about creating an extra type for strings that only have a short life time and put them on the stackk
let string_obj = ObjString::new(val.to_string());
state.alloc(HeapObj::new_string(string_obj))
}
_ => {
self.runtime_error(
"Attempted to index a non-indexable value",
&state,
&modules,
);
return InterpretResult::InterpretRuntimeError;
}
};
state.stack.push(value);
}
_ => {
self.runtime_error(
"Attempted to index a non-indexable value",
&state,
&modules,
);
return InterpretResult::InterpretRuntimeError;
}
}
}
OpSetIndex => {
// the new value
let value = state.pop();
// the index
let index = match state.pop() {
Value::Long(i) => i as usize,
Value::Float(i) => i as usize,
_ => {
self.runtime_error(
"Attempted to index a non-iterable value",
&state,
&modules,
);
return InterpretResult::InterpretRuntimeError;
}
};
// the target (list or string)
let target = state.pop();
match target {
Value::PhoenixPointer(heap_index) => {
// get the heapObject from the allocated lists
let v = state.deref(heap_index);
match &v.obj {
HeapObjVal::PhoenixList(_) => {
let o = state.deref_mut(heap_index);
let list = if let HeapObjVal::PhoenixList(list) = &mut o.obj {
list
} else {
unreachable!(
"We just checked that the heap object is a list"
)
};
if list.values.len() <= index {
self.runtime_error(
format!("Attempted to index a list with an out-of-bounds index (index: {}, length: {})", index, list.values.len()).as_str(),
&state,
&modules,
);
return InterpretResult::InterpretRuntimeError;
}
list.values[index] = value;
}
HeapObjVal::PhoenixString(_) => {
if let Value::PhoenixPointer(new_val) = value {
let new_val = state.deref_string(new_val).clone();
let o = state.deref_mut(heap_index);
let s = if let HeapObjVal::PhoenixString(s) = &mut o.obj {
s
} else {
unreachable!(
"We just checked that the heap object is a string"
)
};
if s.value.len() <= index {
self.runtime_error(
format!("Attempted to index a string with an out-of-bounds index (index: {}, length: {})", index, s.value.len()).as_str(),
&state,
&modules,
);
return InterpretResult::InterpretRuntimeError;
}
let mut new_string = String::new();
for (i, c) in s.value.chars().enumerate() {
if i == index {
new_string.push(match new_val.value.parse() {
Ok(v) => v,
Err(_) => {
self.runtime_error(
"Attempted to set a string index to a non-string value",
&state,
&modules,
);
return InterpretResult::InterpretRuntimeError;
}
});
} else {
new_string.push(c);
}
}
s.value = new_string;
} else {
self.runtime_error(
"Attempted to set a string index to a non-string value",
&state,
&modules,
);
return InterpretResult::InterpretRuntimeError;
}
}
_ => {
self.runtime_error(
"Attempted to index a non-indexable value",
&state,
&modules,
);
return InterpretResult::InterpretRuntimeError;
}
};
}
_ => {
self.runtime_error(
"Attempted to index a non-indexable value",
&state,
&modules,
);
return InterpretResult::InterpretRuntimeError;
}
}
// todo: find out if this is needed
// state.stack.push(target);
state.stack.push(Value::Nil);
}
OpCreateList(size) => {
let mut list = Vec::new();
for _ in 0..size {
list.push(state.pop());
}
list.reverse();
// allocate the list
let list_obj = ObjList::new(list);
let ptr = state.alloc(HeapObj::new_list(list_obj));
state.stack.push(ptr);
}
OpCreateString => {
let s = state.pop();
if let Value::PhoenixString(s) = s {
let ptr = state.alloc(HeapObj::new_string(ObjString::new(s)));
state.stack.push(ptr);
} else {
self.runtime_error(
"Attempted to create a string from a non-string value",
&state,
&modules,
);
return InterpretResult::InterpretRuntimeError;
}
}
OpCreateHashMap(n) => {
let mut map = HashMap::new();
for _ in 0..n {
let value = state.pop();
let key = state.pop();
map.insert(key, value);
}
let map_obj = ObjHashMap::new(map);
let ptr = state.alloc(HeapObj::new_hashmap(map_obj));
state.stack.push(ptr);
}
OpWait => {
let mut stdout = stdout();
// we know that the last value on the stack is the string we want to print
let s = state.pop().to_string(self, &state, &modules);
stdout.write(format!("{}", s).as_bytes()).unwrap();
stdout.flush().unwrap();
let mut buffer = String::new();
stdin()
.read_line(&mut buffer)
.expect("Failed to read line");
sleep(Duration::from_millis(100));
}
}
}
}
}
fn debug_state_trace(state: &VMState, _vm: &VM, modules: &[ModuleChunk]) {
eprintln!("> Frame: {:?}", state.current_frame);
eprintln!("> Stack: ");
eprint!(">>");
for value in state.stack.iter() {
eprint!(" [ {:?} ] ", value);
}
eprintln!();
eprintln!("> Frames: ");
eprint!(">>");
for value in state.frames.iter() {
eprint!(" [ {:?} ] ", value);
}
eprintln!();
eprintln!("> Globals: ");
for (index, val) in state.globals[state.current_frame.module].iter().enumerate() {
if let Global::Init(global) = val {
eprintln!(
">> {} => {:?}",
VM::get_variable_name(index, state, modules),
global
);
}
}
debug_instances(state);
}
fn debug_instances(state: &VMState) {
eprintln!("> Instances: ");
for (i, instance) in state.gc.instances.iter().enumerate() {
eprintln!(">> [{}] {:?}", i, instance)
}
}
fn debug_trace(vm: &VM, instr: &Instr, state: &VMState, modules: &[ModuleChunk]) {
eprintln!("---");
eprint!("> Next instr (#{}): ", state.current_frame.ip - 1);
disassemble_instruction(
instr,
state.current_frame.ip - 1,
&modules[state.current_frame.module].constants,
&modules[state.current_frame.module].identifiers,
);
debug_state_trace(state, vm, modules);
eprintln!("---\n");
}
pub fn debug_print_constants(modules: &[ModuleChunk]) {
eprintln!("---");
eprintln!("> Constants");
for m in modules.iter() {
eprintln!("--- [ module: {:?} ] ---", m.name);
for val in m.constants.iter() {
eprintln!("\t>> [ {:?} ]", val);
}
}
eprintln!("---\n");
// debug all m.identifiers
eprintln!("---");
eprintln!("> Identifiers");
for m in modules.iter() {
eprintln!("--- [ module: {:?} ] ---", m.name);
for (i, val) in m.identifiers.iter().enumerate() {
eprintln!("\t>> [ {} ] => {:?}", i, val);
}
}
eprintln!("---\n");
}