rune/runtime/inst.rs
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 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
use core::cmp::Ordering;
use core::fmt;
use musli::{Decode, Encode};
use rune_macros::InstDisplay;
use serde::{Deserialize, Serialize};
use crate as rune;
use crate::alloc::prelude::*;
use crate::Hash;
use super::{Call, FormatSpec, Memory, RuntimeError, Type, Value};
/// Pre-canned panic reasons.
///
/// To formulate a custom reason, use
/// [`VmError::panic`][crate::runtime::VmError::panic].
#[derive(Debug, TryClone, Clone, Copy, Serialize, Deserialize, Decode, Encode)]
#[try_clone(copy)]
#[non_exhaustive]
pub enum PanicReason {
/// Not implemented.
NotImplemented,
/// A pattern didn't match where it unconditionally has to.
UnmatchedPattern,
/// Tried to poll a future that has already been completed.
FutureCompleted,
}
impl PanicReason {
/// The identifier of the panic.
fn ident(&self) -> &'static str {
match *self {
Self::NotImplemented => "not implemented",
Self::UnmatchedPattern => "unmatched pattern",
Self::FutureCompleted => "future completed",
}
}
}
impl fmt::Display for PanicReason {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
match *self {
Self::NotImplemented => write!(fmt, "functionality has not been implemented yet")?,
Self::UnmatchedPattern => write!(fmt, "pattern did not match")?,
Self::FutureCompleted => {
write!(fmt, "tried to poll future that has already been completed")?
}
}
Ok(())
}
}
/// Type checks for built-in types.
#[derive(Debug, TryClone, Clone, Copy, PartialEq, Serialize, Deserialize, Decode, Encode)]
#[try_clone(copy)]
#[non_exhaustive]
pub enum TypeCheck {
/// Matches a unit type.
Unit,
/// Matches an anonymous tuple.
Tuple,
/// Matches an anonymous object.
Object,
/// Matches a vector.
Vec,
}
impl fmt::Display for TypeCheck {
fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Unit => write!(fmt, "Unit"),
Self::Tuple => write!(fmt, "Tuple"),
Self::Object => write!(fmt, "Object"),
Self::Vec => write!(fmt, "Vec"),
}
}
}
/// An operation in the stack-based virtual machine.
#[derive(Debug, TryClone, Clone, Copy, Serialize, Deserialize, Decode, Encode, InstDisplay)]
#[try_clone(copy)]
pub enum Inst {
/// Make sure that the memory region has `size` slots of memory available.
Allocate {
/// The size of the memory region to allocate.
size: usize,
},
/// Not operator. Takes a boolean from the top of the stack and inverts its
/// logical value.
///
/// # Operation
///
/// ```text
/// <bool>
/// => <bool>
/// ```
Not {
/// The operand to negate.
addr: InstAddress,
/// Whether the produced value from the not should be kept or not.
out: Output,
},
/// Negate the numerical value on the stack.
///
/// # Operation
///
/// ```text
/// <number>
/// => <number>
/// ```
Neg {
/// The operand to negate.
addr: InstAddress,
/// Whether the produced value from the negation should be kept or not.
out: Output,
},
/// Construct a closure that takes the given number of arguments and
/// captures `count` elements from the top of the stack.
///
/// # Operation
///
/// ```text
/// <value..>
/// => <fn>
/// ```
#[musli(packed)]
Closure {
/// The hash of the internally stored closure function.
hash: Hash,
/// Where to load captured values from.
addr: InstAddress,
/// The number of captured values to store in the environment.
count: usize,
/// Where to store the produced closure.
out: Output,
},
/// Perform a function call within the same unit.
///
/// It will construct a new stack frame which includes the last `args`
/// number of entries.
#[musli(packed)]
CallOffset {
/// The offset of the function being called in the same unit.
offset: usize,
/// The calling convention to use.
call: Call,
/// The address where the arguments are stored.
addr: InstAddress,
/// The number of arguments passed in at `addr`.
args: usize,
/// Whether the return value should be kept or not.
out: Output,
},
/// Call a function by hash.
///
/// The function will be looked up in the unit and context. The arguments
/// passed to the function call are stored at `addr`, where `size`
/// determines the number of arguments. The arguments will be dropped.
///
/// The return value of the function call will be written to `out`.
#[musli(packed)]
Call {
/// The hash of the function to call.
hash: Hash,
/// The address of the arguments being passed.
addr: InstAddress,
/// The number of arguments passed in at `addr`.
args: usize,
/// Whether the return value should be kept or not.
out: Output,
},
/// Call an associated function.
///
/// The instance being called should be the the object at address `addr`.
/// The number of arguments specified should include this object.
///
/// The return value of the function call will be written to `out`.
#[musli(packed)]
CallAssociated {
/// The hash of the name of the function to call.
hash: Hash,
/// The address of arguments being passed.
addr: InstAddress,
/// The number of arguments passed in at `addr`.
args: usize,
/// Whether the return value should be kept or not.
out: Output,
},
/// Look up an instance function.
///
/// The instance being used is stored at `addr`, and the function hash to look up is `hash`.
#[musli(packed)]
LoadInstanceFn {
/// The address of the instance for which the function is being loaded.
addr: InstAddress,
/// The name hash of the instance function.
hash: Hash,
/// Where to store the loaded instance function.
out: Output,
},
/// Perform a function call on a function pointer stored on the stack.
///
/// # Operation
///
/// ```text
/// <fn>
/// <args...>
/// => <ret>
/// ```
#[musli(packed)]
CallFn {
/// The address of the function being called.
function: InstAddress,
/// The address of the arguments being passed.
addr: InstAddress,
/// The number of arguments passed in at `addr`.
args: usize,
/// Whether the returned value from calling the function should be kept
/// or not.
out: Output,
},
/// Perform an index get operation. Pushing the result on the stack.
///
/// # Operation
///
/// ```text
/// <target>
/// <index>
/// => <value>
/// ```
#[musli(packed)]
IndexGet {
/// How the target is addressed.
target: InstAddress,
/// How the index is addressed.
index: InstAddress,
/// Whether the produced value should be kept or not.
out: Output,
},
/// Set the given index of the tuple on the stack, with the given value.
///
/// # Operation
///
/// ```text
/// <value>
/// <tuple>
/// => *nothing*
/// ```
#[musli(packed)]
TupleIndexSet {
/// The object being assigned to.
target: InstAddress,
/// The index to set.
index: usize,
/// The value being assigned.
value: InstAddress,
},
/// Get the given index out of a tuple from the given variable slot.
/// Errors if the item doesn't exist or the item is not a tuple.
///
/// # Operation
///
/// ```text
/// => <value>
/// ```
#[musli(packed)]
TupleIndexGetAt {
/// The address where the tuple we are getting from is stored.
addr: InstAddress,
/// The index to fetch.
index: usize,
/// Whether the produced value should be kept or not.
out: Output,
},
/// Set the given index out of an object on the top of the stack.
/// Errors if the item doesn't exist or the item is not an object.
///
/// The index is identifier by a static string slot, which is provided as an
/// argument.
///
/// # Operation
///
/// ```text
/// <object>
/// <value>
/// =>
/// ```
#[musli(packed)]
ObjectIndexSet {
/// The object being assigned to.
target: InstAddress,
/// The static string slot corresponding to the index to set.
slot: usize,
/// The value being assigned.
value: InstAddress,
},
/// Get the given index out of an object from the given variable slot.
/// Errors if the item doesn't exist or the item is not an object.
///
/// The index is identifier by a static string slot, which is provided as an
/// argument.
///
/// # Operation
///
/// ```text
/// => <value>
/// ```
#[musli(packed)]
ObjectIndexGetAt {
/// The address where the object is stored.
addr: InstAddress,
/// The static string slot corresponding to the index to fetch.
slot: usize,
/// Where to store the fetched value.
out: Output,
},
/// Perform an index set operation.
///
/// # Operation
///
/// ```text
/// <target>
/// <index>
/// <value>
/// => *noop*
/// ```
IndexSet {
/// The object being assigned to.
target: InstAddress,
/// The index to set.
index: InstAddress,
/// The value being assigned.
value: InstAddress,
},
/// Await the future that is on the stack and push the value that it
/// produces.
///
/// # Operation
///
/// ```text
/// <future>
/// => <value>
/// ```
Await {
/// Address of the future being awaited.
addr: InstAddress,
/// Whether the produced value from the await should be kept or not.
out: Output,
},
/// Select over `len` futures stored at address `addr`.
///
/// Once a branch has been matched, will store the branch that matched in
/// the branch register and perform a jump by the index of the branch that
/// matched.
///
/// Will also store the output if the future into `value`. If no branch
/// matched, the empty value will be stored.
#[musli(packed)]
Select {
/// The base address of futures being waited on.
addr: InstAddress,
/// The number of futures to poll.
len: usize,
/// Where to store the value produced by the future that completed.
value: Output,
},
/// Load the given function by hash and push onto the stack.
///
/// # Operation
///
/// ```text
/// => <value>
/// ```
#[musli(packed)]
LoadFn {
/// The hash of the function to push.
hash: Hash,
/// Where to store the loaded function.
out: Output,
},
/// Push a value onto the stack.
///
/// # Operation
///
/// ```text
/// => <value>
/// ```
#[musli(packed)]
Store {
/// The value to push.
value: InstValue,
/// Where the value is being copied to.
out: Output,
},
/// Copy a variable from a location `offset` relative to the current call
/// frame.
///
/// A copy is very cheap. It simply means pushing a reference to the stack.
#[musli(packed)]
Copy {
/// Address of the value being copied.
addr: InstAddress,
/// Where the value is being copied to.
out: Output,
},
/// Move a variable from a location `offset` relative to the current call
/// frame.
#[musli(packed)]
Move {
/// Address of the value being moved.
addr: InstAddress,
/// Where the value is being moved to.
out: Output,
},
/// Drop the given value set.
#[musli(packed)]
Drop {
/// An indicator of the set of addresses to drop.
set: usize,
},
/// Swap two values on the stack using their offsets relative to the current
/// stack frame.
#[musli(packed)]
Swap {
/// Offset to the first value.
a: InstAddress,
/// Offset to the second value.
b: InstAddress,
},
/// Pop the current stack frame and restore the instruction pointer from it.
///
/// The stack frame will be cleared, and the value on the top of the stack
/// will be left on top of it.
#[musli(packed)]
Return {
/// The address of the value to return.
addr: InstAddress,
},
/// Pop the current stack frame and restore the instruction pointer from it.
///
/// The stack frame will be cleared, and a unit value will be pushed to the
/// top of the stack.
ReturnUnit,
/// Unconditionally jump to `offset` relative to the current instruction
/// pointer.
///
/// # Operation
///
/// ```text
/// *nothing*
/// => *nothing*
/// ```
#[musli(packed)]
Jump {
/// Offset to jump to.
jump: usize,
},
/// Jump to `offset` relative to the current instruction pointer if the
/// condition is `true`.
///
/// # Operation
///
/// ```text
/// <boolean>
/// => *nothing*
/// ```
#[musli(packed)]
JumpIf {
/// The address of the condition for the jump.
cond: InstAddress,
/// Offset to jump to.
jump: usize,
},
/// Jump to the given offset If the top of the stack is false.
///
/// # Operation
///
/// ```text
/// <bool>
/// => *noop*
/// ```
#[musli(packed)]
JumpIfNot {
/// The address of the condition for the jump.
cond: InstAddress,
/// The offset to jump if the condition is true.
jump: usize,
},
/// Construct a vector at `out`, populating it with `count` elements from
/// `addr`.
///
/// The values at `addr` are dropped.
#[musli(packed)]
Vec {
/// Where the arguments to the vector are stored.
addr: InstAddress,
/// The number of elements in the vector.
count: usize,
/// Where to store the produced vector.
out: Output,
},
/// Construct a one element tuple at `out`, populating it with `count`
/// elements from `addr`.
///
/// The values at `addr` are not dropped.
#[musli(packed)]
Tuple1 {
/// Tuple arguments.
#[inst_display(display_with = DisplayArray::new)]
addr: [InstAddress; 1],
/// Where to store the produced tuple.
out: Output,
},
/// Construct a two element tuple at `out`, populating it with `count`
/// elements from `addr`.
///
/// The values at `addr` are not dropped.
#[musli(packed)]
Tuple2 {
/// Tuple arguments.
#[inst_display(display_with = DisplayArray::new)]
addr: [InstAddress; 2],
/// Where to store the produced tuple.
out: Output,
},
/// Construct a three element tuple at `out`, populating it with `count`
/// elements from `addr`.
///
/// The values at `addr` are not dropped.
#[musli(packed)]
Tuple3 {
/// Tuple arguments.
#[inst_display(display_with = DisplayArray::new)]
addr: [InstAddress; 3],
/// Where to store the produced tuple.
out: Output,
},
/// Construct a four element tuple at `out`, populating it with `count`
/// elements from `addr`.
///
/// The values at `addr` are not dropped.
#[musli(packed)]
Tuple4 {
/// Tuple arguments.
#[inst_display(display_with = DisplayArray::new)]
addr: [InstAddress; 4],
/// Where to store the produced tuple.
out: Output,
},
/// Construct a tuple at `out`, populating it with `count` elements from
/// `addr`.
///
/// Unlike `TupleN` variants, values at `addr` are dropped.
#[musli(packed)]
Tuple {
/// Where the arguments to the tuple are stored.
addr: InstAddress,
/// The number of elements in the tuple.
count: usize,
/// Where to store the produced tuple.
out: Output,
},
/// Take the tuple that is on top of the stack and push its content onto the
/// stack.
///
/// This is used to unpack an environment for closures - if the closure has
/// an environment.
///
/// # Operation
///
/// ```text
/// <tuple>
/// => <value...>
/// ```
Environment {
/// The tuple to push.
addr: InstAddress,
/// The expected size of the tuple.
count: usize,
/// Where to unpack the environment.
out: Output,
},
/// Construct a push an object onto the stack. The number of elements
/// in the object are determined the slot of the object keys `slot` and are
/// popped from the stack.
///
/// For each element, a value is popped corresponding to the object key.
///
/// # Operation
///
/// ```text
/// <value..>
/// => <object>
/// ```
#[musli(packed)]
Object {
/// Where the arguments to the tuple are stored.
addr: InstAddress,
/// The static slot of the object keys.
slot: usize,
/// Where to store the produced tuple.
out: Output,
},
/// Construct a range.
///
/// The arguments loaded are determined by the range being constructed.
#[musli(packed)]
Range {
/// The kind of the range, which determines the number arguments on the
/// stack.
range: InstRange,
/// Where to store the produced range.
out: Output,
},
/// Construct a push an object of the given type onto the stack. The type is
/// an empty struct.
///
/// # Operation
///
/// ```text
/// => <object>
/// ```
#[musli(packed)]
EmptyStruct {
/// The type of the object to construct.
hash: Hash,
/// Where to write the empty struct.
out: Output,
},
/// Construct a struct of type `hash` at `out`, populating it with fields
/// from `addr`. The number of fields and their names is determined by the
/// `slot` being referenced.
///
/// The values at `addr` are dropped.
#[musli(packed)]
Struct {
/// The address to load fields from.
addr: InstAddress,
/// The type of the struct to construct.
hash: Hash,
/// Where to write the constructed struct.
out: Output,
},
/// Construct a struct from a constant.
///
/// The values at `addr` are dropped.
#[musli(packed)]
ConstConstruct {
/// Where constructor arguments are stored.
addr: InstAddress,
/// The type of the struct to construct.
hash: Hash,
/// The number of constructor arguments.
count: usize,
/// Where to write the constructed struct.
out: Output,
},
/// Load a literal string from a static string slot.
///
/// # Operation
///
/// ```text
/// => <string>
/// ```
#[musli(packed)]
String {
/// The static string slot to load the string from.
slot: usize,
/// Where to store the string.
out: Output,
},
/// Load a literal byte string from a static byte string slot.
///
/// # Operation
///
/// ```text
/// => <bytes>
/// ```
#[musli(packed)]
Bytes {
/// The static byte string slot to load the string from.
slot: usize,
/// Where to store the bytes.
out: Output,
},
/// Pop the given number of values from the stack, and concatenate a string
/// from them.
///
/// This is a dedicated template-string optimization.
///
/// # Operation
///
/// ```text
/// <value...>
/// => <string>
/// ```
#[musli(packed)]
StringConcat {
/// Where the strings to concatenate are stored.
addr: InstAddress,
/// The number of items to pop from the stack.
len: usize,
/// The minimum string size used.
size_hint: usize,
/// Where to store the produced string.
out: Output,
},
/// Push a combined format specification and value onto the stack. The value
/// used is the last value on the stack.
#[musli(packed)]
Format {
/// Address of the value being formatted.
addr: InstAddress,
/// The format specification to use.
spec: FormatSpec,
/// Where to store the produced format.
out: Output,
},
/// Test if the top of the stack is a unit.
///
/// # Operation
///
/// ```text
/// <value>
/// => <boolean>
/// ```
IsUnit {
/// The address of the value to test.
addr: InstAddress,
/// Where to store the output.
out: Output,
},
/// Perform the try operation which takes the value at the given `address`
/// and tries to unwrap it or return from the current call frame.
///
/// # Operation
///
/// ```text
/// <value>
/// => <boolean>
/// ```
#[musli(packed)]
Try {
/// Address of value to try.
addr: InstAddress,
/// Where to store the value in case there is a continuation.
out: Output,
},
/// Test if the top of the stack is a specific character.
///
/// # Operation
///
/// ```text
/// <value>
/// => <boolean>
/// ```
#[musli(packed)]
EqChar {
/// Address of the value to compare.
addr: InstAddress,
/// The character to test against.
#[inst_display(display_with = DisplayDebug::new)]
value: char,
/// Where to store the result of the comparison.
out: Output,
},
/// Test if the specified value is a specific signed integer.
#[musli(packed)]
EqSigned {
/// Address of the value to compare.
addr: InstAddress,
/// The value to test against.
value: i64,
/// Where to store the result of the comparison.
out: Output,
},
/// Test if the specified value is a specific unsigned integer.
#[musli(packed)]
EqUnsigned {
/// Address of the value to compare.
addr: InstAddress,
/// The value to test against.
value: u64,
/// Where to store the result of the comparison.
out: Output,
},
/// Test if the top of the stack is a specific boolean.
///
/// # Operation
///
/// ```text
/// <value>
/// => <boolean>
/// ```
#[musli(packed)]
EqBool {
/// Address of the value to compare.
addr: InstAddress,
/// The value to test against.
value: bool,
/// Where to store the result of the comparison.
out: Output,
},
/// Compare the top of the stack against a static string slot.
///
/// # Operation
///
/// ```text
/// <value>
/// => <boolean>
/// ```
#[musli(packed)]
EqString {
/// Address of the value to compare.
addr: InstAddress,
/// The slot to test against.
slot: usize,
/// Where to store the result of the comparison.
out: Output,
},
/// Compare the top of the stack against a static bytes slot.
///
/// # Operation
///
/// ```text
/// <value>
/// => <boolean>
/// ```
#[musli(packed)]
EqBytes {
/// Address of the value to compare.
addr: InstAddress,
/// The slot to test against.
slot: usize,
/// Where to store the result of the comparison.
out: Output,
},
/// Test that the top of the stack has the given type.
///
/// # Operation
///
/// ```text
/// <value>
/// => <boolean>
/// ```
#[musli(packed)]
MatchType {
/// The type hash to match against.
hash: Hash,
/// The address of the value to test.
addr: InstAddress,
/// Where to store the output.
out: Output,
},
/// Test if the specified variant matches. This is distinct from
/// [Inst::MatchType] because it will match immediately on the variant type
/// if appropriate which is possible for internal types, but external types
/// will require an additional runtime check for matching.
///
/// # Operation
///
/// ```text
/// <value>
/// => <boolean>
/// ```
#[musli(packed)]
MatchVariant {
/// The exact type hash of the variant.
variant_hash: Hash,
/// The container type.
enum_hash: Hash,
/// The index of the variant.
index: usize,
/// The address of the value to test.
addr: InstAddress,
/// Where to store the output.
out: Output,
},
/// Test if the top of the stack is the given builtin type or variant.
///
/// # Operation
///
/// ```text
/// <value>
/// => <boolean>
/// ```
#[musli(packed)]
MatchBuiltIn {
/// The type to check for.
type_check: TypeCheck,
/// The address of the value to test.
addr: InstAddress,
/// Where to store the output.
out: Output,
},
/// Test that the top of the stack is a tuple with the given length
/// requirements.
///
/// # Operation
///
/// ```text
/// <value>
/// => <boolean>
/// ```
#[musli(packed)]
MatchSequence {
/// Type constraints that the sequence must match.
type_check: TypeCheck,
/// The minimum length to test for.
len: usize,
/// Whether the operation should check exact `true` or minimum length
/// `false`.
exact: bool,
/// The address of the value to test.
addr: InstAddress,
/// Where to store the output.
out: Output,
},
/// Test that the top of the stack is an object matching the given slot of
/// object keys.
///
/// # Operation
///
/// ```text
/// <object>
/// => <boolean>
/// ```
#[musli(packed)]
MatchObject {
/// The slot of object keys to use.
slot: usize,
/// Whether the operation should check exact `true` or minimum length
/// `false`.
exact: bool,
/// The address of the value to test.
addr: InstAddress,
/// Where to store the output.
out: Output,
},
/// Perform a generator yield where the value yielded is expected to be
/// found at the top of the stack.
///
/// This causes the virtual machine to suspend itself.
///
/// # Operation
///
/// ```text
/// <value>
/// => <value>
/// ```
Yield {
/// Address of the value being yielded.
addr: InstAddress,
/// Where to store the produced resume value.
out: Output,
},
/// Perform a generator yield with a unit.
///
/// This causes the virtual machine to suspend itself.
///
/// # Operation
///
/// ```text
/// => <unit>
/// ```
YieldUnit {
/// Where to store the produced resume value.
out: Output,
},
/// Construct a built-in variant onto the stack.
///
/// The variant will pop as many values of the stack as necessary to
/// construct it.
///
/// # Operation
///
/// ```text
/// <value..>
/// => <variant>
/// ```
#[musli(packed)]
Variant {
/// Where the arguments to construct the variant are stored.
addr: InstAddress,
/// The kind of built-in variant to construct.
variant: InstVariant,
/// Where to store the variant.
out: Output,
},
/// An operation.
#[musli(packed)]
Op {
/// The kind of operation.
op: InstOp,
/// The address of the first argument.
a: InstAddress,
/// The address of the second argument.
b: InstAddress,
/// Whether the produced value from the operation should be kept or not.
out: Output,
},
/// An arithmetic operation.
#[musli(packed)]
Arithmetic {
/// The kind of operation.
op: InstArithmeticOp,
/// The address of the first argument.
a: InstAddress,
/// The address of the second argument.
b: InstAddress,
/// Whether the produced value from the operation should be kept or not.
out: Output,
},
/// A bitwise operation.
#[musli(packed)]
Bitwise {
/// The kind of operation.
op: InstBitwiseOp,
/// The address of the first argument.
a: InstAddress,
/// The address of the second argument.
b: InstAddress,
/// Whether the produced value from the operation should be kept or not.
out: Output,
},
/// A shift operation.
#[musli(packed)]
Shift {
/// The kind of operation.
op: InstShiftOp,
/// The address of the first argument.
a: InstAddress,
/// The address of the second argument.
b: InstAddress,
/// Whether the produced value from the operation should be kept or not.
out: Output,
},
/// Instruction for assigned arithmetic operations.
#[musli(packed)]
AssignArithmetic {
/// The kind of operation.
op: InstArithmeticOp,
/// The target of the operation.
target: InstTarget,
/// The value being assigned.
rhs: InstAddress,
},
/// Instruction for assigned bitwise operations.
#[musli(packed)]
AssignBitwise {
/// The kind of operation.
op: InstBitwiseOp,
/// The target of the operation.
target: InstTarget,
/// The value being assigned.
rhs: InstAddress,
},
/// Instruction for assigned shift operations.
#[musli(packed)]
AssignShift {
/// The kind of operation.
op: InstShiftOp,
/// The target of the operation.
target: InstTarget,
/// The value being assigned.
rhs: InstAddress,
},
/// Advance an iterator at the given position.
#[musli(packed)]
IterNext {
/// The address of the iterator to advance.
addr: InstAddress,
/// A relative jump to perform if the iterator could not be advanced.
jump: usize,
/// Where to store the produced value from the iterator.
out: Output,
},
/// Cause the VM to panic and error out without a reason.
///
/// This should only be used during testing or extreme scenarios that are
/// completely unrecoverable.
#[musli(packed)]
Panic {
/// The reason for the panic.
#[inst_display(display_with = PanicReason::ident)]
reason: PanicReason,
},
}
impl Inst {
/// Construct an instruction to push a unit.
pub fn unit(out: Output) -> Self {
Self::Store {
value: InstValue::Unit,
out,
}
}
/// Construct an instruction to push a boolean.
pub fn bool(b: bool, out: Output) -> Self {
Self::Store {
value: InstValue::Bool(b),
out,
}
}
/// Construct an instruction to push a character.
pub fn char(c: char, out: Output) -> Self {
Self::Store {
value: InstValue::Char(c),
out,
}
}
/// Construct an instruction to push an integer.
pub fn signed(v: i64, out: Output) -> Self {
Self::Store {
value: InstValue::Integer(v),
out,
}
}
/// Construct an instruction to push an unsigned integer.
pub fn unsigned(v: u64, out: Output) -> Self {
Self::Store {
value: InstValue::Unsigned(v),
out,
}
}
/// Construct an instruction to push a float.
pub fn float(v: f64, out: Output) -> Self {
Self::Store {
value: InstValue::Float(v),
out,
}
}
/// Construct an instruction to push a type.
pub fn ty(ty: Type, out: Output) -> Self {
Self::Store {
value: InstValue::Type(ty),
out,
}
}
/// Construct an instruction to push an ordering.
pub fn ordering(ordering: Ordering, out: Output) -> Self {
Self::Store {
value: InstValue::Ordering(ordering),
out,
}
}
}
/// What to do with the output of an instruction.
#[derive(TryClone, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize, Encode, Decode)]
#[try_clone(copy)]
#[non_exhaustive]
#[musli(transparent)]
#[serde(transparent)]
pub struct Output {
offset: usize,
}
impl Output {
/// Construct a keep output kind.
#[inline]
pub(crate) fn keep(offset: usize) -> Self {
assert_ne!(offset, usize::MAX, "Address is invalid");
Self { offset }
}
/// Construct a discard output kind.
#[inline]
pub(crate) fn discard() -> Self {
Self { offset: usize::MAX }
}
/// Check if the output is a keep.
#[inline(always)]
pub(crate) fn as_addr(&self) -> Option<InstAddress> {
if self.offset == usize::MAX {
None
} else {
Some(InstAddress::new(self.offset))
}
}
/// Write output using the provided [`IntoOutput`] implementation onto the
/// stack.
///
/// The [`IntoOutput`] trait primarily allows for deferring a computation
/// since it's implemented by [`FnOnce`]. However, you must take care that
/// any side effects calling a function may have are executed outside of the
/// call to `store`. Like if the function would error.
///
/// # Examples
///
/// ```
/// use rune::runtime::{Output, Memory, ToValue, VmResult, InstAddress};
/// use rune::vm_try;
///
/// fn sum(stack: &mut dyn Memory, addr: InstAddress, args: usize, out: Output) -> VmResult<()> {
/// let mut number = 0;
///
/// for value in vm_try!(stack.slice_at(addr, args)) {
/// number += vm_try!(value.as_integer::<i64>());
/// }
///
/// out.store(stack, number);
/// VmResult::Ok(())
/// }
#[inline(always)]
pub fn store<M, O>(self, stack: &mut M, o: O) -> Result<(), RuntimeError>
where
M: ?Sized + Memory,
O: IntoOutput,
{
if let Some(addr) = self.as_addr() {
*stack.at_mut(addr)? = o.into_output()?;
}
Ok(())
}
}
impl fmt::Display for Output {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.offset == usize::MAX {
write!(f, "discard")
} else {
write!(f, "keep({})", self.offset)
}
}
}
impl fmt::Debug for Output {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
/// Trait used to coerce values into outputs.
pub trait IntoOutput {
/// Coerce the current value into an output.
fn into_output(self) -> Result<Value, RuntimeError>;
}
impl<F, O> IntoOutput for F
where
F: FnOnce() -> O,
O: IntoOutput,
{
#[inline]
fn into_output(self) -> Result<Value, RuntimeError> {
self().into_output()
}
}
impl<T, E> IntoOutput for Result<T, E>
where
T: IntoOutput,
RuntimeError: From<E>,
{
#[inline]
fn into_output(self) -> Result<Value, RuntimeError> {
self?.into_output()
}
}
impl IntoOutput for Value {
#[inline]
fn into_output(self) -> Result<Value, RuntimeError> {
Ok(self)
}
}
/// How an instruction addresses a value.
#[derive(
Default,
TryClone,
Clone,
Copy,
PartialEq,
Eq,
Hash,
PartialOrd,
Ord,
Serialize,
Deserialize,
Decode,
Encode,
)]
#[repr(transparent)]
#[try_clone(copy)]
pub struct InstAddress {
offset: usize,
}
impl InstAddress {
/// The first possible address.
pub const ZERO: InstAddress = InstAddress { offset: 0 };
/// An invalid address.
pub const INVALID: InstAddress = InstAddress { offset: usize::MAX };
/// Construct a new address.
#[inline]
pub(crate) const fn new(offset: usize) -> Self {
Self { offset }
}
/// Get the offset of the address.
#[inline]
pub(crate) fn offset(self) -> usize {
self.offset
}
/// Get the address as an output.
#[inline]
pub(crate) fn output(self) -> Output {
Output::keep(self.offset)
}
}
impl fmt::Display for InstAddress {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.offset == usize::MAX {
write!(f, "invalid")
} else {
self.offset.fmt(f)
}
}
}
impl fmt::Debug for InstAddress {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self, f)
}
}
/// Range limits of a range expression.
#[derive(Debug, TryClone, Clone, Copy, Serialize, Deserialize, Decode, Encode)]
#[try_clone(copy)]
#[non_exhaustive]
pub enum InstRange {
/// `start..`.
RangeFrom {
/// The start address of the range.
start: InstAddress,
},
/// `..`.
RangeFull,
/// `start..=end`.
RangeInclusive {
/// The start address of the range.
start: InstAddress,
/// The end address of the range.
end: InstAddress,
},
/// `..=end`.
RangeToInclusive {
/// The end address of the range.
end: InstAddress,
},
/// `..end`.
RangeTo {
/// The end address of the range.
end: InstAddress,
},
/// `start..end`.
Range {
/// The start address of the range.
start: InstAddress,
/// The end address of the range.
end: InstAddress,
},
}
impl fmt::Display for InstRange {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
InstRange::RangeFrom { start } => write!(f, "{start}.."),
InstRange::RangeFull => write!(f, ".."),
InstRange::RangeInclusive { start, end } => write!(f, "{start}..={end}"),
InstRange::RangeToInclusive { end } => write!(f, "..={end}"),
InstRange::RangeTo { end } => write!(f, "..{end}"),
InstRange::Range { start, end } => write!(f, "{start}..{end}"),
}
}
}
/// The target of an operation.
#[derive(Debug, TryClone, Clone, Copy, Serialize, Deserialize, Encode, Decode)]
#[try_clone(copy)]
pub enum InstTarget {
/// Target is an offset to the current call frame.
#[musli(packed)]
Address(InstAddress),
/// Target the field of an object.
#[musli(packed)]
Field(InstAddress, usize),
/// Target a tuple field.
#[musli(packed)]
TupleField(InstAddress, usize),
}
impl fmt::Display for InstTarget {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Address(addr) => write!(f, "address({addr})"),
Self::Field(addr, slot) => write!(f, "field({addr}, {slot})"),
Self::TupleField(addr, slot) => write!(f, "tuple-field({addr}, {slot})"),
}
}
}
/// An operation between two values on the machine.
#[derive(Debug, TryClone, Clone, Copy, Serialize, Deserialize, Decode, Encode)]
#[try_clone(copy)]
pub enum InstArithmeticOp {
/// The add operation. `a + b`.
Add,
/// The sub operation. `a - b`.
Sub,
/// The multiply operation. `a * b`.
Mul,
/// The division operation. `a / b`.
Div,
/// The remainder operation. `a % b`.
Rem,
}
impl fmt::Display for InstArithmeticOp {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Add => {
write!(f, "+")?;
}
Self::Sub => {
write!(f, "-")?;
}
Self::Mul => {
write!(f, "*")?;
}
Self::Div => {
write!(f, "/")?;
}
Self::Rem => {
write!(f, "%")?;
}
}
Ok(())
}
}
/// An operation between two values on the machine.
#[derive(Debug, TryClone, Clone, Copy, Serialize, Deserialize, Decode, Encode)]
#[try_clone(copy)]
pub enum InstBitwiseOp {
/// The bitwise and operation. `a & b`.
BitAnd,
/// The bitwise xor operation. `a ^ b`.
BitXor,
/// The bitwise or operation. `a | b`.
BitOr,
}
impl fmt::Display for InstBitwiseOp {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::BitAnd => {
write!(f, "&")?;
}
Self::BitXor => {
write!(f, "^")?;
}
Self::BitOr => {
write!(f, "|")?;
}
}
Ok(())
}
}
/// An operation between two values on the machine.
#[derive(Debug, TryClone, Clone, Copy, Serialize, Deserialize, Decode, Encode)]
#[try_clone(copy)]
pub enum InstShiftOp {
/// The shift left operation. `a << b`.
Shl,
/// The shift right operation. `a << b`.
Shr,
}
impl fmt::Display for InstShiftOp {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Shl => {
write!(f, "<<")?;
}
Self::Shr => {
write!(f, ">>")?;
}
}
Ok(())
}
}
/// An operation between two values on the machine.
#[derive(Debug, TryClone, Clone, Copy, Serialize, Deserialize, Decode, Encode)]
#[try_clone(copy)]
pub enum InstOp {
/// Compare two values on the stack for lt and push the result as a
/// boolean on the stack.
Lt,
/// Compare two values on the stack for lte and push the result as a
/// boolean on the stack.
Le,
/// Compare two values on the stack for gt and push the result as a
/// boolean on the stack.
Gt,
/// Compare two values on the stack for gte and push the result as a
/// boolean on the stack.
Ge,
/// Compare two values on the stack for equality and push the result as a
/// boolean on the stack.
///
/// # Operation
///
/// ```text
/// <b>
/// <a>
/// => <bool>
/// ```
Eq,
/// Compare two values on the stack for inequality and push the result as a
/// boolean on the stack.
///
/// # Operation
///
/// ```text
/// <b>
/// <a>
/// => <bool>
/// ```
Neq,
/// Coerce a value into the given type.
///
/// # Operation
///
/// ```text
/// <type>
/// <value>
/// => <boolean>
/// ```
As,
/// Test if the top of the stack is an instance of the second item on the
/// stack.
///
/// # Operation
///
/// ```text
/// <type>
/// <value>
/// => <boolean>
/// ```
Is,
/// Test if the top of the stack is not an instance of the second item on
/// the stack.
///
/// # Operation
///
/// ```text
/// <type>
/// <value>
/// => <boolean>
/// ```
IsNot,
/// Pop two values from the stack and test if they are both boolean true.
///
/// # Operation
///
/// ```text
/// <boolean>
/// <boolean>
/// => <boolean>
/// ```
And,
/// Pop two values from the stack and test if either of them are boolean
/// true.
///
/// # Operation
///
/// ```text
/// <boolean>
/// <boolean>
/// => <boolean>
/// ```
Or,
}
impl fmt::Display for InstOp {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Lt => {
write!(f, "<")?;
}
Self::Gt => {
write!(f, ">")?;
}
Self::Le => {
write!(f, "<=")?;
}
Self::Ge => {
write!(f, ">=")?;
}
Self::Eq => {
write!(f, "==")?;
}
Self::Neq => {
write!(f, "!=")?;
}
Self::As => {
write!(f, "as")?;
}
Self::Is => {
write!(f, "is")?;
}
Self::IsNot => {
write!(f, "is not")?;
}
Self::And => {
write!(f, "&&")?;
}
Self::Or => {
write!(f, "||")?;
}
}
Ok(())
}
}
/// A literal value that can be pushed.
#[derive(Debug, TryClone, Clone, Copy, Serialize, Deserialize, Decode, Encode)]
#[try_clone(copy)]
#[non_exhaustive]
pub enum InstValue {
/// An empty tuple.
Unit,
/// A boolean.
#[musli(packed)]
Bool(bool),
/// A character.
#[musli(packed)]
Char(char),
/// An unsigned integer.
#[musli(packed)]
Unsigned(u64),
/// An integer.
#[musli(packed)]
Integer(i64),
/// A float.
#[musli(packed)]
Float(f64),
/// A type hash.
#[musli(packed)]
Type(Type),
/// An ordering.
Ordering(
#[musli(with = crate::musli::ordering)]
#[serde(with = "crate::serde::ordering")]
Ordering,
),
}
impl InstValue {
/// Convert into a value that can be pushed onto the stack.
pub fn into_value(self) -> Value {
match self {
Self::Unit => Value::unit(),
Self::Bool(v) => Value::from(v),
Self::Char(v) => Value::from(v),
Self::Unsigned(v) => Value::from(v),
Self::Integer(v) => Value::from(v),
Self::Float(v) => Value::from(v),
Self::Type(v) => Value::from(v),
Self::Ordering(v) => Value::from(v),
}
}
}
impl fmt::Display for InstValue {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Unit => write!(f, "()")?,
Self::Bool(v) => write!(f, "{}", v)?,
Self::Char(v) => write!(f, "{v:?}")?,
Self::Unsigned(v) => write!(f, "{v}u64")?,
Self::Integer(v) => write!(f, "{v}i64")?,
Self::Float(v) => write!(f, "{v}")?,
Self::Type(v) => write!(f, "{}", v.into_hash())?,
Self::Ordering(v) => write!(f, "{v:?}")?,
}
Ok(())
}
}
/// A variant that can be constructed.
#[derive(Debug, TryClone, Clone, Copy, Serialize, Deserialize, Decode, Encode)]
#[try_clone(copy)]
pub enum InstVariant {
/// `Option::Some`, which uses one value.
Some,
/// `Option::None`, which uses no values.
None,
/// `Result::Ok`, which uses one value.
Ok,
/// `Result::Err`, which uses one value.
Err,
}
impl fmt::Display for InstVariant {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Some => {
write!(f, "Some")?;
}
Self::None => {
write!(f, "None")?;
}
Self::Ok => {
write!(f, "Ok")?;
}
Self::Err => {
write!(f, "Err")?;
}
}
Ok(())
}
}
#[repr(transparent)]
struct DisplayArray<T>(T)
where
T: ?Sized;
impl<T> DisplayArray<[T]> {
#[inline]
fn new(value: &[T]) -> &Self {
// SAFETY: The `DisplayArray` struct is a transparent wrapper around the
// value.
unsafe { &*(value as *const [T] as *const Self) }
}
}
impl<T> fmt::Display for DisplayArray<[T]>
where
T: fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut it = self.0.iter();
write!(f, "[")?;
let last = it.next_back();
for value in it {
write!(f, "{value}, ")?;
}
if let Some(last) = last {
last.fmt(f)?;
}
write!(f, "]")?;
Ok(())
}
}
#[repr(transparent)]
struct DisplayDebug<T>(T)
where
T: ?Sized;
impl<T> DisplayDebug<T>
where
T: ?Sized,
{
#[inline]
fn new(value: &T) -> &Self {
// SAFETY: The `DisplayDebug` struct is a transparent wrapper around the
// value.
unsafe { &*(value as *const T as *const Self) }
}
}
impl<T> fmt::Display for DisplayDebug<T>
where
T: ?Sized + fmt::Debug,
{
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.0, f)
}
}
impl IntoOutput for &str {
#[inline]
fn into_output(self) -> Result<Value, RuntimeError> {
Ok(Value::try_from(self)?)
}
}