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
//! The Molt Interpreter //! //! TODO: This should be primary documentation on using the Molt Interp. //! //! The [`Interp`] struct is the primary API for embedding Molt into a Rust application. //! Given an `Interp`, the application may: //! //! * Evaluate scripts //! * Check scripts for completeness //! * Extend the language by defining new Molt commands in Rust //! * Set and get Molt variables in command bodies //! * Interpret Molt values as a variety of data types. //! * Access application data the context cache //! //! The following describes the features of the [`Interp`] in general; follow the links for //! specifics of the various types and methods. //! //! # Interp is not Sync! //! //! The `Interp` class (and the rest of Molt) is intended for use in a single thread. It is //! safe to have multiple `Interps` in different threads; but use `String` (or another `Sync`) //! when passing data between them. In particular, `Value` is not `Sync`. //! //! # Creating an Interpreter //! //! There are two ways to create an interpreter. The usual way is to call //! [`Interp::new`](struct.Interp.html#method.new), which creates an interpreter and populates //! it with all of the standard Molt commands. Alternatively, //! [`Interp::empty`](struct.Interp.html#method.empty) creates an interpreter with no commands, //! allowing the application to define only those commands it needs. This is useful when the goal //! is to provide the application with a simple, non-scriptable console command set. //! //! TODO: Define a way to add various subsets of the standard commands to an initially //! empty interpreter. //! //! ``` //! use molt::Interp; //! let mut interp = Interp::new(); //! // ... //! ``` //! //! # Evaluating Scripts //! //! There are a number of ways to evaluate Molt scripts, all of which return [`MoltResult`]: //! //! ```ignore //! pub type MoltResult = Result<Value, ResultCode>; //! ``` //! //! [`Value`] is the type of all Molt values (i.e., values that can be passed as parameters and //! stored in variables). [`ResultCode`] is an enum that encompasses all of the kinds of //! exceptional return from Molt code, including errors, `return`, `break`, and `continue`. //! //! [`Interp::eval`](struct.Interp.html#method.eval) and //! [`Interp::eval_value`](struct.Interp.html#method.eval_value) evaluate a string as a Molt //! script, and return either a normal `Value` or a Molt error. The script is evaluated in //! the caller's context: if called at the application level, the script will be evaluated in //! the interpreter's global scope; if called by a Molt command, it will be evaluated in the //! scope in which that command is executing. //! //! [`Interp::eval_body`](struct.Interp.html#method.eval_body) is used to evaluate the body //! of loops and other control structures. Unlike `Interp::eval`, it passes the //! `return`, `break`, and `continue` result codes back to the caller for handling. //! //! # Evaluating Expressions //! //! In Molt, as in Standard Tcl, algebraic expressions are evaluated by the `expr` command. At //! the Rust level this feature is provided by the //! [`Interp::expr`](struct.Interp.html#method.expr) method, which takes the expression as a //! [`Value`] and returns the computed `Value` or an error. //! //! There are three convenience methods, //! [`Interp::expr_bool`](struct.Interp.html#method.expr_bool), //! [`Interp::expr_int`](struct.Interp.html#method.expr_int), and //! [`Interp::expr_float`](struct.Interp.html#method.expr_float), which streamline the computation //! of a particular kind of value, and return an error if the computed result is not of that type. //! //! # Checking Scripts for Completeness //! //! The [`Interp::complete`](struct.Interp.html#method.complete) checks whether a Molt script is //! complete: i.e., that it contains no unterminated quoted or braced strings that //! would prevent it from being evaluated as Molt code. This is primarily useful when //! implementing a Read-Eval-Print-Loop, as it allows the REPL to easily determine whether it //! should evaluate the input immediately or ask for an additional line of input. //! //! # Defining New Commands //! //! The usual reason for embedding Molt in an application is to extend it with //! application-specific commands. There are a number of ways to do this. //! //! The simplest method, and the one used by most of Molt's built-in commands, is to define a //! [`CommandFunc`] and register it with the interpreter using the //! [`Interp::add_command`](struct.Interp.html#method.add_command) method: //! //! ```pub type CommandFunc = fn(&mut Interp, &[Value]) -> MoltResult;``` //! //! A `CommandFunc` is simply a Rust function that accepts an interpreter and a slice of Molt //! [`Value`] objects and returns a [`MoltResult`]. The slice of [`Value`] objects represents //! the name of the command and its arguments, which the function may interpret in any way it //! desires. //! //! TODO: describe context commands and command objects. //! //! TODO: flesh out Molt's ensemble command API, and then describe how to define ensemble commands. //! //! [`MoltResult`]: ../types/struct.MoltResult.html //! [`ResultCode`]: ../types/struct.ResultCode.html //! [`CommandFunc`]: ../types/struct.CommandFunc.html //! [`Value`]: ../Value/struct.Value.html //! [`Interp`]: struct.Interp.html use crate::commands; use crate::eval_ptr::EvalPtr; use crate::expr; use crate::molt_err; use crate::molt_ok; use crate::parser; use crate::parser::Script; use crate::parser::Word; use crate::scope::ScopeStack; use crate::types::Command; use crate::types::*; use crate::util::is_varname_char; use crate::value::Value; use std::any::Any; use std::collections::HashMap; use std::rc::Rc; use std::time::Instant; /// The Molt Interpreter. /// /// The `Interp` struct is the primary API for /// embedding Molt into a Rust application. The application creates an instance /// of `Interp`, configures with it the required set of application-specific /// and standard Molt commands, and then uses it to evaluate Molt scripts and /// expressions. /// /// # Example /// /// By default, the `Interp` comes configured with the full set of standard /// Molt commands. /// /// ``` /// # use molt::types::*; /// # use molt::Interp; /// # use molt::molt_ok; /// # fn dummy() -> MoltResult { /// let mut interp = Interp::new(); /// let four = interp.eval("expr {2 + 2}")?; /// assert_eq!(four, Value::from(4)); /// # molt_ok!() /// # } /// ``` #[derive(Default)] #[allow(dead_code)] // TEMP pub struct Interp { // Command Table commands: HashMap<String, Rc<dyn Command>>, // Variable Table scopes: ScopeStack, // Context ID Counter last_context_id: u64, // Context Map context_map: HashMap<ContextID, Box<dyn Any>>, // Defines the recursion limit for Interp::eval(). recursion_limit: usize, // Current number of eval levels. num_levels: usize, // Profile Map profile_map: HashMap<String, ProfileRecord>, } struct ProfileRecord { count: u128, nanos: u128, } impl ProfileRecord { fn new() -> Self { Self { count: 0, nanos: 0 } } } // NOTE: The order of methods in the generated RustDoc depends on the order in this block. // Consequently, methods are ordered pedagogically. impl Interp { //-------------------------------------------------------------------------------------------- // Constructors /// Creates a new Molt interpreter with no commands defined. Use this when crafting /// command languages that shouldn't include the normal TCL commands, or as a base /// to which specific Molt command sets can be added. /// /// # Example /// /// ``` /// # use molt::interp::Interp; /// let mut interp = Interp::empty(); /// assert!(interp.command_names().is_empty()); /// ``` pub fn empty() -> Self { Self { recursion_limit: 1000, commands: HashMap::new(), last_context_id: 0, context_map: HashMap::new(), scopes: ScopeStack::new(), num_levels: 0, profile_map: HashMap::new(), } } /// Creates a new Molt interpreter, pre-populated with the standard Molt commands. /// Use [`command_names`](#method.command_names) (or the `info commands` Molt command) /// to retrieve the full list, and the [`add_command`](#method.add_command) family of /// methods to extend the interpreter with new commands. /// /// TODO: Define command sets (sets of commands that go together, so that clients can /// add or remove them in groups). /// /// ``` /// # use molt::types::*; /// # use molt::Interp; /// # use molt::molt_ok; /// # fn dummy() -> MoltResult { /// let mut interp = Interp::new(); /// let four = interp.eval("expr {2 + 2}")?; /// assert_eq!(four, Value::from(4)); /// # molt_ok!() /// # } /// ``` /// pub fn new() -> Self { let mut interp = Interp::empty(); // TODO: These commands affect the interpreter only, not the external environment. // It might be desirable to subdivide them further, into those that can cause // denial-of-service kinds of problems, e.g., for, while, proc, rename, and those // that can't. interp.add_command("append", commands::cmd_append); interp.add_command("assert_eq", commands::cmd_assert_eq); interp.add_command("break", commands::cmd_break); interp.add_command("catch", commands::cmd_catch); interp.add_command("continue", commands::cmd_continue); interp.add_command("error", commands::cmd_error); interp.add_command("expr", commands::cmd_expr); interp.add_command("for", commands::cmd_for); interp.add_command("foreach", commands::cmd_foreach); interp.add_command("global", commands::cmd_global); interp.add_command("if", commands::cmd_if); interp.add_command("incr", commands::cmd_incr); interp.add_command("info", commands::cmd_info); interp.add_command("join", commands::cmd_join); interp.add_command("lappend", commands::cmd_lappend); interp.add_command("lindex", commands::cmd_lindex); interp.add_command("list", commands::cmd_list); interp.add_command("llength", commands::cmd_llength); interp.add_command("proc", commands::cmd_proc); interp.add_command("puts", commands::cmd_puts); interp.add_command("rename", commands::cmd_rename); interp.add_command("return", commands::cmd_return); interp.add_command("set", commands::cmd_set); interp.add_command("time", commands::cmd_time); interp.add_command("unset", commands::cmd_unset); interp.add_command("while", commands::cmd_while); // TODO: Requires file access. Ultimately, might go in an extension crate if // the necessary operations aren't available in core::. interp.add_command("source", commands::cmd_source); // TODO: Useful for entire programs written in Molt; but not necessarily wanted in // extension scripts. interp.add_command("exit", commands::cmd_exit); // TODO: Developer Tools interp.add_command("parse", parser::cmd_parse); interp.add_command("pdump", commands::cmd_pdump); interp.add_command("pclear", commands::cmd_pclear); interp } //-------------------------------------------------------------------------------------------- // Script and Expression Evaluation /// Evaluates a script one command at a time. Returns the [`Value`](../value/struct.Value.html) /// of the last command in the script, or the value of any explicit `return` call in the /// script, or any error thrown by the script. Other /// [`ResultCode`](../types/enum.ResultCode.html) values are converted to normal errors. /// /// Use this method (or [`eval_value`](#method.eval_value) to evaluate arbitrary scripts. /// Use [`eval_body`](#method.eval_body) to evaluate the body of control structures. /// /// # Example /// /// The following code shows how to evaluate a script and handle the result, whether /// it's a computed `Value` or an error message (which is also a `Value`). /// /// ``` /// # use molt::types::*; /// # use molt::Interp; /// let mut interp = Interp::new(); /// let input = "set a 1"; /// match interp.eval(input) { /// Ok(val) => { /// // Computed a Value /// println!("Value: {}", val); /// } /// Err(ResultCode::Error(msg)) => { /// // Got an error; print it out. /// println!("Error: {}", msg); /// } /// _ => { /// // Won't ever happen, but the compiler doesn't know that. /// // panic!() if you like. /// } /// } /// ``` pub fn eval(&mut self, script: &str) -> MoltResult { let value = Value::from(script); self.eval_value(&value) } pub fn eval_value(&mut self, value: &Value) -> MoltResult { // TODO: Could probably do better, here. If the value is already a list, for // example, can maybe evaluate it as a command without using as_script(). // Tricky, though. Don't want to have to parse it as a list. Need a quick way // to determine if something is already a list. // FIRST, check the number of nesting levels self.num_levels += 1; if self.num_levels > self.recursion_limit { self.num_levels -= 1; return molt_err!("too many nested calls to Interp::eval (infinite loop?)"); } // NEXT, evaluate the script and translate the result to Ok or Error let result = self.eval_body(value); // NEXT, decrement the number of nesting levels. self.num_levels -= 1; // NEXT, translate and return the result. match result { Err(ResultCode::Return(val)) => Ok(val), Err(ResultCode::Break) => molt_err!("invoked \"break\" outside of a loop"), Err(ResultCode::Continue) => molt_err!("invoked \"continue\" outside of a loop"), _ => result, } } /// Evaluates a script one command at a time, returning whatever /// [`MoltResult`](../types/type.MoltResult.html) arises. /// /// This is the method to use when evaluating a control structure's /// script body; the control structure must handle the special /// result codes appropriately. /// /// # Example /// /// The following code could be used to process the body of one of the Molt looping /// commands, e.g., `while` or /// `foreach`. [`ResultCode`](../types/enum.ResultCode.html)`::Return` and `ResultCode::Error` /// return out of the looping command altogether, returning control to the caller. /// `ResultCode::Break` breaks out of the loop. `Ok` and `ResultCode::Continue` /// continue with the next iteration. /// /// ```ignore /// ... /// while (...) { /// let result = interp.eval_body(&body); /// /// match result { /// Ok(_) => (), /// Err(ResultCode::Return(_)) => return result, /// Err(ResultCode::Error(_)) => return result, /// Err(ResultCode::Break) => break, /// Err(ResultCode::Continue) => (), /// } /// } /// /// molt_ok!() /// ``` pub fn eval_body(&mut self, body: &Value) -> MoltResult { self.eval_script(&*body.as_script()?) } fn eval_script(&mut self, script: &Script) -> MoltResult { let mut result_value = Value::empty(); for word_vec in script.commands() { let words = self.words_to_list(word_vec.words())?; if words.is_empty() { break; } let name = words[0].as_str(); if let Some(cmd) = self.commands.get(name) { // let start = Instant::now(); let cmd = Rc::clone(cmd); let result = cmd.execute(self, words.as_slice()); // self.profile_save(&format!("cmd.execute({})", name), start); match result { Ok(v) => result_value = v, _ => return result, } } else { return molt_err!("invalid command name \"{}\"", name); } } Ok(result_value) } fn words_to_list(&mut self, words: &[Word]) -> Result<MoltList, ResultCode> { let mut list: MoltList = Vec::new(); for word in words { match word { Word::Value(val) => list.push(val.clone()), Word::VarRef(name) => list.push(self.var(name)?), Word::Script(script) => list.push(self.eval_script(script)?), Word::Tokens(tokens) => { let tlist = self.words_to_list(tokens)?; let string: String = tlist.iter().map(|i| i.as_str()).collect(); list.push(Value::from(string)); } // TODO: Consider saving all individual strings as values. Word::String(str) => list.push(Value::from(str)), } } Ok(list) } /// Determines whether or not the script is syntactically complete, /// e.g., has no unmatched quotes, brackets, or braces. /// /// REPLs use this to determine whether or not to ask for another line of /// input. /// /// # Example /// /// ``` /// # use molt::types::*; /// # use molt::interp::Interp; /// let mut interp = Interp::new(); /// assert!(interp.complete("set a [expr {1+1}]")); /// assert!(!interp.complete("set a [expr {1+1")); /// ``` pub fn complete(&mut self, script: &str) -> bool { parser::parse(script).is_ok() } /// Evaluates a [Molt expression](https://wduquette.github.io/molt/ref/expr.html) and /// returns its value. The expression is passed a `Value` which is interpreted as a `String`. /// /// # Example /// ``` /// use molt::Interp; /// use molt::types::*; /// # fn dummy() -> Result<String,ResultCode> { /// let mut interp = Interp::new(); /// let expr = Value::from("2 + 2"); /// let sum = interp.expr(&expr)?.as_int()?; /// /// assert_eq!(sum, 4); /// # Ok("dummy".to_string()) /// # } /// ``` pub fn expr(&mut self, expr: &Value) -> MoltResult { expr::expr(self, expr) } /// Evaluates a boolean [Molt expression](https://wduquette.github.io/molt/ref/expr.html) /// and returns its value, or an error if it couldn't be interpreted as a boolean. /// /// # Example /// /// ``` /// use molt::Interp; /// use molt::types::*; /// # fn dummy() -> Result<String,ResultCode> { /// let mut interp = Interp::new(); /// /// let expr = Value::from("1 < 2"); /// let flag: bool = interp.expr_bool(&expr)?; /// /// assert!(flag); /// # Ok("dummy".to_string()) /// # } /// ``` pub fn expr_bool(&mut self, expr: &Value) -> Result<bool, ResultCode> { expr::expr(self, expr)?.as_bool() } /// Evaluates a [Molt expression](https://wduquette.github.io/molt/ref/expr.html) /// and returns its value as an integer, or an error if it couldn't be interpreted as an /// integer. /// /// # Example /// /// ``` /// use molt::Interp; /// use molt::types::*; /// # fn dummy() -> Result<String,ResultCode> { /// let mut interp = Interp::new(); /// /// let expr = Value::from("1 + 2"); /// let val: MoltInt = interp.expr_int(&expr)?; /// /// assert_eq!(val, 3); /// # Ok("dummy".to_string()) /// # } /// ``` pub fn expr_int(&mut self, expr: &Value) -> Result<MoltInt, ResultCode> { expr::expr(self, expr)?.as_int() } /// Evaluates a [Molt expression](https://wduquette.github.io/molt/ref/expr.html) /// and returns its value as a float, or an error if it couldn't be interpreted as a /// float. /// /// # Example /// /// ``` /// use molt::Interp; /// use molt::types::*; /// # fn dummy() -> Result<String,ResultCode> { /// let mut interp = Interp::new(); /// /// let expr = Value::from("1.1 + 2.2"); /// let val: MoltFloat = interp.expr_float(&expr)?; /// /// assert_eq!(val, 3.3); /// # Ok("dummy".to_string()) /// # } /// ``` pub fn expr_float(&mut self, expr: &Value) -> Result<MoltFloat, ResultCode> { expr::expr(self, expr)?.as_float() } //-------------------------------------------------------------------------------------------- // Command Definition and Handling /// Adds a command defined by a `CommandFunc` to the interpreter. This is the normal way to /// add commands to the interpreter. /// /// # Accessing Application Data /// /// When embedding Molt in an application, it is common to define commands that require /// mutable or immutable access to application data. If the command requires /// access to data other than that provided by the `Interp` itself, e.g., application data, /// consider adding the relevant data structure to the context cache and then use /// [`add_context_command`](#method.add_context_command). Alternatively, define a struct that /// implements `Command` and use [`add_command_object`](#method.add_command_object). pub fn add_command(&mut self, name: &str, func: CommandFunc) { let command = CommandFuncWrapper::new(func); self.add_command_object(name, command); } /// Adds a command defined by a `ContextCommandFunc` to the interpreter. /// /// This is the normal way to add commands requiring application context to /// the interpreter. It is up to the module creating the context to free it when it is /// no longer required. /// /// **Warning**: Do not use this method to define a TCL object, i.e., a command with /// its own data and lifetime. Use a type that implements `Command` and `Drop`. pub fn add_context_command( &mut self, name: &str, func: ContextCommandFunc, context_id: ContextID, ) { let command = ContextCommandFuncWrapper::new(func, context_id); self.add_command_object(name, command); } /// Adds a procedure to the interpreter. /// /// This is how to add a Molt `proc` to the interpreter. The arguments are the same /// as for the `proc` command and the `commands::cmd_proc` function. pub(crate) fn add_proc(&mut self, name: &str, args: &[Value], body: &str) { let command = CommandProc { args: args.to_owned(), body: body.to_string(), }; self.add_command_object(name, command); } /// Adds a command to the interpreter using a `Command` object. /// /// Use this when defining a command that requires application context. pub fn add_command_object<T: 'static + Command>(&mut self, name: &str, command: T) { self.commands.insert(name.into(), Rc::new(command)); } /// Determines whether the interpreter contains a command with the given /// name. pub fn has_command(&self, name: &str) -> bool { self.commands.contains_key(name) } /// Renames the command. /// /// **Note:** This does not update procedures that reference the command under the old /// name. This is intentional: it is a common TCL programming technique to wrap an /// existing command by renaming it and defining a new command with the old name that /// calls the original command at its new name. pub fn rename_command(&mut self, old_name: &str, new_name: &str) { if let Some(cmd) = self.commands.get(old_name) { let cmd = Rc::clone(cmd); self.commands.remove(old_name); self.commands.insert(new_name.into(), cmd); } } /// Removes the command with the given name. pub fn remove_command(&mut self, name: &str) { self.commands.remove(name); } /// Gets a vector of the names of the existing commands. /// pub fn command_names(&self) -> MoltList { let vec: MoltList = self .commands .keys() .cloned() .map(|x| Value::from(&x)) .collect(); vec } //-------------------------------------------------------------------------------------------- // Interpreter Configuration /// Gets the interpreter's recursion limit. /// /// # Example /// ``` /// # use molt::types::*; /// # use molt::interp::Interp; /// let mut interp = Interp::new(); /// assert_eq!(interp.recursion_limit(), 1000); /// ``` pub fn recursion_limit(&self) -> usize { self.recursion_limit } /// Sets the interpreter's recursion limit. The default is 1000. /// /// # Example /// ``` /// # use molt::types::*; /// # use molt::interp::Interp; /// let mut interp = Interp::new(); /// interp.set_recursion_limit(100); /// assert_eq!(interp.recursion_limit(), 100); /// ``` pub fn set_recursion_limit(&mut self, limit: usize) { self.recursion_limit = limit; } //-------------------------------------------------------------------------------------------- // Context Cache /// Saves the client context data in the interpreter's context cache, /// returning a generated context ID. Client commands can retrieve the data /// given the ID. /// /// /// # Example /// /// ``` /// use molt::types::*; /// use molt::interp::Interp; /// /// let mut interp = Interp::new(); /// let data: Vec<String> = Vec::new(); /// let id = interp.save_context(data); /// ``` pub fn save_context<T: 'static>(&mut self, data: T) -> ContextID { let id = self.context_id(); self.context_map.insert(id, Box::new(data)); id } /// Retrieves mutable client context given the context ID. /// /// # Example /// /// ``` /// use molt::types::*; /// use molt::interp::Interp; /// /// let mut interp = Interp::new(); /// let data: Vec<String> = Vec::new(); /// let id = interp.save_context(data); /// /// // Later... /// let data: &mut Vec<String> = interp.context(id); /// data.push("New Value".into()); /// /// // Or /// let data = interp.context::<Vec<String>>(id); /// data.push("New Value".into()); /// ``` /// /// # Panics /// /// This call panics if the context ID is unknown, or if the retrieved data /// has an unexpected type. pub fn context<T: 'static>(&mut self, id: ContextID) -> &mut T { self.context_map .get_mut(&id) .expect("unknown context ID") .downcast_mut::<T>() .expect("context type mismatch") } /// Removes a context record from the context cache. Clears the data from /// the cache when it is no longer needed. /// /// # Example /// /// ``` /// use molt::types::*; /// use molt::interp::Interp; /// /// let mut interp = Interp::new(); /// let data: Vec<String> = Vec::new(); /// let id = interp.save_context(data); /// /// // Later... /// interp.forget_context(id); /// ``` /// pub fn forget_context(&mut self, id: ContextID) { self.context_map.remove(&id); } /// Generates a unique context ID for command context data. /// /// Normally the client will use [`save_context`](#method.save_context) to /// save the context data and generate the client ID in one operation, rather than /// call this explicitly. //// /// # Example /// /// ``` /// use molt::types::*; /// use molt::interp::Interp; /// /// let mut interp = Interp::new(); /// let id1 = interp.context_id(); /// let id2 = interp.context_id(); /// assert_ne!(id1, id2); /// ``` pub fn context_id(&mut self) -> ContextID { // TODO: Practically speaking we won't overflow u64; but practically speaking // we should check any. self.last_context_id += 1; ContextID(self.last_context_id) } /// Saves a client context value in the interpreter for the given /// context ID. Client commands can retrieve the data given the context ID. /// /// Normally the client will use [`save_context`](#method.save_context) to /// save the context data and generate the client ID in one operation, rather than /// call this explicitly. /// /// TODO: This method allows the user to generate a context ID and /// put data into the context cache as two separate steps; and to update the /// the data in the context cache for a given ID. I'm not at all sure that /// either of those things is a good idea. Waiting to see. /// /// # Example /// /// ``` /// use molt::types::*; /// use molt::interp::Interp; /// /// let mut interp = Interp::new(); /// let id = interp.context_id(); /// let data: Vec<String> = Vec::new(); /// interp.set_context(id, data); /// ``` pub fn set_context<T: 'static>(&mut self, id: ContextID, data: T) { self.context_map.insert(id, Box::new(data)); } //-------------------------------------------------------------------------------------------- // Variable Handling /// Retrieves the value of the named variable in the current scope, if any. pub fn var(&self, name: &str) -> MoltResult { match self.scopes.get(name) { Some(v) => molt_ok!(v.clone()), None => molt_err!("can't read \"{}\": no such variable", name), } } /// Sets the value of the named variable in the current scope, creating the variable /// if necessary, and returning the value. pub fn set_and_return(&mut self, name: &str, value: Value) -> Value { self.scopes.set(name, value.clone()); value } /// Sets the value of the named variable in the current scope, creating the variable /// if necessary. /// /// Ultimately, this should be set_var. pub fn set_var(&mut self, name: &str, value: &Value) { self.scopes.set(name, value.clone()); } /// Unsets the value of the named variable in the current scope pub fn unset_var(&mut self, name: &str) { self.scopes.unset(name); } /// Gets a vector of the visible var names. pub fn vars_in_scope(&self) -> MoltList { self.scopes.vars_in_scope() } /// Pushes a variable scope on to the scope stack. /// Procs use this to define their local scope. pub fn push_scope(&mut self) { self.scopes.push(); } /// Pops a variable scope off of the scope stack. pub fn pop_scope(&mut self) { self.scopes.pop(); } /// Return the current scope level pub fn scope_level(&self) -> usize { self.scopes.current() } /// Links the variable name in the current scope to the given scope. pub fn upvar(&mut self, level: usize, name: &str) { assert!(level <= self.scopes.current(), "Invalid scope level"); self.scopes.upvar(level, name); } //-------------------------------------------------------------------------------------------- // The Molt Parser // // TODO: Can this be easily moved to another module? It needs access to the // Interp struct's fields. /// Low-level script evaluator; evaluates the next script in the /// context. fn eval_context(&mut self, ctx: &mut EvalPtr) -> MoltResult { let mut result_value = Value::empty(); while !ctx.at_end_of_script() { // let start = Instant::now(); let words = self.parse_command(ctx)?; if words.is_empty() { break; } // self.profile_save(&format!("parse_command({})", words[0].as_str()), start); // When scanning for info if ctx.is_no_eval() { continue; } // FIRST, convert to Vec<&str> let name = words[0].as_str(); if let Some(cmd) = self.commands.get(name) { // let start = Instant::now(); let cmd = Rc::clone(cmd); let result = cmd.execute(self, words.as_slice()); // self.profile_save(&format!("cmd.execute({})", name), start); match result { Ok(v) => result_value = v, _ => return result, } } else { return molt_err!("invalid command name \"{}\"", name); } } Ok(result_value) } fn parse_command(&mut self, ctx: &mut EvalPtr) -> Result<MoltList, ResultCode> { // FIRST, deal with whitespace and comments between "here" and the next command. while !ctx.at_end_of_script() { ctx.skip_block_white(); // Either there's a comment, or we're at the beginning of the next command. // If the former, skip the comment; then check for more whitespace and comments. // Otherwise, go on to the command. if !ctx.skip_comment() { break; } } let mut words = Vec::new(); // Read words until we get to the end of the line or hit an error // NOTE: parse_word() can always assume that it's at the beginning of a word. while !ctx.at_end_of_command() { // FIRST, get the next word; there has to be one, or there's an input error. let word = self.parse_word(ctx)?; // NEXT, save the word we found. words.push(word); // NEXT, skip any whitespace. ctx.skip_line_white(); } // If we ended at a ";", consume the semi-colon. if ctx.next_is(';') { ctx.next(); } Ok(words) } /// We're at the beginning of a word belonging to the current command. /// It's either a bare word, a braced string, or a quoted string--or there's /// an error in the input. Whichever it is, get it. fn parse_word(&mut self, ctx: &mut EvalPtr) -> MoltResult { if ctx.next_is('{') { Ok(self.parse_braced_word(ctx)?) } else if ctx.next_is('"') { Ok(self.parse_quoted_word(ctx)?) } else { Ok(self.parse_bare_word(ctx)?) } } pub(crate) fn parse_braced_word(&mut self, ctx: &mut EvalPtr) -> MoltResult { // FIRST, skip the opening brace, and count it; non-escaped braces need to // balance. ctx.skip_char('{'); let mut count = 1; // NEXT, add tokens to the word until we reach the close quote let mut word = String::new(); let mut start = ctx.mark(); while !ctx.at_end() { // Note: the while condition ensures that there's a character. if ctx.next_is('{') { count += 1; ctx.skip(); } else if ctx.next_is('}') { count -= 1; if count > 0 { ctx.skip(); } else { // We've found and consumed the closing brace. We should either // see more more whitespace, or we should be at the end of the list // Otherwise, there are incorrect characters following the close-brace. word.push_str(ctx.token(start)); let result = Ok(Value::from(word)); ctx.skip(); // Skip the closing brace if ctx.at_end_of_command() || ctx.next_is_line_white() { return result; } else { return molt_err!("extra characters after close-brace"); } } } else if ctx.next_is('\\') { word.push_str(ctx.token(start)); ctx.skip(); // If there's no character it's because we're at the end; and there's // no close brace. if let Some(ch) = ctx.next() { if ch == '\n' { word.push(' '); } else { word.push('\\'); word.push(ch); } } start = ctx.mark(); } else { ctx.skip(); } } molt_err!("missing close-brace") } /// Parse a quoted word. pub(crate) fn parse_quoted_word(&mut self, ctx: &mut EvalPtr) -> MoltResult { // FIRST, consume the the opening quote. ctx.next(); // NEXT, add tokens to the word until we reach the close quote let mut word = String::new(); let mut start = ctx.mark(); while !ctx.at_end() { // Note: the while condition ensures that there's a character. if ctx.next_is('[') { word.push_str(ctx.token(start)); word.push_str(self.parse_script(ctx)?.as_str()); start = ctx.mark(); } else if ctx.next_is('$') { word.push_str(ctx.token(start)); word.push_str(self.parse_variable(ctx)?.as_str()); start = ctx.mark(); } else if ctx.next_is('\\') { word.push_str(ctx.token(start)); word.push(ctx.backslash_subst()); start = ctx.mark(); } else if ctx.next_is('"') { word.push_str(ctx.token(start)); ctx.skip_char('"'); if !ctx.at_end_of_command() && !ctx.next_is_line_white() { return molt_err!("extra characters after close-quote"); } else { return Ok(Value::from(word)); } } else { ctx.skip(); } } molt_err!("missing \"") } /// Parse a bare word. fn parse_bare_word(&mut self, ctx: &mut EvalPtr) -> MoltResult { let mut word = String::new(); let mut start = ctx.mark(); while !ctx.at_end_of_command() && !ctx.next_is_line_white() { // Note: the while condition ensures that there's a character. if ctx.next_is('[') { word.push_str(ctx.token(start)); word.push_str(self.parse_script(ctx)?.as_str()); start = ctx.mark(); } else if ctx.next_is('$') { word.push_str(ctx.token(start)); word.push_str(self.parse_variable(ctx)?.as_str()); start = ctx.mark(); } else if ctx.next_is('\\') { word.push_str(ctx.token(start)); word.push(ctx.backslash_subst()); start = ctx.mark(); } else { ctx.skip(); } } word.push_str(ctx.token(start)); Ok(Value::from(word)) } pub(crate) fn parse_script(&mut self, ctx: &mut EvalPtr) -> MoltResult { // FIRST, skip the '[' ctx.skip_char('['); // NEXT, parse the script up to the matching ']' let old_flag = ctx.is_bracket_term(); ctx.set_bracket_term(true); let result = self.eval_context(ctx); ctx.set_bracket_term(old_flag); // NEXT, make sure there's a closing bracket if result.is_ok() { if ctx.next_is(']') { ctx.next(); } else { return molt_err!("missing close-bracket"); } } result } pub(crate) fn parse_variable(&mut self, ctx: &mut EvalPtr) -> MoltResult { // FIRST, skip the '$' ctx.skip_char('$'); // NEXT, make sure this is really a variable reference. If it isn't // just return a "$". if !ctx.next_is_varname_char() && !ctx.next_is('{') { return Ok(Value::from("$")); } // NEXT, is this a braced variable name? let var_value; if ctx.next_is('{') { ctx.skip_char('{'); let start = ctx.mark(); ctx.skip_while(|ch| *ch != '}'); if ctx.at_end() { return molt_err!("missing close-brace for variable name"); } var_value = self.var(ctx.token(start))?; ctx.skip_char('}'); } else { let start = ctx.mark(); ctx.skip_while(|ch| is_varname_char(*ch)); var_value = self.var(ctx.token(start))?; } Ok(var_value) } //-------------------------------------------------------------------------------------------- // Profiling pub fn profile_save(&mut self, name: &str, start: std::time::Instant) { let dur = Instant::now().duration_since(start).as_nanos(); let rec = self .profile_map .entry(name.into()) .or_insert_with(ProfileRecord::new); rec.count += 1; rec.nanos += dur; } pub fn profile_clear(&mut self) { self.profile_map.clear(); } pub fn profile_dump(&self) { if self.profile_map.is_empty() { println!("no profile data"); } else { for (name, rec) in &self.profile_map { let avg = rec.nanos / rec.count; println!("{} nanos {}, count={}", avg, name, rec.count); } } } } /// A struct that wraps a CommandFunc and implements the Command trait. struct CommandFuncWrapper { func: CommandFunc, } impl CommandFuncWrapper { fn new(func: CommandFunc) -> Self { Self { func } } } impl Command for CommandFuncWrapper { fn execute(&self, interp: &mut Interp, argv: &[Value]) -> MoltResult { (self.func)(interp, argv) } } /// A struct that wraps a ContextCommandFunc and implements the Command trait. struct ContextCommandFuncWrapper { func: ContextCommandFunc, context_id: ContextID, } impl ContextCommandFuncWrapper { fn new(func: ContextCommandFunc, context_id: ContextID) -> Self { Self { func, context_id } } } impl Command for ContextCommandFuncWrapper { fn execute(&self, interp: &mut Interp, argv: &[Value]) -> MoltResult { (self.func)(interp, self.context_id, argv) } } // EvalPtr structure for a proc. struct CommandProc { args: MoltList, body: String, } // TODO: Need to work out how we're going to store the CommandProc details for // best efficiency. impl Command for CommandProc { fn execute(&self, interp: &mut Interp, argv: &[Value]) -> MoltResult { let name = argv[0].as_str(); // FIRST, push the proc's local scope onto the stack. interp.push_scope(); // NEXT, process the proc's argument list. let mut argi = 1; // Skip the proc's name for (speci, spec) in self.args.iter().enumerate() { // FIRST, get the parameter as a vector. It should be a list of // one or two elements. let vec = &*spec.as_list()?; // Should never fail assert!(vec.len() == 1 || vec.len() == 2); // NEXT, if this is the args parameter, give the remaining args, // if any. Note that "args" has special meaning only if it's the // final arg spec in the list. if vec[0].as_str() == "args" && speci == self.args.len() - 1 { interp.set_and_return("args", Value::from(&argv[argi..])); // We've processed all of the args argi = argv.len(); break; } // NEXT, do we have a matching argument? if argi < argv.len() { // Pair them up interp.set_var(vec[0].as_str(), &argv[argi]); argi += 1; continue; } // NEXT, do we have a default value? if vec.len() == 2 { interp.set_var(vec[0].as_str(), &vec[1]); } else { // We don't; we're missing a required argument. return self.wrong_num_args(name); } } // NEXT, do we have any arguments left over? if argi != argv.len() { return self.wrong_num_args(name); } // NEXT, evaluate the proc's body, getting the result. let result = interp.eval(&self.body); // NEXT, pop the scope off of the stack; we're done with it. interp.pop_scope(); // NEXT, return the computed result. // Note: no need for special handling for return, break, continue; // interp.eval() returns only Ok or a real error. result } } impl CommandProc { // Outputs the wrong # args message for the proc. The name is passed in // because it can be changed via the `rename` command. fn wrong_num_args(&self, name: &str) -> MoltResult { let mut msg = String::new(); msg.push_str("wrong # args: should be \""); msg.push_str(name); for (i, arg) in self.args.iter().enumerate() { msg.push(' '); // "args" has special meaning only in the last place. if arg.as_str() == "args" && i == self.args.len() - 1 { msg.push_str("?arg ...?"); break; } let vec = arg.as_list().expect("error in proc arglist validation!"); if vec.len() == 1 { msg.push_str(vec[0].as_str()); } else { msg.push('?'); msg.push_str(vec[0].as_str()); msg.push('?'); } } msg.push_str("\""); molt_err!(&msg) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_empty() { let interp = Interp::empty(); // Interpreter is empty assert!(interp.command_names().is_empty()); } #[test] fn test_new() { let interp = Interp::new(); // Interpreter is not empty assert!(!interp.command_names().is_empty()); // Note: in theory, we should test here that the normal set of commands is present. // In fact, that should be tested by the `molt test` suite. } #[test] fn test_eval() { let mut interp = Interp::new(); assert_eq!(interp.eval("set a 1"), Ok(Value::from("1"))); assert_eq!( interp.eval("error 2"), Err(ResultCode::Error(Value::from("2"))) ); assert_eq!(interp.eval("return 3"), Ok(Value::from("3"))); assert_eq!( interp.eval("break"), Err(ResultCode::Error(Value::from( "invoked \"break\" outside of a loop" ))) ); assert_eq!( interp.eval("continue"), Err(ResultCode::Error(Value::from( "invoked \"continue\" outside of a loop" ))) ); } #[test] fn test_eval_value() { let mut interp = Interp::new(); assert_eq!( interp.eval_value(&Value::from("set a 1")), Ok(Value::from("1")) ); assert_eq!( interp.eval_value(&Value::from("error 2")), Err(ResultCode::Error(Value::from("2"))) ); assert_eq!( interp.eval_value(&Value::from("return 3")), Ok(Value::from("3")) ); assert_eq!( interp.eval_value(&Value::from("break")), Err(ResultCode::Error(Value::from( "invoked \"break\" outside of a loop" ))) ); assert_eq!( interp.eval_value(&Value::from("continue")), Err(ResultCode::Error(Value::from( "invoked \"continue\" outside of a loop" ))) ); } #[test] fn test_eval_body() { let mut interp = Interp::new(); assert_eq!( interp.eval_body(&Value::from("set a 1")), Ok(Value::from("1")) ); assert_eq!( interp.eval_body(&Value::from("set a 1; set b 2")), Ok(Value::from("2")) ); assert_eq!( interp.eval_body(&Value::from("error 2; set a whoops")), Err(ResultCode::Error(Value::from("2"))) ); assert_eq!( interp.eval_body(&Value::from("return 3; set a whoops")), Err(ResultCode::Return(Value::from("3"))) ); assert_eq!( interp.eval_body(&Value::from("break; set a whoops")), Err(ResultCode::Break) ); assert_eq!( interp.eval_body(&Value::from("continue; set a whoops")), Err(ResultCode::Continue) ); } #[test] fn test_complete() { let mut interp = Interp::new(); assert!(interp.complete("abc")); assert!(interp.complete("a {bc} [def] \"ghi\" xyz")); assert!(!interp.complete("a {bc")); assert!(!interp.complete("a [bc")); assert!(!interp.complete("a \"bc")); } #[test] fn test_expr() { let mut interp = Interp::new(); assert_eq!(interp.expr(&Value::from("1 + 2")), Ok(Value::from(3))); assert_eq!( interp.expr(&Value::from("a + b")), Err(ResultCode::Error(Value::from( "unknown math function \"a\"" ))) ); } #[test] fn test_expr_bool() { let mut interp = Interp::new(); assert_eq!(interp.expr_bool(&Value::from("1")), Ok(true)); assert_eq!(interp.expr_bool(&Value::from("0")), Ok(false)); assert_eq!( interp.expr_bool(&Value::from("a")), Err(ResultCode::Error(Value::from( "unknown math function \"a\"" ))) ); } #[test] fn test_expr_int() { let mut interp = Interp::new(); assert_eq!(interp.expr_int(&Value::from("1 + 2")), Ok(3)); assert_eq!( interp.expr_int(&Value::from("a")), Err(ResultCode::Error(Value::from( "unknown math function \"a\"" ))) ); } #[test] fn test_expr_float() { let mut interp = Interp::new(); let val = interp .expr_float(&Value::from("1.1 + 2.2")) .expect("floating point value"); assert!((val - 3.3).abs() < 0.001); assert_eq!( interp.expr_float(&Value::from("a")), Err(ResultCode::Error(Value::from( "unknown math function \"a\"" ))) ); } #[test] fn test_parse_braced_word() { let mut interp = Interp::new(); // Simple string assert_eq!(pbrace(&mut interp, "{abc}"), "abc|".to_string()); // Simple string with following space assert_eq!(pbrace(&mut interp, "{abc} "), "abc| ".to_string()); // String with white space assert_eq!(pbrace(&mut interp, "{a b c} "), "a b c| ".to_string()); // String with $ and []space assert_eq!(pbrace(&mut interp, "{a $b [c]} "), "a $b [c]| ".to_string()); // String with escaped braces assert_eq!(pbrace(&mut interp, "{a\\{bc} "), "a\\{bc| ".to_string()); assert_eq!(pbrace(&mut interp, "{ab\\}c} "), "ab\\}c| ".to_string()); // String with escaped newline (a real newline with a \ in front) assert_eq!(pbrace(&mut interp, "{ab\\\nc}"), "ab c|".to_string()); } fn pbrace(interp: &mut Interp, input: &str) -> String { let mut ctx = EvalPtr::new(input); match interp.parse_braced_word(&mut ctx) { Ok(val) => format!("{}|{}", val.as_str(), ctx.tok().as_str()), Err(ResultCode::Error(value)) => format!("{}", value), Err(code) => format!("{:?}", code), } } #[test] fn test_parse_quoted_word() { let mut interp = Interp::new(); // Simple string assert_eq!(pqw(&mut interp, "\"abc\""), "abc|".to_string()); // Simple string with text following assert_eq!(pqw(&mut interp, "\"abc\" "), "abc| ".to_string()); // Backslash substitution at beginning, middle, and end assert_eq!(pqw(&mut interp, "\"\\x77-\""), "w-|".to_string()); assert_eq!(pqw(&mut interp, "\"a\\x77-\""), "aw-|".to_string()); assert_eq!(pqw(&mut interp, "\"a\\x77\""), "aw|".to_string()); // Variable substitution interp.set_var("x", &Value::from("5")); assert_eq!(pqw(&mut interp, "\"a$x.b\" "), "a5.b| ".to_string()); interp.set_var("xyz1", &Value::from("10")); assert_eq!(pqw(&mut interp, "\"a$xyz1.b\" "), "a10.b| ".to_string()); assert_eq!(pqw(&mut interp, "\"a$.b\" "), "a$.b| ".to_string()); assert_eq!(pqw(&mut interp, "\"a${x}.b\" "), "a5.b| ".to_string()); // Command substitution assert_eq!(pqw(&mut interp, "\"a[list b]c\""), "abc|".to_string()); assert_eq!(pqw(&mut interp, "\"a[list b c]d\""), "ab cd|".to_string()); // Extra characters after close-quote assert_eq!( pqw(&mut interp, "\"abc\"x "), "extra characters after close-quote" ); } fn pqw(interp: &mut Interp, input: &str) -> String { let mut ctx = EvalPtr::new(input); match interp.parse_quoted_word(&mut ctx) { Ok(val) => format!("{}|{}", val.as_str(), ctx.tok().as_str()), Err(ResultCode::Error(value)) => format!("{}", value), Err(code) => format!("{:?}", code), } } #[test] fn test_parse_bare() { let mut interp = Interp::new(); // Single word assert_eq!(pbare(&mut interp, "abc"), "abc|".to_string()); // Single word with whitespace following assert_eq!(pbare(&mut interp, "abc "), "abc| ".to_string()); assert_eq!(pbare(&mut interp, "abc\t"), "abc|\t".to_string()); // Backslash substitution at beginning, middle, and end assert_eq!(pbare(&mut interp, "\\x77-"), "w-|".to_string()); assert_eq!(pbare(&mut interp, "a\\x77-"), "aw-|".to_string()); assert_eq!(pbare(&mut interp, "a\\x77"), "aw|".to_string()); // Variable substitution interp.set_var("x", &Value::from("5")); assert_eq!(pbare(&mut interp, "a$x.b "), "a5.b| ".to_string()); interp.set_var("xyz1", &Value::from("10")); assert_eq!(pbare(&mut interp, "a$xyz1.b "), "a10.b| ".to_string()); assert_eq!(pbare(&mut interp, "a$.b "), "a$.b| ".to_string()); assert_eq!(pbare(&mut interp, "a${x}.b "), "a5.b| ".to_string()); // Command substitution assert_eq!(pbare(&mut interp, "a[list b]c"), "abc|".to_string()); assert_eq!(pbare(&mut interp, "a[list b c]d"), "ab cd|".to_string()); } fn pbare(interp: &mut Interp, input: &str) -> String { let mut ctx = EvalPtr::new(input); match interp.parse_bare_word(&mut ctx) { Ok(val) => format!("{}|{}", val.as_str(), ctx.tok().as_str()), Err(ResultCode::Error(value)) => format!("{}", value), Err(code) => format!("{:?}", code), } } #[test] fn test_parse_variable() { let mut interp = Interp::new(); assert_eq!(pvar(&mut interp, "a", "$a"), "OK|".to_string()); assert_eq!(pvar(&mut interp, "abc", "$abc"), "OK|".to_string()); assert_eq!(pvar(&mut interp, "abc", "$abc."), "OK|.".to_string()); assert_eq!(pvar(&mut interp, "a", "$a.bc"), "OK|.bc".to_string()); assert_eq!(pvar(&mut interp, "a1_", "$a1_.bc"), "OK|.bc".to_string()); assert_eq!(pvar(&mut interp, "a", "${a}b"), "OK|b".to_string()); assert_eq!(pvar(&mut interp, "a", "$"), "$|".to_string()); assert_eq!( pvar(&mut interp, "a", "$1"), "can't read \"1\": no such variable".to_string() ); } fn pvar(interp: &mut Interp, var: &str, input: &str) -> String { let mut ctx = EvalPtr::new(input); interp.set_var(var, &Value::from("OK")); match interp.parse_variable(&mut ctx) { Ok(val) => format!("{}|{}", val, ctx.tok().as_str()), Err(ResultCode::Error(value)) => format!("{}", value), Err(code) => format!("{:?}", code), } } #[test] fn test_recursion_limit() { let mut interp = Interp::new(); assert_eq!(interp.recursion_limit(), 1000); interp.set_recursion_limit(100); assert_eq!(interp.recursion_limit(), 100); assert!(dbg!(interp.eval("proc myproc {} { myproc }")).is_ok()); assert_eq!( interp.eval("myproc"), molt_err!("too many nested calls to Interp::eval (infinite loop?)") ); } //----------------------------------------------------------------------- // Context Cache tests #[test] fn context_basic_use() { let mut interp = Interp::new(); // Save a context object. let id = interp.save_context(String::from("ABC")); // Retrieve it. let ctx = interp.context::<String>(id); assert_eq!(*ctx, "ABC"); ctx.push_str("DEF"); let ctx = interp.context::<String>(id); assert_eq!(*ctx, "ABCDEF"); } #[test] fn context_advanced_use() { let mut interp = Interp::new(); // Save a context object. let id = interp.context_id(); interp.set_context(id, String::from("ABC")); // Retrieve it. let ctx = interp.context::<String>(id); assert_eq!(*ctx, "ABC"); } #[test] #[should_panic] fn context_unknown() { let mut interp = Interp::new(); // Valid ID Generated, but no context saved. let id = interp.context_id(); // Try to retrieve it. let _ctx = interp.context::<String>(id); // Should panic! } #[test] #[should_panic] fn context_wrong_type() { let mut interp = Interp::new(); // Save a context object. let id = interp.save_context(String::from("ABC")); // Try to retrieve it as something else. let _ctx = interp.context::<Vec<String>>(id); // Should panic! } #[test] #[should_panic] fn context_forget() { let mut interp = Interp::new(); // Save a context object. let id = interp.save_context(String::from("ABC")); // Retrieve it. let ctx = interp.context::<String>(id); assert_eq!(*ctx, "ABC"); // Forget it interp.forget_context(id); // Retrieve it; should panic. let _ctx = interp.context::<String>(id); } }