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
use std::{
fmt::{Display, Formatter},
iter::Peekable,
mem::{swap, take},
println,
rc::Rc,
vec,
};
use hashbrown::HashMap;
use crate::{
chunk::Chunk,
code::OpCode,
error::{ErrorTuple, Location, SiltError},
function::FunctionObject,
lexer::{Lexer, TokenResult},
token::{Operator, Token},
value::Value,
};
macro_rules! build_block_until {
($self:ident, $($rule:ident)|*) => {{
while match $self.peek()? {
$( Token::$rule)|* => {$self.eat(); false}
Token::EOF => {
return Err($self.error_at(SiltError::UnterminatedBlock));
}
_ =>{declaration($self)?; true}
} {
}
}};
}
macro_rules! devnote {
($self:ident $message:literal) => {
#[cfg(feature = "dev-out")]
println!(
"=> {}: peek: {:?} -> current: {:?}",
$message,
$self.peek().unwrap_or(&Token::Nil).clone(),
$self.get_current().unwrap_or(&Token::Nil)
);
};
}
macro_rules! devout {
($($arg:tt)*) => {
#[cfg(feature = "dev-out")]
println!($($arg)*);
}
}
macro_rules! op_assign {
($self:ident, $ident:ident,$op:ident) => {{
let value = $self.expression();
let bin = Expression::Binary {
left: Box::new(Expression::Variable {
$ident,
location: $self.get_last_loc(),
}),
operator: Operator::$op,
right: Box::new(value),
location: $self.get_last_loc(),
};
Expression::Assign {
ident: $ident,
value: Box::new(bin),
location: $self.get_last_loc(),
}
}};
}
/** error if missing, eat if present */
macro_rules! expect_token {
($self:ident $token:ident) => {{
if let Token::$token = $self.peek()? {
$self.eat();
} else {
return Err($self.error_at(SiltError::ExpectedToken(Token::$token)));
}
};};
($self:ident, $token:ident, $custom_error:expr) => {{
if let Token::$token = $self.peek()? {
$self.eat();
} else {
return Err($custom_error);
}
};};
}
macro_rules! expect_token_exp {
($self:ident $token:ident) => {{
if let Some(&Token::$token) = $self.peek() {
$self.eat();
} else {
$self.error(SiltError::ExpectedToken(Token::$token));
return Expression::InvalidExpression;
}
};};
}
macro_rules! rule {
($prefix:expr, $infix:expr, $precedence:tt) => {{
ParseRule {
prefix: $prefix,
infix: $infix,
precedence: Precedence::$precedence,
}
}};
() => {};
}
/** the higher the precedence, */
#[derive(PartialEq, PartialOrd)]
enum Precedence {
None,
Assignment, // =
Or, // or
And, // and
Equality, // == ~= !=
Comparison, // < > <= >=
Concat, // ..
Term, // + -
Factor, // * /
Unary, // ~ - !
Call, // . ()
Primary,
}
// precedence enum includes concat ..
type Ident = u8;
type Catch = Result<(), ErrorTuple>;
impl Precedence {
fn next(self) -> Self {
match self {
Precedence::None => Precedence::Assignment,
Precedence::Assignment => Precedence::Or,
Precedence::Or => Precedence::And,
Precedence::And => Precedence::Equality,
Precedence::Equality => Precedence::Comparison,
Precedence::Comparison => Precedence::Concat,
Precedence::Concat => Precedence::Term,
Precedence::Term => Precedence::Factor,
Precedence::Factor => Precedence::Unary,
Precedence::Unary => Precedence::Call,
Precedence::Call => Precedence::Primary,
Precedence::Primary => Precedence::Primary, // TODO over?
}
}
}
impl Display for Precedence {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
match self {
Precedence::None => write!(f, "None"),
Precedence::Assignment => write!(f, "Assignment"),
Precedence::Or => write!(f, "Or"),
Precedence::And => write!(f, "And"),
Precedence::Equality => write!(f, "Equality"),
Precedence::Comparison => write!(f, "Comparison"),
Precedence::Concat => write!(f, "Concat"),
Precedence::Term => write!(f, "Term"),
Precedence::Factor => write!(f, "Factor"),
Precedence::Unary => write!(f, "Unary"),
Precedence::Call => write!(f, "Call"),
Precedence::Primary => write!(f, "Primary"),
}
}
}
struct ParseRule {
prefix: fn(&mut Compiler, can_assign: bool) -> Catch,
infix: fn(&mut Compiler, can_assign: bool) -> Catch,
precedence: Precedence,
}
/** stores a local identifier's name by boxed string, if none is provbided it serves as a placeholder for statements such as a loop, this way they cannot be resolved as variables */
struct Local {
ident: Option<Box<String>>,
/** scope depth, indepedent of functional depth */
depth: usize,
/** how many layers deep the local value is nested in a function, with 0 being global (should only happen once to reserve the root func on the stack) */
functional_depth: usize,
is_captured: bool,
}
struct UpLocal {
/** location on the overall stack */
ident: u8,
/** location on the immediately scoped stack, 1 if it's the first declared value in scope (after closure) */
// scoped_ident: u8,
neighboring: bool,
universal_ident: u8,
}
pub struct Compiler {
pub body: FunctionObject,
iterator: Peekable<Lexer>,
pub current_index: usize,
pub errors: Vec<ErrorTuple>,
pub valid: bool,
current: Result<Token, ErrorTuple>,
current_location: Location,
local_count: usize,
scope_depth: usize,
functional_depth: usize,
// TODO we need a fail catch if we exceed a local variable amount of up values as well
up_values: Vec<Vec<UpLocal>>,
/** an offset tracker each time we descend into a new functional scope. For instance if we drop 1 level down from the root level that had 3 locals prior [A,B,C] then our stack looks like [root, A, B, C, fn] then we'll store 3 at this field's index 0 since the calling function is always at the bottom of the stack */
local_functional_offset: Vec<usize>,
// locals: Vec<Local>,
locals: Vec<Local>,
labels: HashMap<String, usize>,
// location: (usize, usize),
// previous: TokenTuple,
// pre_previous: TokenTuple,
pending_gotos: Vec<(String, usize, Location)>,
extra: bool, // pub global: &'a mut Environment,
/** hack to flip off a pop when an expression takes on statement properties, used only for := right now */
override_pop: bool,
}
impl<'a> Compiler {
/** Create a new compiler instance */
pub fn new() -> Compiler {
// assert!(p.len() == p.len());
Self {
body: FunctionObject::new(None, true),
iterator: Lexer::new("".to_string()).peekable(),
current: Ok(Token::Nil),
current_location: (0, 0),
current_index: 0,
errors: vec![],
valid: true,
local_count: 0,
scope_depth: 0,
functional_depth: 0,
up_values: vec![vec![]],
locals: vec![Local {
ident: None,
depth: 0,
functional_depth: 0,
is_captured: false,
}],
local_functional_offset: vec![],
labels: HashMap::new(),
pending_gotos: vec![],
// location: (0, 0),
// previous: (Token::Nil, (0, 0)),
// pre_previous: (Token::Nil, (0, 0)),
extra: true,
override_pop: false,
}
}
/** Syntax error with code at location */
fn error_syntax(&mut self, code: SiltError, location: Location) -> ErrorTuple {
self.valid = false;
self.body.chunk.invalidate();
ErrorTuple { code, location }
}
/**syntax error at current token location with provided code */
fn error_at(&mut self, code: SiltError) -> ErrorTuple {
self.error_syntax(code, self.current_location)
}
/** Print all syntax errors */
pub fn print_errors(&self) {
for e in &self.errors {
println!("!!{} at {}:{}", e.code, e.location.0, e.location.1);
}
}
pub fn error_string(&self) -> String {
let mut s = String::new();
for e in &self.errors {
s.push_str(&format!(
"!!{} at {}:{}",
e.code, e.location.0, e.location.1
));
}
s
}
/** Push error and location on to error stack */
fn push_error(&mut self, code: ErrorTuple) {
self.errors.push(code);
}
/** Return current array of errors */
pub fn get_errors(&self) -> &Vec<ErrorTuple> {
&self.errors
}
pub fn pop_errors(&mut self) -> Vec<ErrorTuple> {
std::mem::replace(&mut self.errors, vec![])
}
fn get_chunk(&self) -> &Chunk {
&self.body.chunk
}
fn get_chunk_mut(&mut self) -> &mut Chunk {
&mut self.body.chunk
}
fn get_chunk_size(&self) -> usize {
self.body.chunk.code.len()
}
fn write_code(&mut self, byte: OpCode, location: Location) -> usize {
self.body.chunk.write_code(byte, location)
}
fn read_last_code(&self) -> &OpCode {
self.body.chunk.read_last_code()
}
fn write_identifier(&mut self, identifier: Box<String>) -> usize {
self.body.chunk.write_identifier(identifier)
}
/** pop and return the token tuple, take care as this does not wipe the current token but does advance the iterator */
fn pop(&mut self) -> (Result<Token, ErrorTuple>, Location) {
self.current_index += 1;
match self.iterator.next() {
Some(Ok(t)) => {
devout!("popped {}", t.0);
(Ok(t.0), t.1)
}
Some(Err(e)) => {
let l = e.location;
(Err(e), l)
}
None => (Ok(Token::EOF), (0, 0)),
}
}
/** Slightly faster pop that devourse the token or error, should follow a peek or risk skipping as possible error. Probably irrelevant otherwise. */
fn eat(&mut self) {
self.current_index += 1;
let t = self.iterator.next();
#[cfg(feature = "dev-out")]
{
match t {
Some(Ok(t)) => println!("eat {}", t.0),
Some(Err(e)) => println!("eat {}", e.code),
None => println!("eat {:?}", Token::EOF),
}
}
}
/** pop and store on to self as current token tuple */
fn store(&mut self) {
self.current_index += 1;
(self.current, self.current_location) = match self.iterator.next() {
Some(Ok(t)) => (Ok(t.0), t.1),
Some(Err(e)) => {
// self.error_syntax(e.code, e.location);
let l = e.location;
(Err(e), l)
}
None => (Ok(Token::EOF), (0, 0)),
};
}
/** take by value and gain ownership of the currently stored token */
fn copy_store(&mut self) -> Result<Token, ErrorTuple> {
// std::mem::replace(&mut self.current, Ok(Token::Nil))
self.current.clone()
}
/** take current, replace with next. a true pop*/
fn store_and_return(&mut self) -> Result<Token, ErrorTuple> {
self.current_index += 1;
let (r, l) = match self.iterator.next() {
Some(Ok(t)) => (Ok(t.0), t.1),
Some(Err(e)) => {
// self.error_syntax(e.code, e.location);
let l = e.location;
(Err(e), l)
}
None => (Ok(Token::EOF), (0, 0)),
};
self.current_location = l;
std::mem::replace(&mut self.current, r)
}
/** return the current token result */
fn get_current(&self) -> Result<&Token, ErrorTuple> {
match &self.current {
Ok(t) => {
devout!("get_current {}", t);
Ok(t)
}
Err(e) => Err(e.clone()),
}
}
/** only use after peek */
// pub fn eat_out(&mut self) -> TokenResult {
// self.current_index += 1;
// self.iterator.next().unwrap()
// }
/** return the peeked token result */
fn peek(&mut self) -> Result<&Token, ErrorTuple> {
match self.iterator.peek() {
Some(Ok(t)) => {
devout!("peek {}", t.0);
Ok(&t.0)
}
Some(Err(e)) => {
// self.error_syntax(e.code, e.location);
devout!("peek err {}", e.code);
let l = e.location;
Err(ErrorTuple {
code: e.code.clone(),
location: l,
})
}
None => Ok(&Token::EOF),
}
}
/** return the peeked token tuple (token+location) result */
fn peek_result(&mut self) -> &TokenResult {
#[cfg(feature = "dev-out")]
match self.iterator.peek() {
Some(r) => {
match r {
Ok(t) => {
println!("peek_res {}", t.0);
}
Err(e) => {
println!("peek_res err {}", e.code);
}
}
r
}
None => &Ok((Token::EOF, (0, 0))),
}
#[cfg(not(feature = "dev-out"))]
match self.iterator.peek() {
Some(r) => r,
None => &Ok((Token::EOF, (0, 0))),
}
}
/** emit op code at token location */
fn emit(&mut self, op: OpCode, location: Location) {
#[cfg(feature = "dev-out")]
{
println!("emit ... {}", op);
// self.chunk.print_chunk();
}
self.write_code(op, location);
}
/** emit op code at current token location */
fn emit_at(&mut self, op: OpCode) {
#[cfg(feature = "dev-out")]
{
println!("emit_at ...{}", op);
// self.chunk.print_chunk()
}
self.write_code(op, self.current_location);
}
/** emit op code at current token location and return op index */
fn emit_index(&mut self, op: OpCode) -> usize {
#[cfg(feature = "dev-out")]
{
println!("emit_index ... {}", op);
// frame.chunk.print_chunk()
}
self.write_code(op, self.current_location)
}
/** patch the op code that specified index */
fn patch(&mut self, offset: usize) -> Catch {
let jump = self.get_chunk().code.len() - offset - 1;
if jump > u16::MAX as usize {
self.error_at(SiltError::TooManyOperations);
}
// self.chunk.code[offset] = ((jump >> 8) & 0xff) as u8;
// self.chunk.code[offset + 1] = (jump & 0xff) as u8;
match self.get_chunk().code[offset] {
OpCode::GOTO_IF_FALSE(_) => {
self.get_chunk_mut().code[offset] = OpCode::GOTO_IF_FALSE(jump as u16)
}
OpCode::GOTO_IF_TRUE(_) => {
self.get_chunk_mut().code[offset] = OpCode::GOTO_IF_TRUE(jump as u16)
}
OpCode::FORWARD(_) => self.get_chunk_mut().code[offset] = OpCode::FORWARD(jump as u16),
OpCode::REWIND(_) => self.get_chunk_mut().code[offset] = OpCode::REWIND(jump as u16),
_ => {
return Err(self.error_at(SiltError::ChunkCorrupt));
}
}
Ok(())
}
fn emit_rewind(&mut self, start: usize) {
// we base the jump off of the index we'll be at one we've written the rewind op below
let jump = (self.get_chunk_size() + 1) - start;
if jump > u16::MAX as usize {
self.error_at(SiltError::TooManyOperations);
}
self.write_code(OpCode::REWIND(jump as u16), self.current_location);
}
fn set_label(&mut self, label: String) {
self.labels.insert(label, self.get_chunk_size());
}
fn identifer_constant(&mut self, ident: Box<String>) -> u8 {
self.write_identifier(ident) as u8
}
/** write to constant table */
fn write_constant(&mut self, value: Value) -> u8 {
self.body.chunk.write_constant(value) as u8
}
/** write to constant table and emit the op code at location */
fn constant(&mut self, value: Value, location: Location) {
let constant = self.write_constant(value);
self.emit(OpCode::CONSTANT { constant }, location);
}
/** write to constant table and emit the op code at the current location */
fn constant_at(&mut self, value: Value) {
self.constant(value, self.current_location);
}
/** write identifier to constant table, remove duplicates, and emit code */
fn emit_identifer_constant_at(&mut self, ident: Box<String>) {
let constant = self.write_identifier(ident) as u8;
self.emit(OpCode::CONSTANT { constant }, self.current_location);
}
fn is_end(&mut self) -> bool {
match self.iterator.peek() {
None => true,
_ => false,
}
}
/** replaces the conents of func with the compilers body */
fn swap_function(&mut self, mut func: &mut FunctionObject) {
swap(&mut self.body, func);
// func
}
fn get_rule(token: &Token) -> ParseRule {
// ParseRule {
// prefix: Some(|self| self.grouping()),
// infix: None,
// precedence: Precedence::None,
// },
// let func: dyn FnMut(&mut Compiler<'_>) = &Self::grouping;
// store reference of callable function within self
// let func: &fn(&'a mut Compiler<'_>) = &Self::grouping as &fn(&'a mut Compiler<'_>);
// let func: fn(&mut Compiler) = unary;
match token {
Token::OpenParen => rule!(grouping, call, Call),
Token::OpenBrace => rule!(tabulate, call_table, None),
Token::Assign => rule!(void, void, None),
Token::Op(op) => match op {
Operator::Sub => rule!(unary, binary, Term),
Operator::Add => rule!(void, binary, Term),
Operator::Multiply => rule!(void, binary, Factor),
Operator::Divide => rule!(void, binary, Factor),
Operator::Not => rule!(unary, void, None),
Operator::NotEqual => rule!(void, binary, Equality),
Operator::Equal => rule!(void, binary, Equality),
Operator::Less => rule!(void, binary, Comparison),
Operator::LessEqual => rule!(void, binary, Comparison),
Operator::Greater => rule!(void, binary, Comparison),
Operator::GreaterEqual => rule!(void, binary, Comparison),
Operator::Concat => rule!(void, concat, Concat),
Operator::And => rule!(void, and, And),
Operator::Or => rule!(void, or, Or),
Operator::Length => rule!(unary, void, None),
_ => rule!(void, void, None),
},
Token::Identifier(_) => rule!(variable, void, None),
// Token::OpenBracket => rule!(void, indexer, Call),
Token::Integer(_) => rule!(integer, void, None),
Token::Number(_) => rule!(number, void, None),
Token::StringLiteral(_) => rule!(string, call_string, None),
Token::Nil => rule!(literal, void, None),
Token::True => rule!(literal, void, None),
Token::False => rule!(literal, void, None),
// Token::Bang => rule!(unary, void, None),
_ => rule!(void, void, None),
}
}
pub fn compile(&mut self, source: String) -> FunctionObject {
#[cfg(feature = "dev-out")]
{
let lexer = Lexer::new(source.to_owned());
lexer.for_each(|r| match r {
Ok(t) => {
println!("token {}", t.0);
}
Err(e) => println!("err {}", e),
});
}
let lexer = Lexer::new(source.to_owned());
self.iterator = lexer.peekable();
while !self.is_end() {
match declaration(self) {
Ok(()) => {}
Err(e) => {
self.push_error(e);
self.synchronize();
}
}
}
self.emit(OpCode::RETURN, (0, 0));
take(&mut self.body)
}
fn synchronize(&mut self) {
// TODO should we unwind or just dump it all?
// self.eat();
// while !self.is_end() {
// match self.get_current() {
// Ok(Token::Print) => return,
// _ => {}
// }
// self.eat();
// }
}
fn parse_precedence(&mut self, precedence: Precedence, skip_step: bool) -> Catch {
if !skip_step {
self.store();
}
// self.store(); // MARK with store first it works for normal statements, but it breaks for incomplete expressions that are meant to pop off
// Basically the integer we just saw is dropped off when we reach here because of store
let t = self.get_current()?;
let loc = self.current_location;
devout!("check rule for token {}", t);
let rule = Self::get_rule(&t);
// #[cfg(feature = "dev-out")]
devout!(
"target precedence: {}, current precedence: {}",
precedence,
rule.precedence,
);
// if (rule.prefix) != Self::void { // TODO bubble error up if no prefix, call invalid func to bubble?
let can_assign = precedence <= Precedence::Assignment;
(rule.prefix)(self, can_assign)?;
loop {
let c = self.peek_result();
let rule = match c {
Ok((Token::EOF, _)) => break,
Ok((t, _)) => Self::get_rule(t),
Err(e) => {
return Err(e.clone());
}
};
devout!(
"loop target precedence for : {}, current precedence for : {}",
precedence,
rule.precedence
);
if precedence > rule.precedence {
break;
}
self.store();
(rule.infix)(self, false)?;
}
// TODO test this with `local b="b" sprint b`
if can_assign
&& if let Token::Assign = self.peek()? {
true
} else {
false
}
{
let res = self.peek()?.clone();
return Err(self.error_at(SiltError::InvalidAssignment(res)));
}
// if skip_step {
// self.store();
// }
Ok(())
}
}
fn declaration(this: &mut Compiler) -> Catch {
devout!("----------------------------");
devnote!(this "declaration");
let t = this.peek()?;
match t {
Token::Local => declaration_keyword(this, true, false)?,
Token::Global => declaration_keyword(this, false, false)?,
Token::Function => {
this.eat();
define_function(this, true, None)?;
}
_ => statement(this)?,
}
Ok(())
}
fn declaration_keyword(this: &mut Compiler, local: bool, already_function: bool) -> Catch {
devnote!(this "declaration_keyword");
this.eat();
let (res, location) = this.pop();
match res? {
Token::Identifier(ident) => {
if this.scope_depth > 0 && local {
//local
//TODO should we warn? redefine_behavior(this,ident)?
add_local(this, ident)?;
typing(this, None)?;
} else {
let ident = this.identifer_constant(ident); //(self.global.to_register(&ident), 0);
typing(this, Some((ident, location)))?;
}
}
Token::Function => {
if !already_function {
define_function(this, local, None)?;
} else {
return Err(this.error_at(SiltError::ExpectedLocalIdentifier));
// Statement::InvalidStatement
}
}
// _ => {
// self.error(SiltError::ExpectedLocalIdentifier);
// Statement::InvalidStatement
// }
_ => todo!(),
}
Ok(())
}
fn declaration_scope(
this: &mut Compiler,
ident: Box<String>,
local: bool,
location: Location,
) -> Catch {
if this.scope_depth > 0 && local {
//local
//TODO should we warn? redefine_behavior(this,ident)?
add_local(this, ident)?;
typing(this, None)?;
} else {
let ident = this.identifer_constant(ident);
typing(this, Some((ident, location)))?;
}
Ok(())
}
// TODO Warning?
// fn redefine_behavior(this: &mut Compiler, ident: Box<String>) -> Catch {
// // TODO depth !=-1 ?
// for l in this.locals.iter().rev() {
// if l.depth != -1 && l.depth < this.scope_depth {
// return Ok(());
// } else {
// if l.ident == ident {
// return Err(this.error_at(SiltError::AlreadyDefined(ident)));
// }
// }
// }
// Ok(())
// }
/** Store location as a local to resolve getters with, the index pointing to the stack */
fn add_local(this: &mut Compiler, ident: Box<String>) -> Result<u8, ErrorTuple> {
_add_local(this, Some(ident))
}
/** Store location on the stack with a placeholder that cannot be resolved as a variable, only reserves for operations */
fn add_local_placeholder(this: &mut Compiler) -> Result<u8, ErrorTuple> {
_add_local(this, None)
}
fn _add_local(this: &mut Compiler, ident: Option<Box<String>>) -> Result<u8, ErrorTuple> {
devnote!(this "add_local");
if this.local_count == 255 {
return Err(this.error_at(SiltError::TooManyLocals));
}
this.local_count += 1;
this.locals.push(Local {
ident,
depth: this.scope_depth,
functional_depth: this.functional_depth,
is_captured: false,
});
let i = this.local_count - 1;
Ok(i as u8)
}
// /** Remove a single reserved local */
// fn pop_local(this: &mut Compiler) {
// devnote!(this "pop_local");
// this.local_count -= 1;
// this.locals.pop();
// }
fn resolve_local(this: &mut Compiler, ident: &Box<String>) -> Option<(u8, bool)> {
devnote!(this "resolve_local");
for (i, l) in this.locals.iter_mut().enumerate().rev() {
if let Some(local_ident) = &l.ident {
if local_ident == ident {
#[cfg(feature = "dev-out")]
println!("matched local {}->{} at {}", ident, local_ident, i);
let ident_byte = i as u8;
// first establish we're accessing a value by a closure, it exists outside this function
let is_upvalue = l.functional_depth < this.functional_depth;
return if is_upvalue {
(*l).is_captured = true;
let offset_ident = if l.functional_depth > 0 {
let offset = this.local_functional_offset[l.functional_depth - 1];
i - offset
} else {
i
} as u8;
// MARK we're passing in a target depth of 0, huh?? that's global isnt it? our upvals dont exist there
Some((
resolve_upvalue(
&mut this.up_values,
ident_byte,
offset_ident,
this.functional_depth,
l.functional_depth,
),
is_upvalue,
))
} else {
let offset_ident = if this.functional_depth > 0 {
let offset = this.local_functional_offset[this.functional_depth - 1];
i - offset
} else {
i
} as u8;
Some((offset_ident as u8, false))
};
}
}
}
None
}
// fn add_upvalue(this: &mut Compiler, ident: u8, neighboring: bool) -> u8 {
// let m = this.up_values.last_mut().unwrap();
// let i = m.len();
// m.push(UpLocal { ident, neighboring });
// i as u8
// }
// fn register_upvalue_at(this: &mut Compiler, ident: u8, neighboring: bool, level: usize) -> u8 {
// let mut m = &mut this.up_values[level];
// let i = m.len();
// m.push(UpLocal { ident, neighboring });
// i as u8
// }
/** check if upvalue is registered at this closest level and decend down until reach destination, registiner upvalues as we go if not already*/
fn resolve_upvalue(
up_values: &mut Vec<Vec<UpLocal>>,
ident: u8,
scoped_ident: u8,
level: usize,
target: usize,
) -> u8 {
let m = &mut up_values[level];
for (u, i) in m.iter().enumerate() {
if i.universal_ident == ident {
return u as u8;
}
}
// if level is equal to or no greater than target +1
if level <= target + 1 {
m.push(UpLocal {
ident: scoped_ident,
universal_ident: ident,
neighboring: true,
});
(m.len() - 1) as u8
} else {
// drop(m);
let higher = resolve_upvalue(up_values, ident, scoped_ident, level - 1, target);
let m = &mut up_values[level];
m.push(UpLocal {
ident: higher,
universal_ident: ident,
neighboring: false,
});
(m.len() - 1) as u8
// resolve_upvalue(up_values, ident, level - 1, target)
}
}
// fn resolve_upvalue(this: &mut Compiler, ident: &Box<String>) -> Result<Option<u8>, ErrorTuple> {
// devnote!(this "resolve_upvalue");
// if this.scope_depth == 0 {
// return Ok(None);
// }
// if let Some(local) = resolve_local(this, ident)? {
// return Ok(Some(add_upvalue(this, local, true)?));
// }
// if let Some(upvalue) = this.body.upvalues.iter().position(|u| u.0 == ident) {
// return Ok(Some(upvalue as u8));
// }
// Ok(None)
// }
fn typing(this: &mut Compiler, ident_tuple: Option<(Ident, Location)>) -> Catch {
devnote!(this "typing");
if let Token::Colon = this.peek()? {
// typing or self calling
this.eat();
this.store();
let t = this.get_current()?;
if let Token::ColonIdentifier(target) = t {
// method or type name
// if let Some(&Token::OpenParen) = self.peek() {
// // self call
// Statement::InvalidStatement
// } else {
// // typing
// // return self.assign(self.peek(), ident);
// Statement::InvalidStatement
// }
define_declaration(this, ident_tuple)?;
} else {
todo!("typing");
// self.error(SiltError::InvalidColonPlacement);
// Statement::InvalidStatement
}
} else {
define_declaration(this, ident_tuple)?;
}
Ok(())
}
fn define_declaration(this: &mut Compiler, ident_tuple: Option<(Ident, Location)>) -> Catch {
devnote!(this "define_declaration");
this.store();
let t = this.get_current()?;
match t {
Token::Assign => {
expression(this, false)?;
}
// we can't increment what doesn't exist yet, like what are you even doing?
Token::AddAssign
| Token::SubAssign
| Token::MultiplyAssign
| Token::DivideAssign
| Token::ModulusAssign => {
// let tt = t.unwrap().clone(); // TODO
// self.error(SiltError::InvalidAssignment(tt));
// Statement::InvalidStatement
todo!()
}
_ => this.emit_at(OpCode::NIL), // TODO are more then just declarations hitting this syntactic sugar?
}
define_variable(this, ident_tuple)?;
Ok(())
}
fn define_variable(this: &mut Compiler, ident: Option<(Ident, Location)>) -> Catch {
devnote!(this "define_variable");
if let Some(ident) = ident {
this.emit(OpCode::DEFINE_GLOBAL { constant: ident.0 }, ident.1);
}
Ok(())
}
fn define_function(this: &mut Compiler, local: bool, pre_ident: Option<usize>) -> Catch {
let (ident, location) = if let &Token::Identifier(_) = this.peek()? {
let (res, location) = this.pop();
if let Token::Identifier(ident) = res? {
(ident, location)
} else {
unreachable!()
}
} else {
(Box::new("anonymous".to_string()), this.current_location)
};
let ident_clone = *ident.clone();
let global_ident = if this.scope_depth > 0 && local {
//local
//TODO should we warn? redefine_behavior(this,ident)?
add_local(this, ident)?;
None
} else {
let ident = Some((this.identifer_constant(ident), location));
ident
};
build_function(this, ident_clone, global_ident, false, false)?;
Ok(())
}
/** builds function, implicit return specifices whether a nil is return or the last value popped */
fn build_function(
this: &mut Compiler,
ident: String,
global_ident: Option<(u8, Location)>,
is_script: bool,
implicit_return: bool,
) -> Catch {
// TODO this function could be called called rercursivelly due to the recursive decent nature of the parser, we should add a check to make sure we don't overflow the stack
devnote!(this "build_function");
let mut sidelined_func = FunctionObject::new(Some(ident), is_script);
this.swap_function(&mut sidelined_func);
begin_scope(this);
begin_functional_scope(this);
expect_token!(this OpenParen);
let mut arity = 0;
if let Token::Identifier(_) = this.peek()? {
arity += 1;
build_param(this)?;
while let Token::Comma = this.peek()? {
this.eat();
arity += 1;
if arity > 255 {
// TODO we should use an arity value on the function object but let's make it only exist on compile time
return Err(this.error_at(SiltError::TooManyParameters));
}
build_param(this)?;
}
}
block(this)?;
if let &OpCode::RETURN = this.read_last_code() {
} else {
// TODO if last was semicolon we also push a nil
if !implicit_return {
this.emit_at(OpCode::NIL);
}
this.emit_at(OpCode::RETURN);
}
// TODO why do we need to eat again? This prevents an expression_statement of "End" being called but block should have eaten it?
// if let Token::End = this.peek()? {
// this.eat();
// }
end_scope(this, true);
let upvals = end_functional_scope(this);
// When we're done compiling the function object we drop the current body function back in and push the compiled func as a constant within that body
this.swap_function(&mut sidelined_func);
sidelined_func.upvalue_count = upvals.len() as u8;
let func_value = Value::Function(Rc::new(sidelined_func));
if true {
// need closure
let constant = this.body.chunk.write_constant(func_value) as u8;
this.emit_at(OpCode::CLOSURE { constant });
// emit upvalues
for val in upvals.iter() {
// TODO is it worth specifying difference between first function enclosure from higher functional enclosure?
this.emit_at(OpCode::REGISTER_UPVALUE {
index: val.ident,
neighboring: val.neighboring,
});
}
} else {
// no closure needed
this.constant_at(func_value);
}
define_variable(this, global_ident)?;
Ok(())
}
fn build_param(this: &mut Compiler) -> Catch {
let (res, _) = this.pop();
match res? {
Token::Identifier(ident) => {
add_local(this, ident)?;
}
_ => {
return Err(this.error_at(SiltError::ExpectedLocalIdentifier));
}
}
Ok(())
}
fn statement(this: &mut Compiler) -> Catch {
devnote!(this "statement");
match this.peek()? {
Token::Print => print(this)?,
Token::If => if_statement(this)?,
Token::Do => {
this.eat();
begin_scope(this);
block(this)?;
end_scope(this, false);
}
Token::While => while_statement(this)?,
Token::For => for_statement(this)?,
Token::Return => return_statement(this)?,
// Token::OpenBrace => block(this),
Token::ColonColon => set_goto_label(this)?,
Token::Goto => goto_statement(this)?,
Token::SemiColon => {
this.eat();
// TODO ???
}
// Token::End => {
// // this.eat();
// // TODO ???
// }
_ => expression_statement(this)?,
}
Ok(())
}
fn block(this: &mut Compiler) -> Catch {
devnote!(this "block");
build_block_until!(this, End);
Ok(())
}
/** lower scope depth */
fn begin_scope(this: &mut Compiler) {
this.scope_depth += 1;
}
/** Descend into a function's scope and start a new upvalue vec representing required values a level above us */
fn begin_functional_scope(this: &mut Compiler) {
this.functional_depth += 1;
this.up_values.push(vec![]);
this.local_functional_offset.push(this.local_count);
}
/** raise scope depth and dump lowest locals off the imaginary stack */
fn end_scope(this: &mut Compiler, skip_code: bool) {
this.scope_depth -= 1;
let mut last_was_pop = true;
let mut count = 0;
let mut v = vec![];
while !this.locals.is_empty() && this.locals.last().unwrap().depth > this.scope_depth {
let l = this.locals.pop().unwrap();
if l.is_captured {
if last_was_pop {
v.push(count);
count = 0;
}
last_was_pop = false;
count += 1;
} else {
if !last_was_pop {
v.push(count);
count = 0;
}
last_was_pop = true;
count += 1;
}
}
if count > 0 {
v.push(count);
}
// if we're not dealing with upvalues and we're skipping code due to functional scope our stack will get moved off anyway
if skip_code {
//&& v.len() <= 1 {
return;
}
// index 0 is always OP_POPS but could be count of 0 if the first local is captured. Otherwise we can safely stagger even as pop, odds as close
v.iter().enumerate().for_each(|(i, c)| {
if i % 2 == 0 {
this.emit_at(OpCode::POPS(*c));
} else {
this.emit_at(OpCode::CLOSE_UPVALUES(*c));
}
});
}
/** raise functional depth */
fn end_functional_scope(this: &mut Compiler) -> Vec<UpLocal> {
this.functional_depth -= 1;
this.local_functional_offset.pop();
this.up_values.pop().unwrap()
}
fn if_statement(this: &mut Compiler) -> Catch {
devnote!(this "if_statement");
this.eat();
expression(this, false)?;
expect_token!(this Then);
let index = this.emit_index(OpCode::GOTO_IF_FALSE(0));
this.emit_at(OpCode::POP);
build_block_until!(this, End | Else | ElseIf);
// let else_jump = this.emit_index(OpCode::FORWARD(0));
this.patch(index)?;
this.emit_at(OpCode::POP);
match this.peek()? {
Token::Else => {
this.eat();
let index = this.emit_index(OpCode::FORWARD(0));
build_block_until!(this, End);
this.patch(index)?;
}
Token::ElseIf => {
this.eat();
this.emit_at(OpCode::POP);
if_statement(this)?;
}
_ => {}
}
Ok(())
}
fn while_statement(this: &mut Compiler) -> Catch {
devnote!(this "while_statement");
this.eat();
let loop_start = this.get_chunk_size();
expression(this, false)?;
expect_token!(this Do);
let exit_jump = this.emit_index(OpCode::GOTO_IF_FALSE(0));
this.emit_at(OpCode::POP);
build_block_until!(this, End);
this.emit_rewind(loop_start);
this.patch(exit_jump)?;
this.emit_at(OpCode::POP);
Ok(())
}
fn for_statement(this: &mut Compiler) -> Catch {
devnote!(this "for_statement");
this.eat();
let pair = this.pop();
let t = pair.0?;
if let Token::Identifier(ident) = t {
begin_scope(this);
let iterator = add_local(this, ident)?; // reserve iterator by identifier
expect_token!(this Assign);
let comparison = add_local_placeholder(this)?; // reserve end value with placeholder
let step_value = add_local_placeholder(this)?; // reserve step value with placeholder
expression(this, false)?; // expression for iterator
expect_token!(this Comma);
expression(this, false)?; // expression for end value
// let exit_jump = this.emit_index(OpCode::GOTO_IF_FALSE(0));
// this.emit_at(OpCode::POP);
// either we have an expression for the step or we set it to 1i
if let Token::Comma = this.peek()? {
this.eat();
expression(this, false)?;
} else {
this.constant_at(Value::Integer(1))
};
this.emit_at(OpCode::GET_LOCAL { index: iterator });
let loop_start = this.get_chunk_size();
// compare iterator to end value
this.emit_at(OpCode::GET_LOCAL { index: comparison });
this.emit_at(OpCode::EQUAL);
let exit_jump = this.emit_index(OpCode::GOTO_IF_TRUE(0));
this.emit_at(OpCode::POP);
expect_token!(this Do);
// this.emit_at(OpCode::POP);
// statement(this)?;
build_block_until!(this, End);
this.emit_at(OpCode::GET_LOCAL { index: iterator });
this.emit_at(OpCode::GET_LOCAL { index: step_value });
this.emit_at(OpCode::ADD);
this.emit_at(OpCode::SET_LOCAL { index: iterator });
this.emit_rewind(loop_start);
this.patch(exit_jump)?;
this.emit_at(OpCode::POP);
end_scope(this, false);
Ok(())
} else {
Err(this.error_at(SiltError::ExpectedLocalIdentifier))
}
}
fn return_statement(this: &mut Compiler) -> Catch {
devnote!(this "return_statement");
this.eat();
if let Token::End | Token::EOF = this.peek()? {
this.emit_at(OpCode::NIL);
} else {
expression(this, false)?;
}
this.emit_at(OpCode::RETURN);
Ok(())
}
fn set_goto_label(this: &mut Compiler) -> Catch {
devnote!(this "goto_label");
this.eat();
let token = this.pop().0?;
if let Token::Identifier(ident) = token {
this.labels.insert(*ident, this.get_chunk_size());
} else {
return Err(this.error_at(SiltError::ExpectedLabelIdentifier));
}
Ok(())
}
fn goto_statement(this: &mut Compiler) -> Catch {
devnote!(this "goto_statement");
this.eat();
let token = this.pop().0?;
if let Token::Identifier(ident) = token {
resolve_goto(this, &*ident, this.get_chunk_size(), None)?;
// match this.labels.get(ident) {
// Some(i) => {
// let c = this.chunk.code.len();
// let o = *i;
// if c > o {
// let offset = c - o;
// if offset > u16::MAX as usize {
// return Err(this.error_at(SiltError::TooManyOperations));
// }
// this.emit_at(OpCode::REWIND(offset as u16));
// } else {
// let offset = o - c;
// if offset > u16::MAX as usize {
// return Err(this.error_at(SiltError::TooManyOperations));
// }
// this.emit_at(OpCode::FORWARD(offset as u16));
// }
// }
// None => {
// let index = this.emit_index(OpCode::FORWARD(0));
// this.pending_gotos.push((ident, index));
// // this.labels.insert(*ident, index);
// }
// }
} else {
return Err(this.error_at(SiltError::ExpectedGotoIdentifier));
}
// n end_scope(this: &mut Compiler) {
// this.scope_depth -= 1;
// let mut i = 0;
// while !this.locals.is_empty() && this.locals.last().unwrap().depth > this.scope_depth {
// this.locals.pop();
// i += 1;
// }
// this.emit_at(OpCode::POPN(i));
// }
Ok(())
}
fn resolve_goto(
this: &mut Compiler,
ident: &str,
op_count: usize,
replace: Option<(usize, Location)>,
) -> Catch {
match this.labels.get(ident) {
Some(i) => {
let c = op_count;
let o = *i;
let code = if c > o {
let offset = c - o;
if offset > u16::MAX as usize {
return Err(this.error_at(SiltError::TooManyOperations));
}
OpCode::REWIND(offset as u16)
} else {
let offset = o - c;
if offset > u16::MAX as usize {
return Err(this.error_at(SiltError::TooManyOperations));
}
OpCode::FORWARD(offset as u16)
};
match replace {
Some((i, _)) => {
this.get_chunk_mut().code[i] = code;
}
None => {
this.emit_at(code);
}
}
}
None => match replace {
Some((i, location)) => {
return Err(this.error_syntax(SiltError::UndefinedLabel(ident.to_owned()), location))
}
None => {
let index = this.emit_index(OpCode::FORWARD(0));
this.pending_gotos
.push((ident.to_owned(), index, this.current_location));
} // this.labels.insert(*ident, index);
},
};
Ok(())
}
fn final_resolve_goto(this: &mut Compiler) {
this.pending_gotos
.iter()
.for_each(|(ident, index, location)| {});
}
fn goto_scope_skip(this: &mut Compiler) {
if this.locals.is_empty() {
return;
}
let mut i = 0;
this.locals
.iter()
.rev()
.take_while(|l| l.depth > this.scope_depth)
.for_each(|_| {
i += 1;
});
this.emit_at(OpCode::POPS(i));
}
fn expression(this: &mut Compiler, skip_step: bool) -> Catch {
devnote!(this "expression");
this.parse_precedence(Precedence::Assignment, skip_step)?;
Ok(())
}
fn next_expression(this: &mut Compiler) -> Catch {
devnote!(this "next_expression");
this.eat();
expression(this, false)?;
Ok(())
}
fn expression_statement(this: &mut Compiler) -> Catch {
devnote!(this "expression_statement");
expression(this, false)?;
if this.override_pop {
this.override_pop = false;
} else {
this.emit_at(OpCode::POP);
}
devnote!(this "expression_statement end");
Ok(())
}
fn variable(this: &mut Compiler, can_assign: bool) -> Catch {
devnote!(this "variable");
// let t = this.previous.clone();
// let ident = if let Token::Identifier(ident) = t.0 {
// this.identifer_constant(ident)
// } else {
// unreachable!()
// };
// if let Some(Ok((Token::Assign, _))) = this.peek() {
// this.advance();
// next_expression(this);
// this.emit(OpCode::DEFINE_GLOBAL { constant: ident }, t.1);
// } else {
// this.emit(OpCode::LITERAL { dest: ident, literal: ident }, t.1);
// }
named_variable(this, can_assign, false)?;
Ok(())
}
fn named_variable(this: &mut Compiler, can_assign: bool, mut local: bool) -> Catch {
devnote!(this "named_variables");
let t = this.copy_store()?;
// declare shortcut only valid if we're above scope 0 otherwise it's redundant
// TODO should we send a warning that 0 scoped declares are redundant?
if this.scope_depth > 0
&& if let Token::Op(Operator::ColonEquals) = this.peek()? {
true
} else {
false
}
{
if let Token::Identifier(ident) = t {
// short declare
add_local(this, ident)?;
this.override_pop = true;
this.eat();
expression(this, false)?;
} else {
unreachable!()
}
return Ok(());
}
//normal assigment
let (setter, getter) = if let Token::Identifier(ident) = t {
devout!("assigning to identifier: {}", ident);
// TODO currently this mechanism searches the entire local stack to determine local and then up values, ideally we check up values first once we raise out of the functional scope instead of continuing to walk the local stack, but this will work for now.
match resolve_local(this, &ident) {
Some((i, is_up)) => {
if is_up {
(
OpCode::SET_UPVALUE { index: i },
OpCode::GET_UPVALUE { index: i },
)
} else {
(
OpCode::SET_LOCAL { index: i },
OpCode::GET_LOCAL { index: i },
)
}
}
None => {
let ident = this.identifer_constant(ident);
// add_upvalue(this, ident, this.scope_depth);
(
OpCode::SET_GLOBAL { constant: ident },
OpCode::GET_GLOBAL { constant: ident },
)
}
}
} else {
unreachable!()
};
/*
* normally:
* expression for value
* set_var id
*
* with table:
* push table ref onto stack
* expression for index OR constant for index
* repeat for each chained index and remember count
* expression for value
* set_table with depth = index count
*
*
*/
match this.peek()? {
Token::Assign => {
if can_assign {
this.eat();
expression(this, false)?;
this.emit_at(setter);
} else {
this.emit_at(getter);
}
}
Token::OpenBracket | Token::Dot => {
this.emit_at(getter);
let count = table_indexer(this)? as u8;
if let Token::Assign = this.peek()? {
this.eat();
expression(this, false)?;
this.emit_at(OpCode::TABLE_SET { depth: count });
// override statement end pop because instruction takes care of it
this.override_pop = true;
} else {
this.emit_at(OpCode::TABLE_GET { depth: count });
}
}
_ => this.emit_at(getter),
}
// if can_assign
// && if let Token::Assign = this.peek()? {
// true
// } else {
// false
// }
// {
// this.eat();
// expression(this, false)?;
// this.emit_at(setter);
// } else {
// this.emit_at(getter);
// }
// if let &Token::Assign = this.get_current()? {
// let loc = this.current_location;
// expression(this, false)?;
// this.emit(OpCode::DEFINE_GLOBAL { constant: ident }, loc);
// } else {
// this.emit_at(OpCode::GET_GLOBAL { constant: ident });
// }
Ok(())
}
fn grouping(this: &mut Compiler, _can_assign: bool) -> Catch {
devnote!(this "grouping");
expression(this, false)?;
//TODO expect
// expect_token!(self, CloseParen, SiltError::UnterminatedParenthesis(0, 0));
// self.consume(TokenType::RightParen, "Expect ')' after expression.");
Ok(())
}
fn tabulate(this: &mut Compiler, _can_assign: bool) -> Catch {
devnote!(this "tabulate");
this.emit_at(OpCode::NEW_TABLE);
// not immediately closed
if !matches!(this.peek()?, &Token::CloseBrace) {
let mut count = 0;
// check if index provided via brackets or ident, otherwise increment our count to build array at the end
while {
let start_brace = this.current_location;
if match this.peek()? {
Token::Identifier(_) => {
this.store();
if let Token::Assign = this.peek()? {
let ident = this.get_current()?.unwrap_identifier();
this.emit_identifer_constant_at(ident.clone());
this.eat();
true
} else {
expression(this, true)?; // we skip the store because the ip is already where it needs to be
false
}
}
Token::OpenBracket => {
this.eat();
expression(this, false)?;
expect_token!(
this,
CloseBracket,
this.error_at(SiltError::UnterminatedBracket(start_brace.0, start_brace.1))
);
expect_token!(this, Assign, this.error_at(SiltError::ExpectedAssign));
true
}
_ => {
expression(this, false)?; // normal store expression
false
}
} {
expression(this, false)?;
this.emit_at(OpCode::TABLE_INSERT { offset: count });
} else {
count += 1;
}
match this.peek()? {
Token::Comma => {
this.eat();
true
}
Token::CloseBrace => false,
_ => return Err(this.error_at(SiltError::TableExpectedCommaOrCloseBrace)),
}
} {
// if args >= 255 {
// return Err(this.error_at(SiltError::TooManyParameters));
// }
}
if count > 0 {
this.emit_at(OpCode::TABLE_BUILD(count));
}
}
expect_token!(
this,
CloseBrace,
this.error_at(SiltError::TableExpectedCommaOrCloseBrace)
);
Ok(())
}
/** op unary or primary */
fn unary(this: &mut Compiler, _can_assign: bool) -> Catch {
devnote!(this "unary");
let t = this.copy_store()?;
// self.expression();
this.parse_precedence(Precedence::Unary, false)?;
match t {
Token::Op(Operator::Sub) => this.emit_at(OpCode::NEGATE),
Token::Op(Operator::Not) => this.emit_at(OpCode::NOT),
Token::Op(Operator::Length) => this.emit_at(OpCode::LENGTH),
_ => {}
}
// let operator = Self::de_op(self.eat_out());
// let location = self.get_last_loc();
// let right = self.unary();
// Expression::Unary {
// operator,
// right: Box::new(right),
// location,
// }
// } else {
// self.anonymous_check()
// }
Ok(())
}
fn table_indexer(this: &mut Compiler) -> Result<usize, ErrorTuple> {
let mut count = 0;
while match this.peek()? {
Token::OpenBracket => {
this.eat();
expression(this, false)?;
expect_token!(
this,
CloseBracket,
this.error_at(SiltError::UnterminatedBracket(0, 0))
);
true
}
Token::Dot => {
this.eat();
let t = this.pop();
this.current_location = t.1;
let field = t.0?;
devout!("table_indexer: {} p:{}", field, this.peek()?);
if let Token::Identifier(ident) = field {
this.emit_identifer_constant_at(ident);
} else {
return Err(this.error_at(SiltError::ExpectedFieldIdentifier));
}
true
}
_ => false,
} {
count += 1;
}
Ok(count)
}
fn binary(this: &mut Compiler, _can_assign: bool) -> Catch {
devnote!(this "binary");
let t = this.copy_store()?;
let l = this.current_location;
let rule = Compiler::get_rule(&t);
this.parse_precedence(rule.precedence.next(), false)?;
if let Token::Op(op) = t {
match op {
Operator::Add => this.emit(OpCode::ADD, l),
Operator::Sub => this.emit(OpCode::SUB, l),
Operator::Multiply => this.emit(OpCode::MULTIPLY, l),
Operator::Divide => this.emit(OpCode::DIVIDE, l),
Operator::Concat => this.emit(OpCode::CONCAT, l),
// Operator::Modulus => self.emit(OpCode::MODULUS, t.1),
// Operator::Equal => self.emit(OpCode::EQUAL, t.1),
Operator::Equal => this.emit(OpCode::EQUAL, l),
Operator::NotEqual => this.emit(OpCode::NOT_EQUAL, l),
Operator::Less => this.emit(OpCode::LESS, l),
Operator::LessEqual => this.emit(OpCode::LESS_EQUAL, l),
Operator::Greater => this.emit(OpCode::GREATER, l),
Operator::GreaterEqual => this.emit(OpCode::GREATER_EQUAL, l),
_ => todo!(),
}
}
Ok(())
}
fn concat(this: &mut Compiler, _can_assign: bool) -> Catch {
devnote!(this "concat_binary");
let t = this.copy_store()?;
let l = this.current_location;
let rule = Compiler::get_rule(&t);
this.parse_precedence(rule.precedence.next(), false)?;
if let Token::Op(op) = t {
match op {
Operator::Concat => this.emit(OpCode::CONCAT, l),
_ => todo!(),
}
}
Ok(())
}
fn and(this: &mut Compiler, _can_assign: bool) -> Catch {
devnote!(this "and");
let index = this.emit_index(OpCode::GOTO_IF_FALSE(0));
this.emit_at(OpCode::POP);
this.parse_precedence(Precedence::And, false)?;
this.patch(index)?;
Ok(())
}
fn or(this: &mut Compiler, _can_assign: bool) -> Catch {
devnote!(this "or");
// the goofy way
// let index = this.emit_index(OpCode::GOTO_IF_FALSE(0));
// let final_index = this.emit_index(OpCode::GOTO(0));
// this.patch(index)?;
// this.emit_at(OpCode::POP);
// this.parse_precedence(Precedence::Or, false)?;
// this.patch(final_index)?;
let index = this.emit_index(OpCode::GOTO_IF_TRUE(0));
this.emit_at(OpCode::POP);
this.parse_precedence(Precedence::Or, false)?;
this.patch(index)?;
Ok(())
}
fn integer(this: &mut Compiler, can_assign: bool) -> Catch {
devnote!(this "integer");
let t = this.copy_store()?;
let value = if let Token::Integer(i) = t {
Value::Integer(i)
} else {
unreachable!()
};
this.constant_at(value);
Ok(())
}
fn number(this: &mut Compiler, can_assign: bool) -> Catch {
devnote!(this "number");
let t = this.copy_store()?;
let value = if let Token::Number(n) = t {
Value::Number(n)
} else {
unreachable!()
};
this.constant_at(value);
Ok(())
}
fn string(this: &mut Compiler, can_assign: bool) -> Catch {
devnote!(this "string");
let t = this.copy_store()?;
let value = if let Token::StringLiteral(s) = t {
Value::String(Box::new(s.into_string()))
} else {
unreachable!()
};
this.constant_at(value);
Ok(())
}
fn literal(this: &mut Compiler, can_assign: bool) -> Catch {
devnote!(this "literal");
let t = this.copy_store()?;
match t {
Token::Nil => this.emit_at(OpCode::NIL),
Token::True => this.emit_at(OpCode::TRUE),
Token::False => this.emit_at(OpCode::FALSE),
_ => unreachable!(),
}
Ok(())
}
fn call(this: &mut Compiler, can_assign: bool) -> Catch {
devnote!(this "call");
// let t = this.take_store()?;
// let l = this.current_location;
// let rule = Compiler::get_rule(&t);
// this.parse_precedence(rule.precedence.next(), false)?;
// if let Token::OpenParen = t {
// let arg_count = this.argument_list()?;
// this.emit(OpCode::CALL { arg_count }, l);
// }
let start = this.current_location;
let arg_count = arguments(this, start)?;
this.emit(OpCode::CALL(arg_count), start);
Ok(())
}
fn call_table(this: &mut Compiler, can_assign: bool) -> Catch {
todo!();
Ok(())
}
fn call_string(this: &mut Compiler, can_assign: bool) -> Catch {
todo!();
Ok(())
}
fn arguments(this: &mut Compiler, start: Location) -> Result<u8, ErrorTuple> {
devnote!(this "arguments");
let mut args = 0;
if !matches!(this.peek()?, &Token::CloseParen) {
while {
expression(this, false)?;
args += 1;
if let &Token::Comma = this.peek()? {
this.eat();
true
} else {
false
}
} {
if args >= 255 {
return Err(this.error_at(SiltError::TooManyParameters));
}
}
}
expect_token!(
this,
CloseParen,
this.error_at(SiltError::UnterminatedParenthesis(start.0, start.1))
);
devout!("arguments count: {}", args);
Ok(args)
}
fn print(this: &mut Compiler) -> Catch {
devnote!(this "print");
this.eat();
expression(this, false)?;
this.emit_at(OpCode::PRINT);
Ok(())
}
pub fn void(_this: &mut Compiler, _can_assign: bool) -> Catch {
devnote!(_this "void");
Ok(())
}
// pub fn invalid(_: &mut Compiler) { // TODO
// // this.error(SiltError::InvalidExpression);
// }
// declare
// if var return declare_staement
// return statement
// declare_statement
// eat identifier
// if equal then expresion
// otherwise return as nil binary assign
// ======
// ======
// ======
// ======
// fn assigner(&mut self, ident: Ident) -> Expression {
// let tok = self.eat_out();
// let location = self.get_last_loc();
// match tok {
// Token::Assign => Expression::Assign {
// ident,
// value: Box::new(self.expression()),
// location,
// },
// Token::AddAssign => {
// op_assign!(self, ident, Add)
// }
// Token::SubAssign => {
// op_assign!(self, ident, Sub)
// }
// Token::MultiplyAssign => {
// op_assign!(self, ident, Multiply)
// }
// Token::DivideAssign => {
// op_assign!(self, ident, Divide)
// }
// Token::ModulusAssign => {
// op_assign!(self, ident, Modulus)
// }
// _ => panic!("impossible"), //Statement::Expression(Expression::Variable {ident})
// }
// }