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 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037
// THREAD.rs
// by Lut99
//
// Created:
// 09 Sep 2022, 13:23:41
// Last edited:
// 23 Jul 2024, 01:31:41
// Auto updated?
// Yes
//
// Description:
//! Implements a single Thread of a VM, which sequentially executes a
//! given stream of Edges.
//
use std::any::type_name;
use std::collections::HashMap;
use std::path::PathBuf;
use std::sync::{Arc, RwLock};
use async_recursion::async_recursion;
use brane_ast::ast::{ClassDef, ComputeTaskDef, Edge, EdgeInstr, FunctionDef, TaskDef};
use brane_ast::func_id::FunctionId;
use brane_ast::locations::Location;
use brane_ast::spec::{BuiltinClasses, BuiltinFunctions};
use brane_ast::{DataType, MergeStrategy, Workflow};
use enum_debug::EnumDebug as _;
use futures::future::{BoxFuture, FutureExt};
use log::debug;
use specifications::data::{AccessKind, AvailabilityKind, DataName};
use specifications::profiling::{ProfileScopeHandle, ProfileScopeHandleOwned};
use tokio::spawn;
use tokio::task::JoinHandle;
use crate::dbg_node;
use crate::errors::ReturnEdge;
pub use crate::errors::VmError as Error;
use crate::frame_stack::FrameStack;
use crate::pc::ProgramCounter;
use crate::spec::{CustomGlobalState, CustomLocalState, RunState, TaskInfo, VmPlugin};
use crate::stack::Stack;
use crate::value::{FullValue, Value};
/***** TESTS *****/
#[cfg(test)]
mod tests {
use std::sync::Mutex;
use brane_ast::traversals::print::ast;
use brane_ast::{CompileResult, ParserOptions, compile_program};
use brane_shr::utilities::{create_data_index, create_package_index, test_on_dsl_files_async};
use specifications::data::DataIndex;
use specifications::package::PackageIndex;
use super::*;
use crate::dummy::{DummyPlanner, DummyPlugin, DummyState};
/// Tests the traversal by generating symbol tables for every file.
#[tokio::test]
async fn test_thread() {
// Setup the simple logger
#[cfg(feature = "test_logging")]
if let Err(err) = humanlog::HumanLogger::terminal(humanlog::DebugMode::Debug).init() {
eprintln!("WARNING: Failed to setup logger: {err} (no logging for this session)");
}
// Run the tests on all the files
test_on_dsl_files_async("BraneScript", |path, code| {
async move {
// Start by the name to always know which file this is
println!("{}", (0..80).map(|_| '-').collect::<String>());
println!("File '{}' gave us:", path.display());
// Load the package index
let pindex: PackageIndex = create_package_index();
let dindex: DataIndex = create_data_index();
// Compile it to a workflow
let workflow: Workflow = match compile_program(code.as_bytes(), &pindex, &dindex, &ParserOptions::bscript()) {
CompileResult::Workflow(wf, warns) => {
// Print warnings if any
for w in warns {
w.prettyprint(path.to_string_lossy(), &code);
}
wf
},
CompileResult::Eof(err) => {
// Print the error
err.prettyprint(path.to_string_lossy(), &code);
panic!("Failed to compile to workflow (see output above)");
},
CompileResult::Err(errs) => {
// Print the errors
for e in errs {
e.prettyprint(path.to_string_lossy(), &code);
}
panic!("Failed to compile to workflow (see output above)");
},
_ => {
unreachable!();
},
};
// Run the dummy planner on the workflow
let workflow: Arc<Workflow> = Arc::new(DummyPlanner::plan(&mut HashMap::new(), workflow));
// Now print the file for prettyness
ast::do_traversal(&workflow, std::io::stdout()).unwrap();
println!("{}", (0..40).map(|_| "- ").collect::<String>());
// Run the program
let text: Arc<Mutex<String>> = Arc::new(Mutex::new(String::new()));
let main: Thread<DummyState, ()> = Thread::new(&workflow, DummyState {
workflow: Some(workflow.clone()),
results: Arc::new(Mutex::new(HashMap::new())),
text: text.clone(),
});
match main.run::<DummyPlugin>(ProfileScopeHandleOwned::dummy()).await {
Ok(value) => {
println!("Workflow stdout:");
print!("{}", text.lock().unwrap());
println!();
println!("Workflow returned: {value:?}");
},
Err(err) => {
err.prettyprint();
panic!("Failed to execute workflow (see output above)");
},
}
println!("{}\n\n", (0..80).map(|_| '-').collect::<String>());
}
})
.await;
}
}
/***** HELPER ENUMS *****/
/// Defines the result of an Edge execution.
#[derive(Debug)]
enum EdgeResult {
/// The Edge completed the thread, returning a value. It also contains the timings it took to do the last instruction.
Ok(Value),
/// The Edge execution was a success but the workflow continues (to the given body and the given edge in that body, in fact). It also contains the timings it took to do the last instruction.
Pending(ProgramCounter),
/// The Edge execution was a disaster and something went wrong.
Err(Error),
}
/***** HELPER FUNCTIONS *****/
/// Preprocesses any datasets / intermediate results in the given value.
///
/// # Arguments
/// - `global`: The global VM plugin state to use when actually preprocessing a dataset.
/// - `local`: The local VM plugin state to use when actually preprocessing a dataset.
/// - `pc`: The current program counter index.
/// - `task`: The Task definition for which we are preprocessing.
/// - `at`: The location where we are preprocessing.
/// - `value`: The FullValue that might contain a to-be-processed dataset or intermediate result (or recurse into a value that does).
/// - `input`: The input map for the upcoming task so that we know where the value is planned to be.
/// - `data`: The map that we will populate with the access methods once available.
/// - `prof`: A ProfileScopeHandleOwned that is used to provide more details about the time it takes to preprocess a local argument. Note that this is _not_ user-relevant, only debug/framework-relevant.
///
/// # Returns
/// Adds any preprocessed datasets to `data`, then returns the ValuePreprocessProfile to discover how long it took us to do so.
///
/// # Errors
/// This function may error if the given `input` does not contain any of the data in the value _or_ if the referenced input is not yet planned.
#[async_recursion]
#[allow(clippy::too_many_arguments, clippy::multiple_bound_locations)]
async fn preprocess_value<'p: 'async_recursion, P: VmPlugin>(
global: &Arc<RwLock<P::GlobalState>>,
local: &P::LocalState,
pc: ProgramCounter,
task: &TaskDef,
at: &Location,
value: &FullValue,
input: &HashMap<DataName, Option<AvailabilityKind>>,
data: &mut HashMap<DataName, JoinHandle<Result<AccessKind, P::PreprocessError>>>,
prof: ProfileScopeHandle<'p>,
) -> Result<(), Error> {
// If it's a data or intermediate result, get it; skip it otherwise
let name: DataName = match value {
// The data and intermediate result, of course
FullValue::Data(name) => DataName::Data(name.into()),
FullValue::IntermediateResult(name) => DataName::IntermediateResult(name.into()),
// Also handle any nested stuff
FullValue::Array(values) => {
for (i, v) in values.iter().enumerate() {
prof.nest_fut(format!("[{i}]"), |scope| preprocess_value::<P>(global, local, pc, task, at, v, input, data, scope)).await?;
}
return Ok(());
},
FullValue::Instance(name, props) => {
for (n, v) in props {
prof.nest_fut(format!("{name}.{n}"), |scope| preprocess_value::<P>(global, local, pc, task, at, v, input, data, scope)).await?;
}
return Ok(());
},
// The rest is irrelevant
_ => {
return Ok(());
},
};
// Fetch it from the input
let avail: AvailabilityKind = match input.get(&name) {
Some(avail) => match avail {
Some(avail) => avail.clone(),
None => {
return Err(Error::UnplannedInput { pc, task: task.name().into(), name });
},
},
None => {
return Err(Error::UnknownInput { pc, task: task.name().into(), name });
},
};
// If it is unavailable, download it and make it available
let access: JoinHandle<Result<AccessKind, P::PreprocessError>> = match avail {
AvailabilityKind::Available { how } => {
debug!("{} '{}' is locally available", name.variant(), name.name());
tokio::spawn(async move { Ok(how) })
},
AvailabilityKind::Unavailable { how } => {
debug!("{} '{}' is remotely available", name.variant(), name.name());
// Call the external transfer function
// match P::preprocess(global, local, at, &name, how).await {
// Ok(access) => access,
// Err(err) => { return Err(Error::Custom{ pc, err: Box::new(err) }); }
// }
let prof = ProfileScopeHandleOwned::from(prof);
let global = global.clone();
let local = local.clone();
let at = at.clone();
let name = name.clone();
tokio::spawn(async move {
prof.nest_fut(format!("{}::preprocess()", type_name::<P>()), |scope| P::preprocess(global, local, pc, at, name, how, scope)).await
})
},
};
// Insert it into the map, done
data.insert(name, access);
Ok(())
}
/// Runs a single instruction, modifying the given stack and variable register.
///
/// # Arguments
/// - `pc`: The location of the edge we're executing (used for debugging purposes).
/// - `idx`: The index of the instruction we're executing (used for debugging purposes).
/// - `instr`: The EdgeInstr to execute.
/// - `stack`: The Stack that represents temporary state for executing.
/// - `fstack`: The FrameStack that we read/write variable from/to.
///
/// # Returns
/// The next index to execute. Note that this is _relative_ to the given instruction (so it will typically be 1)
///
/// # Errors
/// This function may error if execution of the instruction failed. This is typically due to incorrect runtime typing.
fn exec_instr(pc: ProgramCounter, idx: usize, instr: &EdgeInstr, stack: &mut Stack, fstack: &mut FrameStack) -> Result<i64, Error> {
use EdgeInstr::*;
let next: i64 = match instr {
Cast { res_type } => {
// Get the top value off the stack
let value: Value = match stack.pop() {
Some(value) => value,
None => return Err(Error::EmptyStackError { pc, instr: Some(idx), expected: DataType::Any }),
};
// Attempt to cast it based on the value it is
let value: Value = match value.cast(res_type, fstack.table()) {
Ok(value) => value,
Err(err) => {
return Err(Error::CastError { pc, instr: idx, err });
},
};
// Push the value back
stack.push(value).to_instr(pc, idx)?;
1
},
Pop {} => {
// Get the top value off the stack and discard it
if stack.pop().is_none() {
return Err(Error::EmptyStackError { pc, instr: Some(idx), expected: DataType::Any });
};
1
},
PopMarker {} => {
// Push a pop marker on top of the stack.
stack.push_pop_marker().to_instr(pc, idx)?;
1
},
DynamicPop {} => {
// Let the stack handle this one.
stack.dpop();
1
},
Branch { next } => {
// Examine the top value on the the stack
let value: Value = match stack.pop() {
Some(value) => value,
None => {
return Err(Error::EmptyStackError { pc, instr: Some(idx), expected: DataType::Boolean });
},
};
// Examine it as a boolean
let value_type: DataType = value.data_type(fstack.table());
let value: bool = match value.try_as_bool() {
Some(value) => value,
None => {
return Err(Error::StackTypeError { pc, instr: Some(idx), got: value_type, expected: DataType::Boolean });
},
};
// Branch only if true
if value { *next } else { 1 }
},
BranchNot { next } => {
// Examine the top value on the the stack
let value: Value = match stack.pop() {
Some(value) => value,
None => {
return Err(Error::EmptyStackError { pc, instr: Some(idx), expected: DataType::Boolean });
},
};
// Examine it as a boolean
let value_type: DataType = value.data_type(fstack.table());
let value: bool = match value.try_as_bool() {
Some(value) => value,
None => {
return Err(Error::StackTypeError { pc, instr: Some(idx), got: value_type, expected: DataType::Boolean });
},
};
// Branch only if **false**
if !value { *next } else { 1 }
},
Not {} => {
// Get the top value off the stack
let value: Value = match stack.pop() {
Some(value) => value,
None => return Err(Error::EmptyStackError { pc, instr: Some(idx), expected: DataType::Numeric }),
};
// Get it as a boolean
let value_type: DataType = value.data_type(fstack.table());
let value: bool = match value.try_as_bool() {
Some(value) => value,
None => {
return Err(Error::StackTypeError { pc, instr: Some(idx), got: value_type, expected: DataType::Boolean });
},
};
// Push the negated value back
stack.push(Value::Boolean { value: !value }).to_instr(pc, idx)?;
1
},
Neg {} => {
// Get the top value off the stack
let value: Value = match stack.pop() {
Some(value) => value,
None => return Err(Error::EmptyStackError { pc, instr: Some(idx), expected: DataType::Numeric }),
};
// Get it as an integer or real value
match value {
Value::Integer { value } => {
// Put the negated value back
stack.push(Value::Integer { value: -value }).to_instr(pc, idx)?;
},
Value::Real { value } => {
// Put the negated value back
stack.push(Value::Real { value: -value }).to_instr(pc, idx)?;
},
// Yeah no not that one
value => {
return Err(Error::StackTypeError { pc, instr: Some(idx), got: value.data_type(fstack.table()), expected: DataType::Numeric });
},
};
1
},
And {} => {
// Pop the lhs and rhs off the stack (reverse order)
let rhs: Value = match stack.pop() {
Some(value) => value,
None => return Err(Error::EmptyStackError { pc, instr: Some(idx), expected: DataType::Boolean }),
};
let lhs: Value = match stack.pop() {
Some(value) => value,
None => return Err(Error::EmptyStackError { pc, instr: Some(idx), expected: DataType::Boolean }),
};
// Get them both as boolean values
let (lhs_type, rhs_type): (DataType, DataType) = (lhs.data_type(fstack.table()), rhs.data_type(fstack.table()));
let (lhs, rhs): (bool, bool) = match (lhs.try_as_bool(), rhs.try_as_bool()) {
(Some(lhs), Some(rhs)) => (lhs, rhs),
(_, _) => {
return Err(Error::StackLhsRhsTypeError { pc, instr: idx, got: (lhs_type, rhs_type), expected: DataType::Boolean });
},
};
// Push the conjunction of the two on top again
stack.push(Value::Boolean { value: lhs && rhs }).to_instr(pc, idx)?;
1
},
Or {} => {
// Pop the lhs and rhs off the stack (reverse order)
let rhs: Value = match stack.pop() {
Some(value) => value,
None => return Err(Error::EmptyStackError { pc, instr: Some(idx), expected: DataType::Boolean }),
};
let lhs: Value = match stack.pop() {
Some(value) => value,
None => return Err(Error::EmptyStackError { pc, instr: Some(idx), expected: DataType::Boolean }),
};
// Get them both as boolean values
let (lhs_type, rhs_type): (DataType, DataType) = (lhs.data_type(fstack.table()), rhs.data_type(fstack.table()));
let (lhs, rhs): (bool, bool) = match (lhs.try_as_bool(), rhs.try_as_bool()) {
(Some(lhs), Some(rhs)) => (lhs, rhs),
(_, _) => {
return Err(Error::StackLhsRhsTypeError { pc, instr: idx, got: (lhs_type, rhs_type), expected: DataType::Boolean });
},
};
// Push the disjunction of the two on top again
stack.push(Value::Boolean { value: lhs || rhs }).to_instr(pc, idx)?;
1
},
Add {} => {
// Pop the lhs and rhs off the stack (reverse order)
let rhs: Value = match stack.pop() {
Some(value) => value,
None => return Err(Error::EmptyStackError { pc, instr: Some(idx), expected: DataType::Addable }),
};
let lhs: Value = match stack.pop() {
Some(value) => value,
None => return Err(Error::EmptyStackError { pc, instr: Some(idx), expected: DataType::Addable }),
};
// Get them both as either numeric _or_ string values
match (lhs, rhs) {
(Value::Integer { value: lhs }, Value::Integer { value: rhs }) => {
// Put the added value back
stack.push(Value::Integer { value: lhs + rhs }).to_instr(pc, idx)?;
},
(Value::Real { value: lhs }, Value::Real { value: rhs }) => {
// Put the added value back
stack.push(Value::Real { value: lhs + rhs }).to_instr(pc, idx)?;
},
(Value::String { value: mut lhs }, Value::String { value: rhs }) => {
// Put the concatenated value back
lhs.push_str(&rhs);
stack.push(Value::String { value: lhs }).to_instr(pc, idx)?;
},
// Yeah no not that one
(lhs, rhs) => {
return Err(Error::StackLhsRhsTypeError {
pc,
instr: idx,
got: (lhs.data_type(fstack.table()), rhs.data_type(fstack.table())),
expected: DataType::Addable,
});
},
};
1
},
Sub {} => {
// Pop the lhs and rhs off the stack (reverse order)
let rhs: Value = match stack.pop() {
Some(value) => value,
None => return Err(Error::EmptyStackError { pc, instr: Some(idx), expected: DataType::Numeric }),
};
let lhs: Value = match stack.pop() {
Some(value) => value,
None => return Err(Error::EmptyStackError { pc, instr: Some(idx), expected: DataType::Numeric }),
};
// Get them both as either numeric _or_ string values
match (lhs, rhs) {
(Value::Integer { value: lhs }, Value::Integer { value: rhs }) => {
// Put the subtracted value back
stack.push(Value::Integer { value: lhs - rhs }).to_instr(pc, idx)?;
},
(Value::Real { value: lhs }, Value::Real { value: rhs }) => {
// Put the subtracted value back
stack.push(Value::Real { value: lhs - rhs }).to_instr(pc, idx)?;
},
// Yeah no not that one
(lhs, rhs) => {
return Err(Error::StackLhsRhsTypeError {
pc,
instr: idx,
got: (lhs.data_type(fstack.table()), rhs.data_type(fstack.table())),
expected: DataType::Numeric,
});
},
};
1
},
Mul {} => {
// Pop the lhs and rhs off the stack (reverse order)
let rhs: Value = match stack.pop() {
Some(value) => value,
None => return Err(Error::EmptyStackError { pc, instr: Some(idx), expected: DataType::Numeric }),
};
let lhs: Value = match stack.pop() {
Some(value) => value,
None => return Err(Error::EmptyStackError { pc, instr: Some(idx), expected: DataType::Numeric }),
};
// Get them both as either numeric _or_ string values
match (lhs, rhs) {
(Value::Integer { value: lhs }, Value::Integer { value: rhs }) => {
// Put the multiplied value back
stack.push(Value::Integer { value: lhs * rhs }).to_instr(pc, idx)?;
},
(Value::Real { value: lhs }, Value::Real { value: rhs }) => {
// Put the multiplied value back
stack.push(Value::Real { value: lhs * rhs }).to_instr(pc, idx)?;
},
// Yeah no not that one
(lhs, rhs) => {
return Err(Error::StackLhsRhsTypeError {
pc,
instr: idx,
got: (lhs.data_type(fstack.table()), rhs.data_type(fstack.table())),
expected: DataType::Numeric,
});
},
};
1
},
Div {} => {
// Pop the lhs and rhs off the stack (reverse order)
let rhs: Value = match stack.pop() {
Some(value) => value,
None => return Err(Error::EmptyStackError { pc, instr: Some(idx), expected: DataType::Numeric }),
};
let lhs: Value = match stack.pop() {
Some(value) => value,
None => return Err(Error::EmptyStackError { pc, instr: Some(idx), expected: DataType::Numeric }),
};
// Get them both as either numeric _or_ string values
match (lhs, rhs) {
(Value::Integer { value: lhs }, Value::Integer { value: rhs }) => {
// Put the divided value back
stack.push(Value::Integer { value: lhs / rhs }).to_instr(pc, idx)?;
},
(Value::Real { value: lhs }, Value::Real { value: rhs }) => {
// Put the divided value back
stack.push(Value::Real { value: lhs / rhs }).to_instr(pc, idx)?;
},
// Yeah no not that one
(lhs, rhs) => {
return Err(Error::StackLhsRhsTypeError {
pc,
instr: idx,
got: (lhs.data_type(fstack.table()), rhs.data_type(fstack.table())),
expected: DataType::Numeric,
});
},
};
1
},
Mod {} => {
// Pop the lhs and rhs off the stack (reverse order)
let rhs: Value = match stack.pop() {
Some(value) => value,
None => return Err(Error::EmptyStackError { pc, instr: Some(idx), expected: DataType::Integer }),
};
let lhs: Value = match stack.pop() {
Some(value) => value,
None => return Err(Error::EmptyStackError { pc, instr: Some(idx), expected: DataType::Integer }),
};
// Get them both as integer values
let (lhs_type, rhs_type): (DataType, DataType) = (lhs.data_type(fstack.table()), rhs.data_type(fstack.table()));
let (lhs, rhs): (i64, i64) = match (lhs.try_as_int(), rhs.try_as_int()) {
(Some(lhs), Some(rhs)) => (lhs, rhs),
(_, _) => {
return Err(Error::StackLhsRhsTypeError { pc, instr: idx, got: (lhs_type, rhs_type), expected: DataType::Integer });
},
};
// Push the modulo of the two on top again
stack.push(Value::Integer { value: lhs % rhs }).to_instr(pc, idx)?;
1
},
Eq {} => {
// Pop the lhs and rhs off the stack (reverse order)
let rhs: Value = match stack.pop() {
Some(value) => value,
None => return Err(Error::EmptyStackError { pc, instr: Some(idx), expected: DataType::Numeric }),
};
let lhs: Value = match stack.pop() {
Some(value) => value,
None => return Err(Error::EmptyStackError { pc, instr: Some(idx), expected: DataType::Numeric }),
};
// Simply push if they are the same
stack.push(Value::Boolean { value: lhs == rhs }).to_instr(pc, idx)?;
1
},
Ne {} => {
// Pop the lhs and rhs off the stack (reverse order)
let rhs: Value = match stack.pop() {
Some(value) => value,
None => return Err(Error::EmptyStackError { pc, instr: Some(idx), expected: DataType::Numeric }),
};
let lhs: Value = match stack.pop() {
Some(value) => value,
None => return Err(Error::EmptyStackError { pc, instr: Some(idx), expected: DataType::Numeric }),
};
// Simply push if they are not the same
stack.push(Value::Boolean { value: lhs != rhs }).to_instr(pc, idx)?;
1
},
Lt {} => {
// Pop the lhs and rhs off the stack (reverse order)
let rhs: Value = match stack.pop() {
Some(value) => value,
None => return Err(Error::EmptyStackError { pc, instr: Some(idx), expected: DataType::Numeric }),
};
let lhs: Value = match stack.pop() {
Some(value) => value,
None => return Err(Error::EmptyStackError { pc, instr: Some(idx), expected: DataType::Numeric }),
};
// Get them both as numeric values
match (lhs, rhs) {
(Value::Integer { value: lhs }, Value::Integer { value: rhs }) => {
// Put the subtracted value back
stack.push(Value::Boolean { value: lhs < rhs }).to_instr(pc, idx)?;
},
(Value::Real { value: lhs }, Value::Real { value: rhs }) => {
// Put the subtracted value back
stack.push(Value::Boolean { value: lhs < rhs }).to_instr(pc, idx)?;
},
// Yeah no not that one
(lhs, rhs) => {
return Err(Error::StackLhsRhsTypeError {
pc,
instr: idx,
got: (lhs.data_type(fstack.table()), rhs.data_type(fstack.table())),
expected: DataType::Numeric,
});
},
};
1
},
Le {} => {
// Pop the lhs and rhs off the stack (reverse order)
let rhs: Value = match stack.pop() {
Some(value) => value,
None => return Err(Error::EmptyStackError { pc, instr: Some(idx), expected: DataType::Numeric }),
};
let lhs: Value = match stack.pop() {
Some(value) => value,
None => return Err(Error::EmptyStackError { pc, instr: Some(idx), expected: DataType::Numeric }),
};
// Get them both as numeric values
match (lhs, rhs) {
(Value::Integer { value: lhs }, Value::Integer { value: rhs }) => {
// Put the subtracted value back
stack.push(Value::Boolean { value: lhs <= rhs }).to_instr(pc, idx)?;
},
(Value::Real { value: lhs }, Value::Real { value: rhs }) => {
// Put the subtracted value back
stack.push(Value::Boolean { value: lhs <= rhs }).to_instr(pc, idx)?;
},
// Yeah no not that one
(lhs, rhs) => {
return Err(Error::StackLhsRhsTypeError {
pc,
instr: idx,
got: (lhs.data_type(fstack.table()), rhs.data_type(fstack.table())),
expected: DataType::Numeric,
});
},
};
1
},
Gt {} => {
// Pop the lhs and rhs off the stack (reverse order)
let rhs: Value = match stack.pop() {
Some(value) => value,
None => return Err(Error::EmptyStackError { pc, instr: Some(idx), expected: DataType::Numeric }),
};
let lhs: Value = match stack.pop() {
Some(value) => value,
None => return Err(Error::EmptyStackError { pc, instr: Some(idx), expected: DataType::Numeric }),
};
// Get them both as numeric values
match (lhs, rhs) {
(Value::Integer { value: lhs }, Value::Integer { value: rhs }) => {
// Put the subtracted value back
stack.push(Value::Boolean { value: lhs > rhs }).to_instr(pc, idx)?;
},
(Value::Real { value: lhs }, Value::Real { value: rhs }) => {
// Put the subtracted value back
stack.push(Value::Boolean { value: lhs > rhs }).to_instr(pc, idx)?;
},
// Yeah no not that one
(lhs, rhs) => {
return Err(Error::StackLhsRhsTypeError {
pc,
instr: idx,
got: (lhs.data_type(fstack.table()), rhs.data_type(fstack.table())),
expected: DataType::Numeric,
});
},
};
1
},
Ge {} => {
// Pop the lhs and rhs off the stack (reverse order)
let rhs: Value = match stack.pop() {
Some(value) => value,
None => return Err(Error::EmptyStackError { pc, instr: Some(idx), expected: DataType::Numeric }),
};
let lhs: Value = match stack.pop() {
Some(value) => value,
None => return Err(Error::EmptyStackError { pc, instr: Some(idx), expected: DataType::Numeric }),
};
// Get them both as numeric values
match (lhs, rhs) {
(Value::Integer { value: lhs }, Value::Integer { value: rhs }) => {
// Put the subtracted value back
stack.push(Value::Boolean { value: lhs >= rhs }).to_instr(pc, idx)?;
},
(Value::Real { value: lhs }, Value::Real { value: rhs }) => {
// Put the subtracted value back
stack.push(Value::Boolean { value: lhs >= rhs }).to_instr(pc, idx)?;
},
// Yeah no not that one
(lhs, rhs) => {
return Err(Error::StackLhsRhsTypeError {
pc,
instr: idx,
got: (lhs.data_type(fstack.table()), rhs.data_type(fstack.table())),
expected: DataType::Numeric,
});
},
};
1
},
Array { length, res_type } => {
let mut res_type: DataType = res_type.clone();
// Pop enough values off the stack
let mut elems: Vec<Value> = Vec::with_capacity(*length);
for _ in 0..*length {
// Pop the value
let value: Value = match stack.pop() {
Some(value) => value,
None => {
return Err(Error::EmptyStackError { pc, instr: Some(idx), expected: res_type });
},
};
// Update the res_type if necessary; otherwise, make sure this is of the correct type
if let DataType::Any = &res_type {
res_type = value.data_type(fstack.table());
} else if res_type != value.data_type(fstack.table()) {
return Err(Error::ArrayTypeError { pc, instr: idx, got: value.data_type(fstack.table()), expected: res_type });
}
// Add the element
elems.push(value);
}
// Remember, stack pushes are in reversed direction
elems.reverse();
// Create the array and push it back
stack.push(Value::Array { values: elems }).to_instr(pc, idx)?;
1
},
ArrayIndex { res_type } => {
// Pop the index
let index: Value = match stack.pop() {
Some(index) => index,
None => {
return Err(Error::EmptyStackError { pc, instr: Some(idx), expected: DataType::Integer });
},
};
// as an integer
let index_type: DataType = index.data_type(fstack.table());
let index: i64 = match index.try_as_int() {
Some(index) => index,
None => {
return Err(Error::StackTypeError { pc, instr: Some(idx), got: index_type, expected: DataType::Integer });
},
};
// Get the array itself
let arr: Value = match stack.pop() {
Some(arr) => arr,
None => {
return Err(Error::EmptyStackError { pc, instr: Some(idx), expected: DataType::Array { elem_type: Box::new(res_type.clone()) } });
},
};
// as an array of values but indexed correctly
let arr_type: DataType = arr.data_type(fstack.table());
let mut arr: Vec<Value> = match arr.try_as_array() {
Some(arr) => arr,
None => {
return Err(Error::StackTypeError {
pc,
instr: Some(idx),
got: arr_type,
expected: DataType::Array { elem_type: Box::new(res_type.clone()) },
});
},
};
// Now index the array and push that element back
if index < 0 || index as usize >= arr.len() {
return Err(Error::ArrIdxOutOfBoundsError { pc, instr: idx, got: index, max: arr.len() });
}
// Finally, push that element back and return
stack.push(arr.swap_remove(index as usize)).to_instr(pc, idx)?;
1
},
Instance { def } => {
let class: &ClassDef = fstack.table().class(*def);
// Pop as many elements as are required (wow)
let mut fields: Vec<Value> = Vec::with_capacity(class.props.len());
for i in 0..class.props.len() {
// Pop the value
let value: Value = match stack.pop() {
Some(value) => value,
None => {
return Err(Error::EmptyStackError {
pc,
instr: Some(idx),
expected: class.props[class.props.len() - 1 - i].data_type.clone(),
});
},
};
// Make sure this is of the correct type
if !value.data_type(fstack.table()).allowed_by(&class.props[class.props.len() - 1 - i].data_type) {
return Err(Error::InstanceTypeError {
pc,
instr: idx,
got: value.data_type(fstack.table()),
class: class.name.clone(),
field: class.props[class.props.len() - 1 - i].name.clone(),
expected: class.props[class.props.len() - 1 - i].data_type.clone(),
});
}
// Add the element
fields.push(value);
}
fields.reverse();
// Map them with the class names (alphabetically)
let mut field_names: Vec<std::string::String> = class.props.iter().map(|v| v.name.clone()).collect();
field_names.sort_by_key(|n| n.to_lowercase());
let mut values: HashMap<std::string::String, Value> = field_names.into_iter().zip(fields).collect();
// Push an instance with those values - unless it's a specific builtin
if class.name == BuiltinClasses::Data.name() {
stack.push(Value::Data { name: values.remove("name").unwrap().try_as_string().unwrap() }).to_instr(pc, idx)?;
} else if class.name == BuiltinClasses::IntermediateResult.name() {
stack.push(Value::IntermediateResult { name: values.remove("name").unwrap().try_as_string().unwrap() }).to_instr(pc, idx)?;
} else {
stack.push(Value::Instance { values, def: *def }).to_instr(pc, idx)?;
}
1
},
Proj { field } => {
// Pop the instance value
let value: Value = match stack.pop() {
Some(value) => value,
None => {
return Err(Error::EmptyStackError { pc, instr: Some(idx), expected: DataType::Class { name: format!("withField={field}") } });
},
};
// as an instance
let value_type: DataType = value.data_type(fstack.table());
let (mut values, def): (HashMap<std::string::String, Value>, usize) = match value.try_as_instance() {
Some(value) => value,
None => {
return Err(Error::StackTypeError {
pc,
instr: Some(idx),
got: value_type,
expected: DataType::Class { name: format!("withField={field}") },
});
},
};
// Attempt to find the value with the correct field
let value: Value = match values.remove(field) {
Some(value) => value,
None => {
// Try as function instead
let mut res: Option<Value> = None;
for m in &fstack.table().class(def).methods {
if &fstack.table().func(FunctionId::Func(*m)).name == field {
res = Some(Value::Method { values, cdef: def, fdef: *m });
break;
}
}
match res {
Some(res) => res,
None => {
return Err(Error::ProjUnknownFieldError {
pc,
instr: idx,
class: fstack.table().class(def).name.clone(),
field: field.clone(),
});
},
}
},
};
// Push it
stack.push(value).to_instr(pc, idx)?;
1
},
VarDec { def } => {
// Simply declare it
if let Err(err) = fstack.declare(*def) {
return Err(Error::VarDecError { pc, instr: idx, err });
}
1
},
VarUndec { def } => {
// Simply undeclare it
if let Err(err) = fstack.undeclare(*def) {
return Err(Error::VarUndecError { pc, instr: idx, err });
}
1
},
VarGet { def } => {
// Attempt to get the value from the variable register
let value: Value = match fstack.get(*def) {
Ok(value) => value.clone(),
Err(err) => {
return Err(Error::VarGetError { pc, instr: idx, err });
},
};
// Push it
stack.push(value).to_instr(pc, idx)?;
1
},
VarSet { def } => {
// Pop the top value off the stack
let value: Value = match stack.pop() {
Some(value) => value,
None => {
return Err(Error::EmptyStackError { pc, instr: Some(idx), expected: fstack.table().var(*def).data_type.clone() });
},
};
// Set it in the register, done
if let Err(err) = fstack.set(*def, value) {
return Err(Error::VarSetError { pc, instr: idx, err });
};
1
},
Boolean { value } => {
// Push a boolean with the given value
stack.push(Value::Boolean { value: *value }).to_instr(pc, idx)?;
1
},
Integer { value } => {
// Push an integer with the given value
stack.push(Value::Integer { value: *value }).to_instr(pc, idx)?;
1
},
Real { value } => {
// Push a real with the given value
stack.push(Value::Real { value: *value }).to_instr(pc, idx)?;
1
},
String { value } => {
// Push a string with the given value
stack.push(Value::String { value: value.clone() }).to_instr(pc, idx)?;
1
},
Function { def } => {
// Push a function with the given definition
stack.push(Value::Function { def: *def }).to_instr(pc, idx)?;
1
},
};
// Done
Ok(next)
}
/***** LIBRARY *****/
/// Represents a single thread that may be executed.
pub struct Thread<G: CustomGlobalState, L: CustomLocalState> {
/// The graph containing the main edges to execute (indexed by `usize::MAX`).
graph: Arc<Vec<Edge>>,
/// The list of function edges to execute.
funcs: Arc<HashMap<usize, Vec<Edge>>>,
/// The 'program counter' of this thread. It first indexed the correct body (`usize::MAX` for main, or else the index of the function), and then the offset within that body.
pc: ProgramCounter,
/// The stack which we use for temporary values.
stack: Stack,
/// The frame stack is used to process function calls.
fstack: FrameStack,
/// The threads that we're blocking on.
threads: Vec<(usize, JoinHandle<Result<Value, Error>>)>,
/// The thread-global custom part of the RunState.
global: Arc<RwLock<G>>,
/// The thread-local custom part of the RunState.
local: L,
}
impl<G: CustomGlobalState, L: CustomLocalState> Thread<G, L> {
/// Spawns a new main thread from the given workflow.
///
/// # Arguments
/// - `workflow`: The Workflow that this thread will execute.
/// - `pindex`: The PackageIndex we use to resolve packages.
/// - `dindex`: The DataIndex we use to resolve datasets.
/// - `global`: The app-wide custom state with which to initialize this thread.
///
/// # Returns
/// A new Thread that may be executed.
#[inline]
pub fn new(workflow: &Workflow, global: G) -> Self {
let global: Arc<RwLock<G>> = Arc::new(RwLock::new(global));
Self {
graph: workflow.graph.clone(),
funcs: workflow.funcs.clone(),
pc: ProgramCounter::start(),
stack: Stack::new(2048),
fstack: FrameStack::new(512, workflow.table.clone()),
threads: vec![],
global: global.clone(),
local: L::new(&global),
}
}
/// Spawns a new main thread that does not start from scratch but instead the given VmState.
///
/// # Arguments
/// - `workflow`: The workflow to execute.
/// - `state`: The runstate to "resume" this thread with.
#[inline]
pub fn from_state(workflow: &Workflow, state: RunState<G>) -> Self {
Self {
graph: workflow.graph.clone(),
funcs: workflow.funcs.clone(),
pc: ProgramCounter::start(),
stack: Stack::new(2048),
fstack: state.fstack,
threads: vec![],
global: state.global.clone(),
local: L::new(&state.global),
}
}
/// 'Forks' this thread such that it may branch in a parallel statement.
///
/// # Arguments
/// - `offset`: The offset (as a `(body, idx)` pair) where the thread will begin computation in the edges list.
///
/// # Returns
/// A new Thread that is partly cloned of this one.
#[inline]
pub fn fork(&self, offset: ProgramCounter) -> Self {
Self {
graph: self.graph.clone(),
funcs: self.funcs.clone(),
pc: offset,
stack: Stack::new(2048),
fstack: self.fstack.fork(),
threads: vec![],
global: self.global.clone(),
local: L::new(&self.global),
}
}
/// Saves the important bits of this Thread for a next execution round.
#[inline]
fn into_state(self) -> RunState<G> {
RunState {
fstack: self.fstack,
global: self.global,
}
}
/// Retrieves the current edge based on the given program counter.
///
/// # Arguments
/// - `pc`: Points to the edge to retrieve.
///
/// # Returns
/// A reference to the Edge to execute.
///
/// # Errors
/// This function may error if the program counter is out-of-bounds.
fn get_edge(&self, pc: ProgramCounter) -> Result<&Edge, Error> {
if pc.func_id.is_main() {
// Assert the index is within range
if pc.edge_idx < self.graph.len() {
Ok(&self.graph[pc.edge_idx])
} else {
Err(Error::PcOutOfBounds { func: pc.func_id, edges: self.graph.len(), got: pc.edge_idx })
}
} else {
// Assert the function is within range
if let Some(edges) = self.funcs.get(&pc.func_id.id()) {
// Assert the index is within range
if pc.edge_idx < edges.len() {
Ok(&edges[pc.edge_idx])
} else {
Err(Error::PcOutOfBounds { func: pc.func_id, edges: edges.len(), got: pc.edge_idx })
}
} else {
Err(Error::UnknownFunction { func: pc.func_id })
}
}
}
/// Executes a single edge, modifying the given stacks and variable register.
///
/// # Arguments
/// - `pc`: Points to the current edge to execute (as a [`ProgramCounter``]).
/// - `plugins`: An object implementing various parts of task execution that are dependent on the actual setup (i.e., offline VS instance).
/// - `prof`: A ProfileScopeHandleOwned that is used to provide more details about the execution times of a single edge. Note that this is _not_ user-relevant, only debug/framework-relevant.
///
/// # Returns
/// The next index to execute. Note that this is an _absolute_ index (so it will typically be `idx` + 1)
///
/// # Errors
/// This function may error if execution of the edge failed. This is typically due to incorrect runtime typing or due to failure to perform an external function call.
async fn exec_edge<P: VmPlugin<GlobalState = G, LocalState = L>>(&mut self, pc: ProgramCounter, prof: ProfileScopeHandleOwned) -> EdgeResult {
// We can early stop if the program counter is out-of-bounds
if pc.func_id.is_main() {
if pc.edge_idx >= self.graph.len() {
debug!("Nothing to do (main, PC {} >= #edges {})", pc.edge_idx, self.graph.len());
// We didn't really execute anything, so no timing taken
return EdgeResult::Ok(Value::Void);
}
} else {
let f: &[Edge] = self.funcs.get(&pc.func_id.id()).unwrap_or_else(|| panic!("Failed to find function with index '{}'", pc.func_id.id()));
if pc.edge_idx >= f.len() {
debug!("Nothing to do ({}, PC {} >= #edges {})", pc.func_id.id(), pc.edge_idx, f.len());
// We didn't really execute anything, so no timing taken
return EdgeResult::Ok(Value::Void);
}
}
// Get the edge based on the index
let edge: &Edge = if pc.func_id.is_main() {
&self.graph[pc.edge_idx]
} else {
&self.funcs.get(&pc.func_id.id()).unwrap_or_else(|| panic!("Failed to find function with index '{}'", pc.func_id.id()))[pc.edge_idx]
};
dbg_node!("{pc}) Executing Edge: {edge:?}");
// Match on the specific edge
use Edge::*;
let next: ProgramCounter = match edge {
Node { task: task_id, at, input, result, next, .. } => {
// Resolve the task
let task: &TaskDef = self.fstack.table().task(*task_id);
// Match the thing to do
match task {
TaskDef::Compute(ComputeTaskDef { package, version, function, args_names, requirements }) => {
debug!("Calling compute task '{}' ('{}' v{})", task.name(), package, version);
// Collect the arguments from the stack (remember, reverse order)
let retr = prof.time("Argument retrieval");
let mut args: HashMap<String, FullValue> = HashMap::with_capacity(function.args.len());
for i in 0..function.args.len() {
let i: usize = function.args.len() - 1 - i;
// Get the element
let value: Value = match self.stack.pop() {
Some(value) => value,
None => {
return EdgeResult::Err(Error::EmptyStackError { pc, instr: None, expected: function.args[i].clone() });
},
};
// Check it has the correct type
let value_type: DataType = value.data_type(self.fstack.table());
if !value_type.allowed_by(&function.args[i]) {
return EdgeResult::Err(Error::FunctionTypeError {
pc,
name: task.name().into(),
arg: i,
got: value_type,
expected: function.args[i].clone(),
});
}
// Add it to the list
args.insert(args_names[i].clone(), value.into_full(self.fstack.table()));
}
// Unwrap the location
let at: &Location = match at {
Some(at) => at,
None => {
return EdgeResult::Err(Error::UnresolvedLocation { pc, name: function.name.clone() });
},
};
retr.stop();
// Next, fetch all the datasets required by calling the external transfer function;
// The map created maps data names to ways of accessing them locally that may be passed to the container itself.
let prepr = prof.nest("argument preprocessing");
let total = prepr.time("Total");
let mut handles: HashMap<DataName, JoinHandle<Result<AccessKind, P::PreprocessError>>> = HashMap::new();
for (i, value) in args.values().enumerate() {
// Preprocess the given value
if let Err(err) = prepr
.nest_fut(format!("argument {i}"), |scope| {
preprocess_value::<P>(&self.global, &self.local, pc, task, at, value, input, &mut handles, scope)
})
.await
{
return EdgeResult::Err(err);
}
}
// Join the handles
let mut data: HashMap<DataName, AccessKind> = HashMap::with_capacity(handles.len());
for (name, handle) in handles {
match handle.await {
Ok(res) => match res {
Ok(access) => {
data.insert(name, access);
},
Err(err) => {
return EdgeResult::Err(Error::Custom { pc, err: Box::new(err) });
},
},
Err(err) => {
return EdgeResult::Err(Error::Custom { pc, err: Box::new(err) });
},
}
}
total.stop();
prepr.finish();
// Prepare the TaskInfo for the call
let info: TaskInfo = TaskInfo {
pc,
def: *task_id,
name: &function.name,
package_name: package,
package_version: version,
requirements,
args,
location: at,
input: data,
result,
};
// Call the external call function with the correct arguments
let mut res: Option<Value> = match prof
.nest_fut(format!("{}::execute()", type_name::<P>()), |scope| P::execute(&self.global, &self.local, info, scope))
.await
{
Ok(res) => res.map(|v| v.into_value(self.fstack.table())),
Err(err) => {
return EdgeResult::Err(Error::Custom { pc, err: Box::new(err) });
},
};
// If the function returns an intermediate result but returned nothing, that's fine; we inject the result here
if function.ret == DataType::IntermediateResult && (res.is_none() || res.as_ref().unwrap() == &Value::Void) {
// Make the intermediate result available for next steps by possible pushing it to the next registry
let name: &str = result.as_ref().unwrap();
let path: PathBuf = name.into();
if let Err(err) = prof
.nest_fut(format!("{}::publicize()", type_name::<P>()), |scope| {
P::publicize(&self.global, &self.local, at, name, &path, scope)
})
.await
{
return EdgeResult::Err(Error::Custom { pc, err: Box::new(err) });
}
// Return the new, intermediate result
res = Some(Value::IntermediateResult { name: name.into() });
}
// Verify its return value
let _ret = prof.time("Return analysis");
if let Some(res) = res {
// Verification
let res_type: DataType = res.data_type(self.fstack.table());
if res_type != function.ret {
return EdgeResult::Err(Error::ReturnTypeError { pc, got: res_type, expected: function.ret.clone() });
}
// If we have it anyway, might as well push it onto the stack
if let Err(err) = self.stack.push(res) {
return EdgeResult::Err(Error::StackError { pc, instr: None, err });
}
} else if function.ret != DataType::Void {
return EdgeResult::Err(Error::ReturnTypeError { pc, got: DataType::Void, expected: function.ret.clone() });
}
},
TaskDef::Transfer {} => {
todo!();
},
}
// Move to the next edge
pc.jump(*next)
},
Linear { instrs, next } => {
// Run the instructions (as long as they don't crash)
let mut instr_pc: usize = 0;
while instr_pc < instrs.len() {
// It looks a bit funky, but we simply add the relative offset after every constrution to the edge-local program counter
instr_pc = (instr_pc as i64
+ match prof.time_func(format!("instruction {instr_pc}"), || {
exec_instr(pc, instr_pc, &instrs[instr_pc], &mut self.stack, &mut self.fstack)
}) {
Ok(next) => next,
Err(err) => {
return EdgeResult::Err(err);
},
}) as usize;
}
// Move to the next edge
pc.jump(*next)
},
Stop {} => {
// Done no value
return EdgeResult::Ok(Value::Void);
},
Branch { true_next, false_next, .. } => {
// Which branch to take depends on the top value of the stack; so get it
let value: Value = match self.stack.pop() {
Some(value) => value,
None => {
return EdgeResult::Err(Error::EmptyStackError { pc, instr: None, expected: DataType::Boolean });
},
};
// as boolean
let value_type: DataType = value.data_type(self.fstack.table());
let value: bool = match value.try_as_bool() {
Some(value) => value,
None => {
return EdgeResult::Err(Error::StackTypeError { pc, instr: None, got: value_type, expected: DataType::Boolean });
},
};
// Branch appropriately
if value {
pc.jump(*true_next)
} else {
match false_next {
Some(false_next) => pc.jump(*false_next),
None => {
return EdgeResult::Ok(Value::Void);
},
}
}
},
Parallel { branches, merge } => {
// Fork this thread for every branch
self.threads.clear();
self.threads.reserve(branches.len());
for (i, b) in branches.iter().enumerate() {
// Fork the thread for that branch
let thread: Self = self.fork(pc.jump(*b));
let prof = prof.clone();
// Schedule its running on the runtime (`spawn`)
self.threads.push((i, spawn(async move { prof.nest_fut(format!("branch {i}"), |scope| thread.run::<P>(scope.into())).await })));
}
// Mark those threads to wait for, and then move to the join
pc.jump(*merge)
},
Join { merge, next } => {
// Await the threads first (if any)
// No need to catch profile results, since writing is done in the `nest_fut` function that's already embedded in the future
let mut results: Vec<(usize, Value)> = Vec::with_capacity(self.threads.len());
for (i, t) in &mut self.threads {
match t.await {
Ok(status) => match status {
Ok(res) => {
results.push((*i, res));
},
Err(err) => {
return EdgeResult::Err(err);
},
},
Err(err) => {
return EdgeResult::Err(Error::SpawnError { pc, err });
},
}
}
self.threads.clear();
// Join their values into one according to the merge strategy
let _merge = prof.time("Result merging");
let result: Option<Value> = match merge {
MergeStrategy::First | MergeStrategy::FirstBlocking => {
if results.is_empty() {
panic!("Joining with merge strategy '{merge:?}' after no threads have been run; this should never happen!");
}
// It's a bit hard to do this unblocking right now, but from the user the effect will be the same.
Some(results.swap_remove(0).1)
},
MergeStrategy::Last => {
if results.is_empty() {
panic!("Joining with merge strategy '{merge:?}' after no threads have been run; this should never happen!");
}
// It's a bit hard to do this unblocking right now, but from the user the effect will be the same.
Some(results.swap_remove(results.len() - 1).1)
},
MergeStrategy::Sum => {
if results.is_empty() {
panic!("Joining with merge strategy '{merge:?}' after no threads have been run; this should never happen!");
}
// Prepare the sum result
let result_type: DataType = results[0].1.data_type(self.fstack.table());
let mut result: Value = if result_type == DataType::Integer {
Value::Integer { value: 0 }
} else if result_type == DataType::Real {
Value::Real { value: 0.0 }
} else {
return EdgeResult::Err(Error::IllegalBranchType {
pc,
branch: 0,
merge: *merge,
got: result_type,
expected: DataType::Numeric,
});
};
// Sum the results into that
for (i, r) in results {
match result {
Value::Integer { ref mut value } => {
if let Value::Integer { value: new_value } = r {
*value += new_value;
} else {
return EdgeResult::Err(Error::BranchTypeError {
pc,
branch: i,
got: r.data_type(self.fstack.table()),
expected: result.data_type(self.fstack.table()),
});
}
},
Value::Real { ref mut value } => {
if let Value::Real { value: new_value } = r {
*value += new_value;
} else {
return EdgeResult::Err(Error::BranchTypeError {
pc,
branch: i,
got: r.data_type(self.fstack.table()),
expected: result.data_type(self.fstack.table()),
});
}
},
_ => {
unreachable!();
},
}
}
// Done, result is now a combination of all values
Some(result)
},
MergeStrategy::Product => {
if results.is_empty() {
panic!("Joining with merge strategy '{merge:?}' after no threads have been run; this should never happen!");
}
// Prepare the sum result
let result_type: DataType = results[0].1.data_type(self.fstack.table());
let mut result: Value = if result_type == DataType::Integer {
Value::Integer { value: 0 }
} else if result_type == DataType::Real {
Value::Real { value: 0.0 }
} else {
return EdgeResult::Err(Error::IllegalBranchType {
pc,
branch: 0,
merge: *merge,
got: result_type,
expected: DataType::Numeric,
});
};
// Sum the results into that
for (i, r) in results {
match result {
Value::Integer { ref mut value } => {
if let Value::Integer { value: new_value } = r {
*value *= new_value;
} else {
return EdgeResult::Err(Error::BranchTypeError {
pc,
branch: i,
got: r.data_type(self.fstack.table()),
expected: result.data_type(self.fstack.table()),
});
}
},
Value::Real { ref mut value } => {
if let Value::Real { value: new_value } = r {
*value *= new_value;
} else {
return EdgeResult::Err(Error::BranchTypeError {
pc,
branch: i,
got: r.data_type(self.fstack.table()),
expected: result.data_type(self.fstack.table()),
});
}
},
_ => {
unreachable!();
},
}
}
// Done, result is now a combination of all values
Some(result)
},
MergeStrategy::Max => {
if results.is_empty() {
panic!("Joining with merge strategy '{merge:?}' after no threads have been run; this should never happen!");
}
// Prepare the sum result
let result_type: DataType = results[0].1.data_type(self.fstack.table());
let mut result: Value = if result_type == DataType::Integer {
Value::Integer { value: i64::MIN }
} else if result_type == DataType::Real {
Value::Real { value: f64::NEG_INFINITY }
} else {
return EdgeResult::Err(Error::IllegalBranchType {
pc,
branch: 0,
merge: *merge,
got: result_type,
expected: DataType::Numeric,
});
};
// Sum the results into that
for (i, r) in results {
match result {
Value::Integer { ref mut value } => {
if let Value::Integer { value: new_value } = r {
if new_value > *value {
*value = new_value;
}
} else {
return EdgeResult::Err(Error::BranchTypeError {
pc,
branch: i,
got: r.data_type(self.fstack.table()),
expected: result.data_type(self.fstack.table()),
});
}
},
Value::Real { ref mut value } => {
if let Value::Real { value: new_value } = r {
if new_value > *value {
*value = new_value;
}
} else {
return EdgeResult::Err(Error::BranchTypeError {
pc,
branch: i,
got: r.data_type(self.fstack.table()),
expected: result.data_type(self.fstack.table()),
});
}
},
_ => {
unreachable!();
},
}
}
// Done, result is now a combination of all values
Some(result)
},
MergeStrategy::Min => {
if results.is_empty() {
panic!("Joining with merge strategy '{merge:?}' after no threads have been run; this should never happen!");
}
// Prepare the sum result
let result_type: DataType = results[0].1.data_type(self.fstack.table());
let mut result: Value = if result_type == DataType::Integer {
Value::Integer { value: i64::MAX }
} else if result_type == DataType::Real {
Value::Real { value: f64::INFINITY }
} else {
return EdgeResult::Err(Error::IllegalBranchType {
pc,
branch: 0,
merge: *merge,
got: result_type,
expected: DataType::Numeric,
});
};
// Sum the results into that
for (i, r) in results {
match result {
Value::Integer { ref mut value } => {
if let Value::Integer { value: new_value } = r {
if new_value < *value {
*value = new_value;
}
} else {
return EdgeResult::Err(Error::BranchTypeError {
pc,
branch: i,
got: r.data_type(self.fstack.table()),
expected: result.data_type(self.fstack.table()),
});
}
},
Value::Real { ref mut value } => {
if let Value::Real { value: new_value } = r {
if new_value < *value {
*value = new_value;
}
} else {
return EdgeResult::Err(Error::BranchTypeError {
pc,
branch: i,
got: r.data_type(self.fstack.table()),
expected: result.data_type(self.fstack.table()),
});
}
},
_ => {
unreachable!();
},
}
}
// Done, result is now a combination of all values
Some(result)
},
MergeStrategy::All => {
if results.is_empty() {
panic!("Joining with merge strategy '{merge:?}' after no threads have been run; this should never happen!");
}
// Collect them all in an Array of (the same!) values
let mut elems: Vec<Value> = Vec::with_capacity(results.len());
let mut elem_type: Option<DataType> = None;
for (i, r) in results {
if let Some(elem_type) = &mut elem_type {
// Verify it's correctly typed
let r_type: DataType = r.data_type(self.fstack.table());
if elem_type != &r_type {
return EdgeResult::Err(Error::BranchTypeError { pc, branch: i, got: r_type, expected: elem_type.clone() });
}
// Add it to the list
elems.push(r);
} else {
// It's the first one; make sure there is _something_ and then add it
let r_type: DataType = r.data_type(self.fstack.table());
if r_type == DataType::Void {
return EdgeResult::Err(Error::IllegalBranchType {
pc,
branch: i,
merge: *merge,
got: DataType::Void,
expected: DataType::NonVoid,
});
}
elem_type = Some(r_type);
elems.push(r);
}
}
// Set it as an Array result
Some(Value::Array { values: elems })
},
MergeStrategy::None => None,
};
// We can now push that onto the stack, then go to next
if let Some(result) = result {
if let Err(err) = self.stack.push(result) {
return EdgeResult::Err(Error::StackError { pc, instr: None, err });
}
}
pc.jump(*next)
},
Loop { cond, .. } => {
// The thing is built in such a way we can just run the condition and be happy
// EDIT: Yeah so this was not a good idea xZ only place in the entire codebase where this is convenient...
pc.jump(*cond)
},
Call { input: _, result: _, next } => {
// Get the top value off the stack
let value: Value = match self.stack.pop() {
Some(value) => value,
None => return EdgeResult::Err(Error::EmptyStackError { pc, instr: None, expected: DataType::Numeric }),
};
// Get it as a function index
let def: usize = match value {
Value::Function { def } => def,
Value::Method { values, cdef, fdef } => {
// Insert the instance as a stack value, and only then proceed to call
let stack_len: usize = self.stack.len();
if let Err(err) =
self.stack.insert(stack_len - (self.fstack.table().func(FunctionId::Func(fdef)).args.len() - 1), Value::Instance {
values,
def: cdef,
})
{
return EdgeResult::Err(Error::StackError { pc, instr: None, err });
};
fdef
},
value => {
return EdgeResult::Err(Error::StackTypeError {
pc,
instr: None,
got: value.data_type(self.fstack.table()),
expected: DataType::Callable,
});
},
};
// Resolve the function index
let sig: &FunctionDef = self.fstack.table().func(FunctionId::Func(def));
// Double-check the correct values are on the stack
let stack_len: usize = self.stack.len();
for (i, v) in self.stack[stack_len - sig.args.len()..].iter().enumerate() {
let v_type: DataType = v.data_type(self.fstack.table());
if !v_type.allowed_by(&sig.args[i]) {
return EdgeResult::Err(Error::FunctionTypeError {
pc,
name: sig.name.clone(),
arg: i,
got: v_type,
expected: sig.args[i].clone(),
});
}
}
// Either run as a builtin (if it is defined as one) or else run the call
if sig.name == BuiltinFunctions::Print.name() {
// We have one variable that is a string; so print it
let text: String = self.stack.pop().unwrap().try_as_string().unwrap();
if let Err(err) = prof
.nest_fut(format!("{}::stdout(false)", type_name::<P>()), |scope| P::stdout(&self.global, &self.local, &text, false, scope))
.await
{
return EdgeResult::Err(Error::Custom { pc, err: Box::new(err) });
}
// Done, go to the next immediately
pc.jump(*next)
} else if sig.name == BuiltinFunctions::PrintLn.name() {
// We have one variable that is a string; so print it
let text: String = self.stack.pop().unwrap().try_as_string().unwrap();
if let Err(err) = prof
.nest_fut(format!("{}::stdout(true)", type_name::<P>()), |scope| P::stdout(&self.global, &self.local, &text, true, scope))
.await
{
return EdgeResult::Err(Error::Custom { pc, err: Box::new(err) });
}
// Done, go to the next immediately
pc.jump(*next)
} else if sig.name == BuiltinFunctions::Len.name() {
// Fetch the array
let array: Vec<Value> = self.stack.pop().unwrap().try_as_array().unwrap();
// Push the length back onto the stack
if let Err(err) = self.stack.push(Value::Integer { value: array.len() as i64 }) {
return EdgeResult::Err(Error::StackError { pc, instr: None, err });
}
// We can then go to the next one immediately
pc.jump(*next)
} else if sig.name == BuiltinFunctions::CommitResult.name() {
// Fetch the arguments
let res_name: String = self.stack.pop().unwrap().try_as_intermediate_result().unwrap();
let data_name: String = self.stack.pop().unwrap().try_as_string().unwrap();
// Try to find out where this res lives, currently
let loc: &String = match self.fstack.table().results.get(&res_name) {
Some(loc) => loc,
None => {
return EdgeResult::Err(Error::UnknownResult { pc, name: res_name });
},
};
// Call the external data committer
let res_path: PathBuf = res_name.as_str().into();
if let Err(err) = prof
.nest_fut(format!("{}::commit()", type_name::<P>()), |scope| {
P::commit(&self.global, &self.local, loc, &res_name, &res_path, &data_name, scope)
})
.await
{
return EdgeResult::Err(Error::Custom { pc, err: Box::new(err) });
};
// Push the resulting data onto the stack
if let Err(err) = self.stack.push(Value::Data { name: data_name }) {
return EdgeResult::Err(Error::StackError { pc, instr: None, err });
}
// We can then go to the next one immediately
pc.jump(*next)
} else {
// Push the return address onto the frame stack and then go to the correct function
if let Err(err) = self.fstack.push(def, pc.jump(*next)) {
return EdgeResult::Err(Error::FrameStackPushError { pc, err });
}
ProgramCounter::call(def)
}
},
Return { result: _ } => {
// Attempt to pop the top frame off the frame stack
let (ret, ret_type): (ProgramCounter, DataType) = match self.fstack.pop() {
Ok(res) => res,
Err(err) => {
return EdgeResult::Err(Error::FrameStackPopError { pc, err });
},
};
// Check if the top value on the stack has this value
if ret != ProgramCounter::new(FunctionId::Main, usize::MAX) {
// If there is something to return, verify it did
if !ret_type.is_void() {
// Peek the top value
let value: &Value = match self.stack.peek() {
Some(value) => value,
None => {
return EdgeResult::Err(Error::EmptyStackError { pc, instr: None, expected: ret_type });
},
};
// Compare its data type
let value_type: DataType = value.data_type(self.fstack.table());
if !value_type.allowed_by(&ret_type) {
return EdgeResult::Err(Error::ReturnTypeError { pc, got: value_type, expected: ret_type });
}
}
// Go to the stack'ed index
ret
} else {
// We return the top value on the stack (if any) as a result of this thread
return EdgeResult::Ok(self.stack.pop().unwrap_or(Value::Void));
}
},
};
// Return it
EdgeResult::Pending(next)
}
/// Runs the thread once until it is pending for something (either other threads or external function calls).
///
/// # Arguments
/// - `prof`: A ProfileScopeHandleOwned that is used to provide more details about the execution times of a workflow execution. Note that this is _not_ user-relevant, only debug/framework-relevant.
///
/// The reason it is owned is due to the boxed return future. It's your responsibility to keep the parent into scope after the future returns; if you don't any collected profile results will likely not be printed.
///
/// # Returns
/// The value that this thread returns once it is done.
///
/// # Errors
/// This function may error if execution of an edge or instruction failed. This is typically due to incorrect runtime typing.
pub fn run<P: VmPlugin<GlobalState = G, LocalState = L>>(mut self, prof: ProfileScopeHandleOwned) -> BoxFuture<'static, Result<Value, Error>> {
async move {
// Start executing edges from where we left off
let prof: ProfileScopeHandleOwned = prof;
loop {
// Run the edge
self.pc = match prof
.nest_fut(format!("{:?} ({})", self.get_edge(self.pc)?.variant(), self.pc), |scope| self.exec_edge::<P>(self.pc, scope.into()))
.await
{
// Either quit or continue, noting down the time taken
EdgeResult::Ok(value) => {
return Ok(value);
},
EdgeResult::Pending(next) => next,
// We failed
EdgeResult::Err(err) => {
return Err(err);
},
};
}
}
.boxed()
}
/// Runs the thread once until it is pending for something (either other threads or external function calls).
///
/// This overload supports snippet execution, returning the state that is necessary for the next repl-loop together with the result.
///
/// # Arguments
/// - `prof`: A ProfileScopeHandleOwned that is used to provide more details about the execution times of a workflow execution. Note that this is _not_ user-relevant, only debug/framework-relevant.
///
/// The reason it is owned is due to the boxed return future. It's your responsibility to keep the parent into scope after the future returns; if you don't any collected profile results will likely not be printed.
///
/// # Returns
/// A tuple of the value that is returned by this thread and the running state used to refer to variables produced in this run, respectively.
///
/// # Errors
/// This function may error if execution of an edge or instruction failed. This is typically due to incorrect runtime typing.
pub fn run_snippet<P: VmPlugin<GlobalState = G, LocalState = L>>(
mut self,
prof: ProfileScopeHandleOwned,
) -> BoxFuture<'static, Result<(Value, RunState<G>), Error>> {
async move {
// Start executing edges from where we left off
let prof: ProfileScopeHandleOwned = prof;
loop {
// Run the edge
self.pc = match prof
.nest_fut(format!("{:?} ({})", self.get_edge(self.pc)?.variant(), self.pc), |scope| self.exec_edge::<P>(self.pc, scope.into()))
.await
{
// Either quit or continue, noting down the time taken
// Return not just the value, but also the VmState part of this thread to keep.
EdgeResult::Ok(value) => {
return Ok((value, self.into_state()));
},
EdgeResult::Pending(next) => next,
// We failed
EdgeResult::Err(err) => {
return Err(err);
},
};
}
}
.boxed()
}
}