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
//! # Standard Molt Command Definitions
//!
//! This module defines the standard Molt commands.
use crate::{
dict::{dict_new, dict_path_insert, dict_path_remove, list_to_dict},
interp::Interp,
types::*,
util, *,
};
use std::fs;
cfg_if::cfg_if! {
if #[cfg(feature = "wasm")] {
use wasm_timer::Instant;
}else{
use std::time::Instant;
}
}
pub const _APPEND: &str = "append";
pub const _ARRAY: &str = "array";
pub const _ASSERT_EQ: &str = "assert_eq";
pub const _BREAK: &str = "break";
pub const _CATCH: &str = "catch";
pub const _CONTINUE: &str = "continue";
pub const _DICT: &str = "dict";
pub const _ERROR: &str = "error";
pub const _EXPR: &str = "expr";
pub const _FOR: &str = "for";
pub const _FOREACH: &str = "foreach";
pub const _GLOBAL: &str = "global";
pub const _IF: &str = "if";
pub const _INCR: &str = "incr";
pub const _INFO: &str = "info";
pub const _JOIN: &str = "join";
pub const _LAPPEND: &str = "lappend";
pub const _LINDEX: &str = "lindex";
pub const _LIST: &str = "list";
pub const _LLENGTH: &str = "llength";
pub const _PROC: &str = "proc";
pub const _PUTS: &str = "puts";
pub const _RENAME: &str = "rename";
pub const _RETURN: &str = "return";
pub const _SET: &str = "set";
pub const _STRING: &str = "string";
pub const _THROW: &str = "throw";
pub const _TIME: &str = "time";
pub const _UNSET: &str = "unset";
pub const _WHILE: &str = "while";
pub const _SOURCE: &str = "source";
pub const _EXIT: &str = "exit";
pub const _PARSE: &str = "parse";
pub const _PDUMP: &str = "pdump";
pub const _PCLEAR: &str = "pclear";
/// # append *varName* ?*value* ...?
///
/// Appends one or more strings to a variable.
/// See molt-book for full semantics.
pub fn cmd_append<Ctx>(interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(1, argv, 2, 0, "varName ?value value ...?")?;
// FIRST, get the value of the variable. If the variable is undefined,
// start with the empty string.
let mut new_string: String = interp
.var(&argv[1])
.and_then(|val| Ok(val.to_string()))
.unwrap_or_else(|_| String::new());
// NEXT, append the remaining values to the string.
for item in &argv[2..] {
new_string.push_str(item.as_str());
}
// NEXT, save and return the new value.
interp.set_var_return(&argv[1], new_string.into())
}
/// # array *subcommand* ?*arg*...?
///
/// https://www.tcl.tk/man/tcl8.6/TclCmd/array.htm
pub fn cmd_array<Ctx>(interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
// cfg_if::cfg_if! {
// if #[cfg(feature = "native_subcmd_help")] {
// let f = gen_subcommand!(
// Ctx,
// 1,
// [
// ("anymore", " ", cmd_todo, "[TODO] array anymore arrayName searchId"),
// ("donesearch", " ", cmd_todo, "[TODO] array donesearch arrayName searchId"),
// ("exists", " ", cmd_array_exists,"array exists arrayName"),
// ("get", " ", cmd_array_get, "array get arrayName ?pattern?"),
// ("names", " ", cmd_array_names, "array names arrayName ?mode? ?pattern?"),
// ("nextelement", "", cmd_todo, "[TODO] array nextelement arrayName searchId"),
// ("set", " ", cmd_array_set, "array set arrayName list"),
// ("size", " ", cmd_array_size, "array size arrayName"),
// ("startsearch", "", cmd_todo, "[TODO] array startsearch arrayName"),
// ("statistics", " ", cmd_todo, "[TODO] array statistics arrayName"),
// ("unset", " ", cmd_array_unset, "array unset arrayName ?pattern?"),
// ],
// );
// }else{
let f = _gen_subcommand_generic!(
1,
[
("exists", cmd_array_exists),
("get", cmd_array_get),
("names", cmd_array_names),
("set", cmd_array_set),
("size", cmd_array_size),
("unset", cmd_array_unset),
],
);
f(interp, argv)
}
/// # array exists arrayName
pub fn cmd_array_exists<Ctx>(interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(2, argv, 3, 3, "arrayName")?;
molt_ok!(Value::from(interp.array_exists(argv[2].as_str())))
}
/// # array names arrayName
/// TODO: Add glob matching as a feature, and support standard TCL options.
pub fn cmd_array_names<Ctx>(interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(2, argv, 3, 3, "arrayName")?;
molt_ok!(Value::from(interp.array_names(argv[2].as_str())))
}
/// # array get arrayname
/// TODO: Add glob matching as a feature, and support standard TCL options.
pub fn cmd_array_get<Ctx>(interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(2, argv, 3, 3, "arrayName")?;
molt_ok!(Value::from(interp.array_get(argv[2].as_str())))
}
/// # parse *script*
///
/// A command for parsing an arbitrary script and outputting the parsed form.
/// This is an undocumented debugging aid. The output can be greatly improved.
pub fn cmd_parse<Ctx>(_interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(1, argv, 2, 2, "script")?;
let script = &argv[1];
molt_ok!(format!("{:?}", parser::parse(script.as_str())?))
}
/// # array set arrayName list
pub fn cmd_array_set<Ctx>(interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(2, argv, 4, 4, "arrayName list")?;
// This odd little dance provides the same semantics as Standard TCL. If the
// given var_name has an index, the array is created (if it didn't exist)
// but no data is added to it, and the command returns an error.
let var_name = argv[2].as_var_name();
if var_name.index().is_none() {
interp.array_set(var_name.name(), &*argv[3].as_list()?)
} else {
// This line will create the array if it doesn't exist, and throw an error if the
// named variable exists but isn't an array. This is a little wacky, but it's
// what TCL 8.6 does.
interp.array_set(var_name.name(), &*Value::empty().as_list()?)?;
// And this line throws an error because the full name the caller specified is an
// element, not the array itself.
molt_err!("can't set \"{}\": variable isn't array", &argv[2])
}
}
/// # array size arrayName
pub fn cmd_array_size<Ctx>(interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(2, argv, 3, 3, "arrayName")?;
molt_ok!(Value::from(interp.array_size(argv[2].as_str()) as MoltInt))
}
/// # array unset arrayName ?*index*?
pub fn cmd_array_unset<Ctx>(interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(2, argv, 3, 4, "arrayName ?index?")?;
if argv.len() == 3 {
interp.array_unset(argv[2].as_str());
} else {
interp.unset_element(argv[2].as_str(), argv[3].as_str());
}
molt_ok!()
}
/// assert_eq received, expected
///
/// Asserts that two values have identical string representations.
/// See molt-book for full semantics.
pub fn cmd_assert_eq<Ctx>(_interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(1, argv, 3, 3, "received expected")?;
if argv[1] == argv[2] {
molt_ok!()
} else {
molt_err!("assertion failed: received \"{}\", expected \"{}\".", argv[1], argv[2])
}
}
/// # break
///
/// Breaks a loops.
/// See molt-book for full semantics.
pub fn cmd_break<Ctx>(_interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(1, argv, 1, 1, "")?;
Err(Exception::molt_break())
}
/// catch script ?resultVarName? ?optionsVarName?
///
/// Executes a script, returning the result code. If the resultVarName is given, the result
/// of executing the script is returned in it. The result code is returned as an integer,
/// 0=Ok, 1=Error, 2=Return, 3=Break, 4=Continue.
pub fn cmd_catch<Ctx>(interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(1, argv, 2, 4, "script ?resultVarName? ?optionsVarName?")?;
// If the script called `return x`, should get Return, -level 1, -code Okay here
let result = interp.eval_value(&argv[1]);
let (code, value) = match &result {
Ok(val) => (0, val.clone()),
Err(exception) => match exception.code() {
ResultCode::Okay => unreachable!(), // Should not be reachable here.
ResultCode::Error => (1, exception.value()),
ResultCode::Return => (2, exception.value()),
ResultCode::Break => (3, exception.value()),
ResultCode::Continue => (4, exception.value()),
ResultCode::Other(_) => unimplemented!(), // TODO: Not in use yet
},
};
if argv.len() >= 3 {
interp.set_var(&argv[2], value)?;
}
if argv.len() == 4 {
interp.set_var(&argv[3], interp.return_options(&result))?;
}
Ok(Value::from(code))
}
/// # continue
///
/// Continues with the next iteration of the inmost loop.
pub fn cmd_continue<Ctx>(_interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(1, argv, 1, 1, "")?;
Err(Exception::molt_continue())
}
/// # dict *subcommand* ?*arg*...?
///
/// https://www.tcl.tk/man/tcl8.6/TclCmd/dict.htm
pub fn cmd_dict<Ctx>(interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
// cfg_if::cfg_if! {
// if #[cfg(feature = "native_subcmd_help")] {
// let f = gen_subcommand!(
// Ctx,
// 1,
// [
// ("append", " ", cmd_todo, "[TODO] dict append dictionaryVariable key ?string ...?"),
// ("create", " ", cmd_dict_new,"dict create ?key value ...?"),
// ("exists", " ", cmd_dict_exists,"dict exists dictionaryValue key ?key ...?"),
// ("filter", " ", cmd_todo, "[TODO] dict filter dictionaryValue filterType arg ?arg ...?"),
// // dict filter dictionaryValue key ?globPattern ...?
// // dict filter dictionaryValue script {keyVariable valueVariable} script
// // dict filter dictionaryValue value ?globPattern ...?
// ("for", " ", cmd_todo, "[TODO] dict for {keyVariable valueVariable} dictionaryValue body"),
// ("get", " ", cmd_dict_get,"dict get dictionaryValue ?key ...?"),
// ("incr", " ", cmd_todo,"[TODO] dict incr dictionaryVariable key ?increment?"),
// ("info", " ", cmd_todo,"[TODO] dict info dictionaryValue"),
// ("keys", " ", cmd_dict_keys,"dict keys dictionaryValue ?globPattern?"),
// ("lappend", "", cmd_todo,"[TODO] dict lappend dictionaryVariable key ?value ...?"),
// ("map", " ", cmd_todo,"[TODO] dict map {keyVariable valueVariable} dictionaryValue body"),
// ("merge", " ", cmd_todo,"[TODO] dict merge ?dictionaryValue ...?"),
// ("remove", " ", cmd_dict_remove,"dict remove dictionaryValue ?key ...?"),
// ("replace", "", cmd_todo,"[TODO] dict replace dictionaryValue ?key value ...?"),
// ("set", " ", cmd_dict_set,"dict set dictionaryVariable key ?key ...? value"),
// ("size", " ", cmd_dict_size,"dict size dictionaryValue"),
// ("unset", " ", cmd_dict_unset,"dict unset dictionaryVariable key ?key ...?"),
// ("update", " ", cmd_todo,"[TODO] dict update dictionaryVariable key varName ?key varName ...? body"),
// ("values", " ", cmd_dict_values,"dict values dictionaryValue ?globPattern?"),
// ("with", " ", cmd_todo,"[TODO] dict with dictionaryVariable ?key ...? body"),
// ],
// );
// }else{
let f = _gen_subcommand_generic!(
1,
[
("create", cmd_dict_new),
("exists", cmd_dict_exists),
("get", cmd_dict_get),
("keys", cmd_dict_keys),
("remove", cmd_dict_remove),
("set", cmd_dict_set),
("size", cmd_dict_size),
("unset", cmd_dict_unset),
("values", cmd_dict_values),
],
);
// }
// }
f(interp, argv)
}
/// # dict create ?key value ...?
fn cmd_dict_new<Ctx>(_interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
// FIRST, we need an even number of arguments.
if argv.len() % 2 != 0 {
return molt_err!(
"wrong # args: should be \"{} {}\"",
Value::from(&argv[0..2]).to_string(),
"?key value?"
);
}
// NEXT, return the value.
if argv.len() > 2 {
molt_ok!(Value::from(list_to_dict(&argv[2..])))
} else {
molt_ok!(Value::from(dict_new()))
}
}
/// # dict exists *dictionary* key ?*key* ...?
fn cmd_dict_exists<Ctx>(_interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(2, argv, 4, 0, "dictionary key ?key ...?")?;
let mut value: Value = argv[2].clone();
let indices = &argv[3..];
for index in indices {
if let Ok(dict) = value.as_dict() {
if let Some(val) = dict.get(index) {
value = val.clone();
} else {
return molt_ok!(false);
}
} else {
return molt_ok!(false);
}
}
molt_ok!(true)
}
/// # dict get *dictionary* ?*key* ...?
fn cmd_dict_get<Ctx>(_interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(2, argv, 3, 0, "dictionary ?key ...?")?;
let mut value: Value = argv[2].clone();
let indices = &argv[3..];
for index in indices {
let dict = value.as_dict()?;
if let Some(val) = dict.get(index) {
value = val.clone();
} else {
return molt_err!("key \"{}\" not known in dictionary", index);
}
}
molt_ok!(value)
}
/// # dict keys *dictionary*
/// TODO: Add filtering when we have glob matching.
fn cmd_dict_keys<Ctx>(_interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(2, argv, 3, 3, "dictionary")?;
let dict = argv[2].as_dict()?;
let keys: MoltList = dict.keys().cloned().collect();
molt_ok!(keys)
}
/// # dict remove *dictionary* ?*key* ...?
fn cmd_dict_remove<Ctx>(_interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(2, argv, 3, 0, "dictionary ?key ...?")?;
// FIRST, get and clone the dictionary, so we can modify it.
let mut dict = (&*argv[2].as_dict()?).clone();
// NEXT, remove the given keys.
for key in &argv[3..] {
// shift_remove preserves the order of the keys.
dict.shift_remove(key);
}
// NEXT, return it as a new Value.
molt_ok!(dict)
}
/// # dict set *dictVarName* *key* ?*key* ...? *value*
fn cmd_dict_set<Ctx>(interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(2, argv, 5, 0, "dictVarName key ?key ...? value")?;
let value = &argv[argv.len() - 1];
let keys = &argv[3..(argv.len() - 1)];
if let Ok(old_dict_val) = interp.var(&argv[2]) {
interp.set_var_return(&argv[2], dict_path_insert(&old_dict_val, keys, value)?)
} else {
let new_val = Value::from(dict_new());
interp.set_var_return(&argv[2], dict_path_insert(&new_val, keys, value)?)
}
}
/// # dict size *dictionary*
fn cmd_dict_size<Ctx>(_interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(2, argv, 3, 3, "dictionary")?;
let dict = argv[2].as_dict()?;
molt_ok!(dict.len() as MoltInt)
}
/// # dict unset *dictVarName* *key* ?*key* ...?
fn cmd_dict_unset<Ctx>(interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(2, argv, 4, 0, "dictVarName key ?key ...?")?;
let keys = &argv[3..];
if let Ok(old_dict_val) = interp.var(&argv[2]) {
interp.set_var_return(&argv[2], dict_path_remove(&old_dict_val, keys)?)
} else {
let new_val = Value::from(dict_new());
interp.set_var_return(&argv[2], dict_path_remove(&new_val, keys)?)
}
}
/// # dict values *dictionary*
/// TODO: Add filtering when we have glob matching.
fn cmd_dict_values<Ctx>(_interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(2, argv, 3, 3, "dictionary")?;
let dict = argv[2].as_dict()?;
let values: MoltList = dict.values().cloned().collect();
molt_ok!(values)
}
/// error *message*
///
/// Returns an error with the given message.
///
/// ## TCL Liens
///
/// * In Standard TCL, `error` can optionally set the stack trace and an error code.
pub fn cmd_error<Ctx>(_interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(1, argv, 2, 2, "message")?;
molt_err!(argv[1].clone())
}
/// # exit ?*returnCode*?
///
/// Terminates the application by calling `std::process::exit()`.
/// If given, _returnCode_ must be an integer return code; if absent, it
/// defaults to 0.
pub fn cmd_exit<Ctx>(_interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(1, argv, 1, 2, "?returnCode?")?;
let return_code: MoltInt = if argv.len() == 1 { 0 } else { argv[1].as_int()? };
std::process::exit(return_code as i32)
}
/// # expr expr
///
/// Evaluates an expression and returns its result.
///
/// ## TCL Liens
///
/// See the Molt Book.
pub fn cmd_expr<Ctx>(interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(1, argv, 2, 0, "expr")?;
if argv.len() == 2 {
interp.expr(&argv[1])
} else {
let values = argv[1..].iter().map(|v| v.as_str()).collect::<Vec<_>>();
interp.expr(&Value::from(values.join(" ")))
}
}
/// # for *start* *test* *next* *command*
///
/// A standard "for" loop. start, next, and command are scripts; test is an expression
///
pub fn cmd_for<Ctx>(interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(1, argv, 5, 5, "start test next command")?;
let start = &argv[1];
let test = &argv[2];
let next = &argv[3];
let command = &argv[4];
// Start
interp.eval_value(start)?;
while interp.expr_bool(test)? {
let result = interp.eval_value(command);
if let Err(exception) = result {
match exception.code() {
ResultCode::Break => break,
ResultCode::Continue => (),
_ => return Err(exception),
}
}
// Execute next script. Break is allowed, but continue is not.
let result = interp.eval_value(next);
if let Err(exception) = result {
match exception.code() {
ResultCode::Break => break,
ResultCode::Continue => {
return molt_err!("invoked \"continue\" outside of a loop");
}
_ => return Err(exception),
}
}
}
molt_ok!()
}
/// # foreach *varList* *list* *body*
///
/// Loops over the items the list, assigning successive items to the variables in the
/// *varList* and calling the *body* as a script once for each set of assignments.
/// On the last iteration, the second and subsequents variables in the *varList* will
/// be assigned the empty string if there are not enough list elements to fill them.
///
/// ## TCL Liens
///
/// * In Standard TCL, `foreach` can loop over several lists at the same time.
pub fn cmd_foreach<Ctx>(interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(1, argv, 4, 4, "varList list body")?;
let var_list = &*argv[1].as_list()?;
let list = &*argv[2].as_list()?;
let body = &argv[3];
let mut i = 0;
while i < list.len() {
for var in var_list {
if i < list.len() {
interp.set_var(&var, list[i].clone())?;
i += 1;
} else {
interp.set_var(&var, Value::empty())?;
}
}
let result = interp.eval_value(body);
if let Err(exception) = result {
match exception.code() {
ResultCode::Break => break,
ResultCode::Continue => (),
_ => return Err(exception),
}
}
}
molt_ok!()
}
/// # global ?*varName* ...?
///
/// Appends any number of values to a variable's value, which need not
/// initially exist.
pub fn cmd_global<Ctx>(interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
// Accepts any number of arguments
// FIRST, if we're at the global scope this is a no-op.
if interp.scope_level() > 0 {
for name in &argv[1..] {
// TODO: Should upvar take the name as a Value?
interp.upvar(0, name.as_str());
}
}
molt_ok!()
}
#[derive(Eq, PartialEq, Debug)]
enum IfWants {
Expr,
ThenBody,
SkipThenClause,
ElseClause,
ElseBody,
}
/// # if *expr* ?then? *script* elseif *expr* ?then? *script* ... ?else? ?*script*?
///
/// Standard conditional. Returns the value of the selected script (or
/// "" if there is no else body and the none of the previous branches were selected).
///
/// # TCL Liens
///
/// * Because we don't yet have an expression parser, the *expr* arguments are evaluated as
/// scripts that must return a boolean value.
pub fn cmd_if<Ctx>(interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
let mut argi = 1;
let mut wants = IfWants::Expr;
while argi < argv.len() {
match wants {
IfWants::Expr => {
wants = if interp.expr_bool(&argv[argi])? {
IfWants::ThenBody
} else {
IfWants::SkipThenClause
};
}
IfWants::ThenBody => {
if argv[argi].as_str() == "then" {
argi += 1;
}
if argi < argv.len() {
return interp.eval_value(&argv[argi]);
} else {
break;
}
}
IfWants::SkipThenClause => {
if argv[argi].as_str() == "then" {
argi += 1;
}
if argi < argv.len() {
argi += 1;
wants = IfWants::ElseClause;
}
continue;
}
IfWants::ElseClause => {
if argv[argi].as_str() == "elseif" {
wants = IfWants::Expr;
} else {
wants = IfWants::ElseBody;
continue;
}
}
IfWants::ElseBody => {
if argv[argi].as_str() == "else" {
argi += 1;
// If "else" appears, then the else body is required.
if argi == argv.len() {
return molt_err!(
"wrong # args: no script following after \"{}\" argument",
argv[argi - 1]
);
}
}
if argi < argv.len() {
return interp.eval_value(&argv[argi]);
} else {
break;
}
}
}
argi += 1;
}
if argi < argv.len() {
return molt_err!(
"wrong # args: extra words after \"else\" clause in \"if\" command"
);
} else if wants == IfWants::Expr {
return molt_err!(
"wrong # args: no expression after \"{}\" argument",
argv[argi - 1]
);
} else if wants == IfWants::ThenBody || wants == IfWants::SkipThenClause {
return molt_err!(
"wrong # args: no script following after \"{}\" argument",
argv[argi - 1]
);
} else {
// Looking for ElseBody, but there doesn't need to be one.
molt_ok!() // temp
}
}
/// # incr *varName* ?*increment* ...?
///
/// Increments an integer variable by a value.
pub fn cmd_incr<Ctx>(interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(1, argv, 2, 3, "varName ?increment?")?;
let increment: MoltInt = if argv.len() == 3 { argv[2].as_int()? } else { 1 };
let new_value = increment
+ interp
.var(&argv[1])
.and_then(|val| Ok(val.as_int()?))
.unwrap_or_else(|_| 0);
interp.set_var_return(&argv[1], new_value.into())
}
/// # info *subcommand* ?*arg*...?
pub fn cmd_info<Ctx>(interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
let f = _gen_subcommand_generic!(
1,
[
("args", cmd_info_args),
("body", cmd_info_body),
("cmdtype", cmd_info_cmdtype),
("commands", cmd_info_commands),
("complete", cmd_info_complete),
("default", cmd_info_default),
("exists", cmd_info_exists),
("globals", cmd_info_globals),
("locals", cmd_info_locals),
("procs", cmd_info_procs),
("vars", cmd_info_vars),
],
);
f(interp, argv)
}
/// # info args *procname*
pub fn cmd_info_args<Ctx>(interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(2, argv, 3, 3, "procname")?;
interp.proc_args(&argv[2].as_str())
}
/// # info body *procname*
pub fn cmd_info_body<Ctx>(interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(2, argv, 3, 3, "procname")?;
interp.proc_body(&argv[2].as_str())
}
/// # info cmdtype *command*
pub fn cmd_info_cmdtype<Ctx>(interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(2, argv, 3, 3, "command")?;
interp.command_type(&argv[2].as_str())
}
/// # info commands ?*pattern*?
pub fn cmd_info_commands<Ctx>(interp: &mut Interp<Ctx>, _argv: &[Value]) -> MoltResult {
molt_ok!(Value::from(interp.command_names()))
}
/// # info default *procname* *arg* *varname*
pub fn cmd_info_default<Ctx>(interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(2, argv, 5, 5, "procname arg varname")?;
if let Some(val) = interp.proc_default(&argv[2].as_str(), &argv[3].as_str())? {
interp.set_var(&argv[4], val)?;
molt_ok!(1)
} else {
interp.set_var(&argv[4], Value::empty())?;
molt_ok!(0)
}
}
/// # info exists *varname*
pub fn cmd_info_exists<Ctx>(interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(2, argv, 3, 3, "varname")?;
Ok(interp.var_exists(&argv[2]).into())
}
/// # info complete *command*
pub fn cmd_info_complete<Ctx>(interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(2, argv, 3, 3, "command")?;
if interp.complete(argv[2].as_str()) {
molt_ok!(true)
} else {
molt_ok!(false)
}
}
/// # info globals
/// TODO: Add glob matching as a feature, and provide optional pattern argument.
pub fn cmd_info_globals<Ctx>(interp: &mut Interp<Ctx>, _argv: &[Value]) -> MoltResult {
molt_ok!(Value::from(interp.vars_in_global_scope()))
}
/// # info locals
/// TODO: Add glob matching as a feature, and provide optional pattern argument.
pub fn cmd_info_locals<Ctx>(interp: &mut Interp<Ctx>, _argv: &[Value]) -> MoltResult {
molt_ok!(Value::from(interp.vars_in_local_scope()))
}
/// # info procs ?*pattern*?
pub fn cmd_info_procs<Ctx>(interp: &mut Interp<Ctx>, _argv: &[Value]) -> MoltResult {
molt_ok!(Value::from(interp.proc_names()))
}
/// # info vars
/// TODO: Add glob matching as a feature, and provide optional pattern argument.
pub fn cmd_info_vars<Ctx>(interp: &mut Interp<Ctx>, _argv: &[Value]) -> MoltResult {
molt_ok!(Value::from(interp.vars_in_scope()))
}
/// # join *list* ?*joinString*?
///
/// Joins the elements of a list with a string. The join string defaults to " ".
pub fn cmd_join<Ctx>(_interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(1, argv, 2, 3, "list ?joinString?")?;
let list = &argv[1].as_list()?;
let join_string = if argv.len() == 3 { argv[2].to_string() } else { " ".to_string() };
// TODO: Need to implement a standard join() method for MoltLists.
let list: Vec<String> = list.iter().map(|v| v.to_string()).collect();
molt_ok!(list.join(&join_string))
}
/// # lappend *varName* ?*value* ...?
///
/// Appends any number of values to a variable's list value, which need not
/// initially exist.
pub fn cmd_lappend<Ctx>(interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(1, argv, 2, 0, "varName ?value ...?")?;
let var_result = interp.var(&argv[1]);
let mut list: MoltList = if var_result.is_ok() {
var_result.expect("got value").to_list()?
} else {
Vec::new()
};
let mut values = argv[2..].to_owned();
list.append(&mut values);
interp.set_var_return(&argv[1], Value::from(list))
}
/// # lindex *list* ?*index* ...?
///
/// Returns an element from the list, indexing into nested lists.
pub fn cmd_lindex<Ctx>(_interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(1, argv, 2, 0, "list ?index ...?")?;
if argv.len() != 3 {
lindex_into(&argv[1], &argv[2..])
} else {
lindex_into(&argv[1], &*argv[2].as_list()?)
}
}
pub fn lindex_into(list: &Value, indices: &[Value]) -> MoltResult {
let mut value: Value = list.clone();
for index_val in indices {
let list = value.as_list()?;
let index = index_val.as_int()?;
value = if index < 0 || index as usize >= list.len() {
Value::empty()
} else {
list[index as usize].clone()
};
}
molt_ok!(value)
}
/// # list ?*arg*...?
///
/// Converts its arguments into a canonical list.
pub fn cmd_list<Ctx>(_interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
// No arg check needed; can take any number.
molt_ok!(&argv[1..])
}
/// # llength *list*
///
/// Returns the length of the list.
pub fn cmd_llength<Ctx>(_interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(1, argv, 2, 2, "list")?;
molt_ok!(argv[1].as_list()?.len() as MoltInt)
}
/// # pdump
///
/// Dumps profile data. Developer use only.
pub fn cmd_pdump<Ctx>(interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(1, argv, 1, 1, "")?;
interp.profile_dump();
molt_ok!()
}
/// # pclear
///
/// Clears profile data. Developer use only.
pub fn cmd_pclear<Ctx>(interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(1, argv, 1, 1, "")?;
interp.profile_clear();
molt_ok!()
}
/// # proc *name* *args* *body*
///
/// Defines a procedure.
pub fn cmd_proc<Ctx>(interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(1, argv, 4, 4, "name args body")?;
// FIRST, get the arguments
let name = argv[1].as_str();
let args = &*argv[2].as_list()?;
// NEXT, validate the argument specs
for arg in args {
let vec = arg.as_list()?;
if vec.is_empty() {
return molt_err!("argument with no name");
} else if vec.len() > 2 {
return molt_err!("too many fields in argument specifier \"{}\"", arg);
}
}
// NEXT, add the command.
interp.add_proc(name, args, &argv[3]);
molt_ok!()
}
/// # puts *string*
///
/// Outputs the string to stdout.
///
/// ## TCL Liens
///
/// * Does not support `-nonewline`
/// * Does not support `channelId`
pub fn cmd_puts<Ctx>(interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(1, argv, 2, 2, "string")?;
cfg_if::cfg_if! {
if #[cfg(feature = "std_buff")] {
interp.std_buff.push(Ok(argv[1].clone()));
} else {
println!("{}", argv[1]);
}
}
molt_ok!()
}
// /// # rename *oldName* *newName*
// ///
// /// Renames the command called *oldName* to have the *newName*. If the
// /// *newName* is "", the command is destroyed.
pub fn cmd_rename<Ctx>(interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(1, argv, 3, 3, "oldName newName")?;
// FIRST, get the arguments
let old_name = argv[1].as_str();
let new_name = argv[2].as_str();
if !interp.has_proc(old_name) {
return molt_err!("can't rename \"{}\": command doesn't exist", old_name);
}
// NEXT, rename or remove the command.
if new_name.is_empty() {
interp.remove_proc(old_name);
} else {
interp.rename_proc(old_name, new_name);
}
molt_ok!()
}
/// # return ?-code code? ?-level level? ?value?
///
/// Returns from a proc with the given *value*, which defaults to the empty result.
/// See the documentation for **return** in The Molt Book for the option semantics.
///
/// ## TCL Liens
///
/// * Doesn't support all of TCL's fancy return machinery. Someday it will.
pub fn cmd_return<Ctx>(_interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(1, argv, 1, 0, "?options...? ?value?")?;
// FIRST, set the defaults
let mut code = ResultCode::Okay;
let mut level: MoltInt = 1;
let mut error_code: Option<Value> = None;
let mut error_info: Option<Value> = None;
// NEXT, with no arguments just return.
if argv.len() == 1 {
return Err(Exception::molt_return_ext(Value::empty(), level as usize, code));
}
// NEXT, get the return value: the last argument, if there's an odd number of arguments
// after the command name.
let return_value: Value;
let opt_args: &[Value] = if argv.len() % 2 == 0 {
// odd number of args following the command name
return_value = argv[argv.len() - 1].clone();
&argv[1..argv.len() - 1]
} else {
// even number of args following the command name
return_value = Value::empty();
&argv[1..argv.len()]
};
// NEXT, Get any options
let mut queue = opt_args.iter();
while let Some(opt) = queue.next() {
// We built the queue to have an even number of arguments, and every option requires
// a value; so there can't be a missing option value.
let val = queue
.next()
.expect("missing option value: coding error in cmd_return");
match opt.as_str() {
"-code" => {
code = ResultCode::from_value(val)?;
}
"-errorcode" => {
error_code = Some(val.clone());
}
"-errorinfo" => {
error_info = Some(val.clone());
}
"-level" => {
// TODO: return better error:
// bad -level value: expected non-negative integer but got "{}"
level = val.as_int()?;
}
// TODO: In standard TCL there are no invalid options; all options are retained.
_ => return molt_err!("invalid return option: \"{}\"", opt),
}
}
// NEXT, return the result: normally a Return exception, but could be "Ok".
if code == ResultCode::Error {
Err(Exception::molt_return_err(
return_value,
level as usize,
error_code,
error_info,
))
} else if level == 0 && code == ResultCode::Okay {
// Not an exception!j
Ok(return_value)
} else {
Err(Exception::molt_return_ext(return_value, level as usize, code))
}
}
/// # set *varName* ?*newValue*?
///
/// Sets variable *varName* to *newValue*, returning the value.
/// If *newValue* is omitted, returns the variable's current value,
/// returning an error if the variable is unknown.
pub fn cmd_set<Ctx>(interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(1, argv, 2, 3, "varName ?newValue?")?;
if argv.len() == 3 {
interp.set_var_return(&argv[1], argv[2].clone())
} else {
molt_ok!(interp.var(&argv[1])?)
}
}
/// # source *filename*
///
/// Sources the file, returning the result.
pub fn cmd_source<Ctx>(interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(1, argv, 2, 2, "filename")?;
let filename = argv[1].as_str();
match fs::read_to_string(filename) {
Ok(script) => interp.eval(&script),
Err(e) => molt_err!("couldn't read file \"{}\": {}", filename, e),
}
}
/// # string *subcommand* ?*arg*...?
///
/// https://www.tcl.tk/man/tcl8.6/TclCmd/string.htm
pub fn cmd_string<Ctx>(interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
// cfg_if::cfg_if! {
// if #[cfg(feature = "native_subcmd_help")] {
// let f = gen_subcommand!(
// Ctx,
// 1,
// [
// ("cat"," ", cmd_string_cat,"string cat ?string1? ?string2...?"),
// ("compare"," ", cmd_string_compare,"string compare ?-nocase? ?-length length? string1 string2"),
// ("equal"," ", cmd_string_equal,"string equal ?-nocase? ?-length length? string1 string2"),
// ("first"," ", cmd_string_first,"string first needleString haystackString ?startIndex?"),
// ("index"," ", cmd_todo,"string index string charIndex"),
// ("is"," ", cmd_todo,"[TODO] string is class ?-strict? ?-failindex varname? string"),
// ("last"," ", cmd_string_last,"string last needleString haystackString ?lastIndex?"),
// ("length"," ", cmd_string_length,"string length string"),
// ("map"," ", cmd_string_map,"string map ?-nocase? mapping string"),
// ("match"," ", cmd_todo,"[TODO] string match ?-nocase? pattern string"),
// ("range"," ", cmd_string_range,"string range string first last"),
// ("repeat"," ", cmd_todo,"[TODO] string repeat string count"),
// ("replace"," ", cmd_todo,"[TODO] string replace string first last ?newstring?"),
// ("reverse"," ", cmd_todo,"[TODO] string reverse string"),
// ("tolower"," ", cmd_string_tolower,"string tolower string ?first? ?last?"),
// ("totitle"," ", cmd_todo,"[TODO] string totitle string ?first? ?last?"),
// ("toupper"," ", cmd_string_toupper,"string toupper string ?first? ?last?"),
// ("trim"," ", cmd_string_trim,"string trim string ?chars?"),
// ("trimleft"," ", cmd_string_trim,"string trimleft string ?chars?"),
// ("trimright"," ", cmd_string_trim,"string trimright string ?chars?"),
// ("bytelength","", cmd_todo,"[TODO] string bytelength string"),
// ("wordend"," ", cmd_todo,"[TODO] string wordend string charIndex"),
// ("wordstart"," ", cmd_todo,"[TODO] string wordstart string charIndex"),
// ],
// );
// }else{
let f = _gen_subcommand_generic!(
1,
[
("cat", cmd_string_cat),
("compare", cmd_string_compare),
("equal", cmd_string_equal),
("first", cmd_string_first),
// ("index", cmd_todo),
("last", cmd_string_last),
("length", cmd_string_length),
("map", cmd_string_map),
("range", cmd_string_range),
// ("replace", cmd_todo),
// ("repeat", cmd_todo),
// ("reverse", cmd_todo),
("tolower", cmd_string_tolower),
("toupper", cmd_string_toupper),
("trim", cmd_string_trim),
("trimleft", cmd_string_trim),
("trimright", cmd_string_trim),
],
);
// }
// }
f(interp, argv)
}
/// TODO cmds
pub fn cmd_todo<Ctx>(interp: &mut Interp<Ctx>, _argv: &[Value]) -> MoltResult {
molt_err!("TODO")
}
/// string cat ?*arg* ...?
pub fn cmd_string_cat<Ctx>(_interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
let mut buff = String::new();
for arg in &argv[2..] {
buff.push_str(arg.as_str());
}
molt_ok!(buff)
}
/// string compare ?-nocase? ?-length length? string1 string2
pub fn cmd_string_compare<Ctx>(_interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(2, argv, 4, 7, "?-nocase? ?-length length? string1 string2")?;
// FIRST, set the defaults.
let arglen = argv.len();
let mut nocase = false;
let mut length: Option<MoltInt> = None;
// NEXT, get options
let opt_args = &argv[2..arglen - 2];
let mut queue = opt_args.iter();
while let Some(opt) = queue.next() {
match opt.as_str() {
"-nocase" => nocase = true,
"-length" => {
if let Some(val) = queue.next() {
length = Some(val.as_int()?);
} else {
return molt_err!("wrong # args: should be \"string compare ?-nocase? ?-length length? string1 string2\"");
}
}
_ => return molt_err!("bad option \"{}\": must be -nocase or -length", opt),
}
}
if nocase {
let val1 = &argv[arglen - 2];
let val2 = &argv[arglen - 1];
// TODO: *Not* the best way to do this; consider using the unicase crate.
let val1 = Value::from(val1.as_str().to_lowercase());
let val2 = Value::from(val2.as_str().to_lowercase());
molt_ok!(util::compare_len(val1.as_str(), val2.as_str(), length)?)
} else {
molt_ok!(util::compare_len(
argv[arglen - 2].as_str(),
argv[arglen - 1].as_str(),
length
)?)
}
}
/// string equal ?-nocase? ?-length length? string1 string2
pub fn cmd_string_equal<Ctx>(_interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(2, argv, 4, 7, "?-nocase? ?-length length? string1 string2")?;
// FIRST, set the defaults.
let arglen = argv.len();
let mut nocase = false;
let mut length: Option<MoltInt> = None;
// NEXT, get options
let opt_args = &argv[2..arglen - 2];
let mut queue = opt_args.iter();
while let Some(opt) = queue.next() {
match opt.as_str() {
"-nocase" => nocase = true,
"-length" => {
if let Some(val) = queue.next() {
length = Some(val.as_int()?);
} else {
return molt_err!("wrong # args: should be \"string equal ?-nocase? ?-length length? string1 string2\"");
}
}
_ => return molt_err!("bad option \"{}\": must be -nocase or -length", opt),
}
}
if nocase {
let val1 = &argv[arglen - 2];
let val2 = &argv[arglen - 1];
// TODO: *Not* the best way to do this; consider using the unicase crate.
let val1 = Value::from(val1.as_str().to_lowercase());
let val2 = Value::from(val2.as_str().to_lowercase());
let flag = util::compare_len(val1.as_str(), val2.as_str(), length)? == 0;
molt_ok!(flag)
} else {
let flag = util::compare_len(
argv[arglen - 2].as_str(),
argv[arglen - 1].as_str(),
length,
)? == 0;
molt_ok!(flag)
}
}
/// string first *needleString* *haystackString* ?*startIndex*?
pub fn cmd_string_first<Ctx>(_interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(2, argv, 4, 5, "needleString haystackString ?startIndex?")?;
let needle = argv[2].as_str();
let haystack = argv[3].as_str();
let start_char: usize = if argv.len() == 5 {
let arg = argv[4].as_int()?;
if arg < 0 {
0
} else {
arg as usize
}
} else {
0
};
let pos_byte: Option<usize> = haystack
.char_indices()
.nth(start_char)
.and_then(|(start_byte, _)| haystack[start_byte..].find(needle));
let pos_char: MoltInt = match pos_byte {
None => -1,
Some(b) => {
haystack[b..].char_indices().take_while(|(i, _)| *i < b).count() as MoltInt
+ start_char as MoltInt
}
};
molt_ok!(pos_char)
}
/// string last *needleString* *haystackString* ?*lastIndex*?
pub fn cmd_string_last<Ctx>(_interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(2, argv, 4, 5, "needleString haystackString ?lastIndex?")?;
let needle = argv[2].as_str();
let haystack = argv[3].as_str();
let count = haystack.chars().count();
let last: Option<usize> = if argv.len() == 5 {
let arg = argv[4].as_int()?;
if arg < 0 {
return molt_ok!(-1);
}
if arg as usize >= count {
None
} else {
Some(arg as usize)
}
} else {
None
};
let slice = match last {
None => haystack,
Some(n) => match haystack.char_indices().nth(n + 1) {
None => haystack,
Some((byte, _)) => &haystack[..byte],
},
};
let pos_byte = slice.rfind(needle);
let pos_char: MoltInt = match pos_byte {
None => -1,
Some(b) => haystack.char_indices().take_while(|(i, _)| *i < b).count() as MoltInt,
};
molt_ok!(pos_char)
}
/// string length *string*
pub fn cmd_string_length<Ctx>(_interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(2, argv, 3, 3, "string")?;
let len: MoltInt = argv[2].as_str().chars().count() as MoltInt;
molt_ok!(len)
}
/// string map ?-nocase? *charMap* *string*
pub fn cmd_string_map<Ctx>(_interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(2, argv, 4, 5, "?-nocase? charMap string")?;
let mut nocase = false;
if argv.len() == 5 {
let opt = argv[2].as_str();
if opt == "-nocase" {
nocase = true;
} else {
return molt_err!("bad option \"{}\": must be -nocase", opt);
}
}
let char_map = argv[argv.len() - 2].as_dict()?;
let s = argv[argv.len() - 1].as_str();
let filtered_keys = char_map
.iter()
.map(|(k, v)| {
let new_k =
if nocase { Value::from(k.as_str().to_lowercase()) } else { k.clone() };
let count = new_k.as_str().chars().count();
(new_k, count, v.clone())
})
.filter(|(_, count, _)| *count > 0)
.collect::<Vec<_>>();
let string_lower: Option<String> = if nocase { Some(s.to_lowercase()) } else { None };
let mut result = String::new();
let mut skip = 0;
for (i, C) in s.char_indices() {
if skip > 0 {
skip -= 1;
continue;
}
let mut matched = false;
for (from, from_char_count, to) in &filtered_keys {
let haystack: &str = match &string_lower {
Some(x) => &x[i..],
None => &s[i..],
};
if haystack.starts_with(&from.as_str()) {
matched = true;
result.push_str(to.as_str());
skip = from_char_count - 1;
break;
}
}
if !matched {
result.push(C);
}
}
molt_ok!(result)
}
/// string range *string* *first* *last*
pub fn cmd_string_range<Ctx>(_interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(2, argv, 5, 5, "string first last")?;
let s = argv[2].as_str();
let first = argv[3].as_int()?;
let last = argv[4].as_int()?;
if last < 0 {
return molt_ok!("");
}
let clamp = { |i: MoltInt| if i < 0 { 0 } else { i } };
let substr = s
.chars()
.skip(clamp(first) as usize)
.take((clamp(last) - clamp(first) + 1) as usize)
.collect::<String>();
molt_ok!(substr)
}
/// string tolower *string*
pub fn cmd_string_tolower<Ctx>(_interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(2, argv, 3, 3, "string")?;
let lower = argv[2].as_str().to_lowercase();
molt_ok!(lower)
}
/// string toupper *string*
pub fn cmd_string_toupper<Ctx>(_interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(2, argv, 3, 3, "string")?;
let upper = argv[2].as_str().to_uppercase();
molt_ok!(upper)
}
/// string (trim|trimleft|trimright) *string*
pub fn cmd_string_trim<Ctx>(_interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(2, argv, 3, 3, "string")?;
let s = argv[2].as_str();
let trimmed = match argv[1].as_str() {
"trimleft" => s.trim_start(),
"trimright" => s.trim_end(),
_ => s.trim(),
};
molt_ok!(trimmed)
}
/// throw *type* *message*
///
/// Throws an error with the error code and message.
pub fn cmd_throw<Ctx>(_interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(1, argv, 3, 3, "type message")?;
Err(Exception::molt_err2(argv[1].clone(), argv[2].clone()))
}
/// # time *command* ?*count*?
///
/// Executes the command the given number of times, and returns the average
/// number of microseconds per iteration. The *count* defaults to 1.
pub fn cmd_time<Ctx>(interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(1, argv, 2, 3, "command ?count?")?;
let command = &argv[1];
let count = if argv.len() == 3 { argv[2].as_int()? } else { 1 };
let start = Instant::now();
for _i in 0..count {
let result = interp.eval_value(command);
if result.is_err() {
return result;
}
}
let span = start.elapsed();
let avg = if count > 0 { span.as_nanos() / (count as u128) } else { 0 } as MoltInt;
molt_ok!("{} nanoseconds per iteration", avg)
}
/// # unset ?-nocomplain? *varName*
///
/// Removes the variable from the interpreter. This is a no op if
/// there is no such variable. The -nocomplain option is accepted for
/// compatible with standard TCL, but is never required.
pub fn cmd_unset<Ctx>(interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(1, argv, 1, 0, "?-nocomplain? ?--? ?name name name...?")?;
let mut options_ok = true;
for arg in argv {
let var = arg.as_str();
if options_ok {
if var == "--" {
options_ok = false;
continue;
} else if var == "-nocomplain" {
continue;
}
}
interp.unset_var(arg);
}
molt_ok!()
}
/// # while *test* *command*
///
/// A standard "while" loop. *test* is a boolean expression; *command* is a script to
/// execute so long as the expression is true.
pub fn cmd_while<Ctx>(interp: &mut Interp<Ctx>, argv: &[Value]) -> MoltResult {
check_args(1, argv, 3, 3, "test command")?;
while interp.expr_bool(&argv[1])? {
let result = interp.eval_value(&argv[2]);
if let Err(exception) = result {
match exception.code() {
ResultCode::Break => break,
ResultCode::Continue => (),
_ => return Err(exception),
}
}
}
molt_ok!()
}