1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584
//! Module defining external-loaded modules for Rhai.
#[cfg(feature = "metadata")]
use crate::api::formatting::format_type;
use crate::ast::FnAccess;
use crate::func::{
shared_take_or_clone, CallableFunction, FnCallArgs, IteratorFn, RegisterNativeFunction,
SendSync, StraightHashMap,
};
use crate::types::{dynamic::Variant, BloomFilterU64, CustomTypeInfo, CustomTypesCollection};
use crate::{
calc_fn_hash, calc_fn_hash_full, Dynamic, Identifier, ImmutableString, NativeCallContext,
RhaiResultOf, Shared, SharedModule, SmartString,
};
use bitflags::bitflags;
#[cfg(feature = "no_std")]
use hashbrown::hash_map::Entry;
#[cfg(not(feature = "no_std"))]
use std::collections::hash_map::Entry;
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
use std::{
any::{type_name, TypeId},
collections::BTreeMap,
fmt,
ops::{Add, AddAssign},
};
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
use crate::func::register::Mut;
/// Initial capacity of the hashmap for functions.
const FN_MAP_SIZE: usize = 16;
/// A type representing the namespace of a function.
#[derive(Debug, Clone, Copy, Eq, PartialEq, Ord, PartialOrd, Hash)]
#[cfg_attr(
feature = "metadata",
derive(serde::Serialize, serde::Deserialize),
serde(rename_all = "camelCase")
)]
#[non_exhaustive]
pub enum FnNamespace {
/// Module namespace only.
///
/// Ignored under `no_module`.
Internal,
/// Expose to global namespace.
Global,
}
impl FnNamespace {
/// Is this a module namespace?
#[inline(always)]
#[must_use]
pub const fn is_module_namespace(self) -> bool {
match self {
Self::Internal => true,
Self::Global => false,
}
}
/// Is this a global namespace?
#[inline(always)]
#[must_use]
pub const fn is_global_namespace(self) -> bool {
match self {
Self::Internal => false,
Self::Global => true,
}
}
}
/// A type containing the metadata of a single registered function.
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct FuncInfoMetadata {
/// Hash value.
pub hash: u64,
/// Function namespace.
pub namespace: FnNamespace,
/// Function access mode.
pub access: FnAccess,
/// Function name.
pub name: Identifier,
#[cfg(not(feature = "no_object"))]
/// Type of `this` pointer, if any.
pub this_type: Option<ImmutableString>,
/// Number of parameters.
pub num_params: usize,
/// Parameter types (if applicable).
pub param_types: Box<[TypeId]>,
/// Parameter names and types (if available).
#[cfg(feature = "metadata")]
pub params_info: Box<[Identifier]>,
/// Return type name.
#[cfg(feature = "metadata")]
pub return_type: Identifier,
/// Comments.
#[cfg(feature = "metadata")]
pub comments: Box<[SmartString]>,
}
/// A type containing a single registered function.
#[derive(Debug, Clone)]
pub struct FuncInfo {
/// Function instance.
pub func: CallableFunction,
/// Function metadata.
pub metadata: Box<FuncInfoMetadata>,
}
impl FuncInfo {
/// _(metadata)_ Generate a signature of the function.
/// Exported under the `metadata` feature only.
#[cfg(feature = "metadata")]
#[must_use]
pub fn gen_signature(&self) -> String {
let mut signature = format!("{}(", self.metadata.name);
let return_type = format_type(&self.metadata.return_type, true);
if self.metadata.params_info.is_empty() {
for x in 0..self.metadata.num_params {
signature.push('_');
if x < self.metadata.num_params - 1 {
signature.push_str(", ");
}
}
} else {
let params = self
.metadata
.params_info
.iter()
.map(|param| {
let mut segment = param.splitn(2, ':');
let name = match segment.next().unwrap().trim() {
"" => "_",
s => s,
};
let result: std::borrow::Cow<str> = segment.next().map_or_else(
|| name.into(),
|typ| format!("{name}: {}", format_type(typ, false)).into(),
);
result
})
.collect::<crate::FnArgsVec<_>>();
signature.push_str(¶ms.join(", "));
}
signature.push(')');
if !self.func.is_script() && !return_type.is_empty() {
signature.push_str(" -> ");
signature.push_str(&return_type);
}
signature
}
}
/// _(internals)_ Calculate a [`u64`] hash key from a namespace-qualified function name and parameter types.
/// Exported under the `internals` feature only.
///
/// Module names are passed in via `&str` references from an iterator.
/// Parameter types are passed in via [`TypeId`] values from an iterator.
///
/// # Note
///
/// The first module name is skipped. Hashing starts from the _second_ module in the chain.
#[inline]
pub fn calc_native_fn_hash<'a>(
modules: impl IntoIterator<Item = &'a str, IntoIter = impl ExactSizeIterator<Item = &'a str>>,
fn_name: &str,
params: &[TypeId],
) -> u64 {
calc_fn_hash_full(
calc_fn_hash(modules, fn_name, params.len()),
params.iter().copied(),
)
}
bitflags! {
/// Bit-flags containing all status for [`Module`].
#[derive(PartialEq, Eq, PartialOrd, Ord, Hash, Debug, Clone, Copy)]
pub struct ModuleFlags: u8 {
/// Is the [`Module`] internal?
const INTERNAL = 0b0000_0001;
/// Is the [`Module`] part of a standard library?
const STANDARD_LIB = 0b0000_0010;
/// Is the [`Module`] indexed?
const INDEXED = 0b0000_0100;
/// Does the [`Module`] contain indexed functions that have been exposed to the global namespace?
const INDEXED_GLOBAL_FUNCTIONS = 0b0000_1000;
}
}
/// A module which may contain variables, sub-modules, external Rust functions,
/// and/or script-defined functions.
#[derive(Clone)]
pub struct Module {
/// ID identifying the module.
id: Option<ImmutableString>,
/// Module documentation.
#[cfg(feature = "metadata")]
doc: SmartString,
/// Custom types.
custom_types: CustomTypesCollection,
/// Sub-modules.
modules: BTreeMap<Identifier, SharedModule>,
/// [`Module`] variables.
variables: BTreeMap<Identifier, Dynamic>,
/// Flattened collection of all [`Module`] variables, including those in sub-modules.
all_variables: Option<StraightHashMap<Dynamic>>,
/// Functions (both native Rust and scripted).
functions: Option<StraightHashMap<FuncInfo>>,
/// Flattened collection of all functions, native Rust and scripted.
/// including those in sub-modules.
all_functions: Option<StraightHashMap<CallableFunction>>,
/// Bloom filter on native Rust functions (in scripted hash format) that contain [`Dynamic`] parameters.
dynamic_functions_filter: BloomFilterU64,
/// Iterator functions, keyed by the type producing the iterator.
type_iterators: BTreeMap<TypeId, Shared<IteratorFn>>,
/// Flattened collection of iterator functions, including those in sub-modules.
all_type_iterators: BTreeMap<TypeId, Shared<IteratorFn>>,
/// Flags.
pub(crate) flags: ModuleFlags,
}
impl Default for Module {
#[inline(always)]
#[must_use]
fn default() -> Self {
Self::new()
}
}
impl fmt::Debug for Module {
#[cold]
#[inline(never)]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut d = f.debug_struct("Module");
d.field("id", &self.id)
.field(
"modules",
&self
.modules
.keys()
.map(SmartString::as_str)
.collect::<Vec<_>>(),
)
.field("vars", &self.variables)
.field(
"functions",
&self
.iter_fn()
.map(|f| f.func.to_string())
.collect::<Vec<_>>(),
);
#[cfg(feature = "metadata")]
d.field("doc", &self.doc);
d.finish()
}
}
#[cfg(not(feature = "no_function"))]
impl<T: IntoIterator<Item = Shared<crate::ast::ScriptFnDef>>> From<T> for Module {
fn from(iter: T) -> Self {
let mut module = Self::new();
iter.into_iter().for_each(|fn_def| {
module.set_script_fn(fn_def);
});
module
}
}
impl<M: AsRef<Module>> Add<M> for &Module {
type Output = Module;
#[inline]
fn add(self, rhs: M) -> Self::Output {
let mut module = self.clone();
module.merge(rhs.as_ref());
module
}
}
impl<M: AsRef<Self>> Add<M> for Module {
type Output = Self;
#[inline(always)]
fn add(mut self, rhs: M) -> Self::Output {
self.merge(rhs.as_ref());
self
}
}
impl<M: Into<Self>> AddAssign<M> for Module {
#[inline(always)]
fn add_assign(&mut self, rhs: M) {
self.combine(rhs.into());
}
}
#[inline(always)]
fn new_hash_map<T>(size: usize) -> StraightHashMap<T> {
StraightHashMap::with_capacity_and_hasher(size, <_>::default())
}
impl Module {
/// Create a new [`Module`].
///
/// # Example
///
/// ```
/// # use rhai::Module;
/// let mut module = Module::new();
/// module.set_var("answer", 42_i64);
/// assert_eq!(module.get_var_value::<i64>("answer").expect("answer should exist"), 42);
/// ```
#[inline(always)]
#[must_use]
pub const fn new() -> Self {
Self {
id: None,
#[cfg(feature = "metadata")]
doc: SmartString::new_const(),
custom_types: CustomTypesCollection::new(),
modules: BTreeMap::new(),
variables: BTreeMap::new(),
all_variables: None,
functions: None,
all_functions: None,
dynamic_functions_filter: BloomFilterU64::new(),
type_iterators: BTreeMap::new(),
all_type_iterators: BTreeMap::new(),
flags: ModuleFlags::INDEXED,
}
}
/// Get the ID of the [`Module`], if any.
///
/// # Example
///
/// ```
/// # use rhai::Module;
/// let mut module = Module::new();
/// module.set_id("hello");
/// assert_eq!(module.id(), Some("hello"));
/// ```
#[inline]
#[must_use]
pub fn id(&self) -> Option<&str> {
self.id.as_ref().map(|s| s.as_str())
}
/// Get the ID of the [`Module`] as an [`Identifier`], if any.
#[inline(always)]
#[must_use]
pub(crate) const fn id_raw(&self) -> Option<&ImmutableString> {
self.id.as_ref()
}
/// Set the ID of the [`Module`].
///
/// If the string is empty, it is equivalent to clearing the ID.
///
/// # Example
///
/// ```
/// # use rhai::Module;
/// let mut module = Module::new();
/// module.set_id("hello");
/// assert_eq!(module.id(), Some("hello"));
/// ```
#[inline(always)]
pub fn set_id(&mut self, id: impl Into<ImmutableString>) -> &mut Self {
let id = id.into();
self.id = (!id.is_empty()).then_some(id);
self
}
/// Clear the ID of the [`Module`].
///
/// # Example
///
/// ```
/// # use rhai::Module;
/// let mut module = Module::new();
/// module.set_id("hello");
/// assert_eq!(module.id(), Some("hello"));
/// module.clear_id();
/// assert_eq!(module.id(), None);
/// ```
#[inline(always)]
pub fn clear_id(&mut self) -> &mut Self {
self.id = None;
self
}
/// Get the documentation of the [`Module`], if any.
/// Exported under the `metadata` feature only.
///
/// # Example
///
/// ```
/// # use rhai::Module;
/// let mut module = Module::new();
/// module.set_doc("//! This is my special module.");
/// assert_eq!(module.doc(), "//! This is my special module.");
/// ```
#[cfg(feature = "metadata")]
#[inline(always)]
#[must_use]
pub fn doc(&self) -> &str {
&self.doc
}
/// Set the documentation of the [`Module`].
/// Exported under the `metadata` feature only.
///
/// If the string is empty, it is equivalent to clearing the documentation.
///
/// # Example
///
/// ```
/// # use rhai::Module;
/// let mut module = Module::new();
/// module.set_doc("//! This is my special module.");
/// assert_eq!(module.doc(), "//! This is my special module.");
/// ```
#[cfg(feature = "metadata")]
#[inline(always)]
pub fn set_doc(&mut self, doc: impl Into<crate::SmartString>) -> &mut Self {
self.doc = doc.into();
self
}
/// Clear the documentation of the [`Module`].
///
/// # Example
///
/// ```
/// # use rhai::Module;
/// let mut module = Module::new();
/// module.set_doc("//! This is my special module.");
/// assert_eq!(module.doc(), "//! This is my special module.");
/// module.clear_doc();
/// assert_eq!(module.doc(), "");
/// ```
#[cfg(feature = "metadata")]
#[inline(always)]
pub fn clear_doc(&mut self) -> &mut Self {
self.doc.clear();
self
}
/// Clear the [`Module`].
#[inline(always)]
pub fn clear(&mut self) {
#[cfg(feature = "metadata")]
self.doc.clear();
self.custom_types.clear();
self.modules.clear();
self.variables.clear();
self.all_variables = None;
self.functions = None;
self.all_functions = None;
self.dynamic_functions_filter.clear();
self.type_iterators.clear();
self.all_type_iterators.clear();
self.flags
.remove(ModuleFlags::INDEXED | ModuleFlags::INDEXED_GLOBAL_FUNCTIONS);
}
/// Map a custom type to a friendly display name.
///
/// # Example
///
/// ```
/// # use rhai::Module;
/// #[derive(Clone)]
/// struct TestStruct;
///
/// let name = std::any::type_name::<TestStruct>();
///
/// let mut module = Module::new();
///
/// module.set_custom_type::<TestStruct>("MyType");
///
/// assert_eq!(module.get_custom_type_display_by_name(name), Some("MyType"));
/// ```
#[inline(always)]
pub fn set_custom_type<T>(&mut self, name: &str) -> &mut Self {
self.custom_types.add_type::<T>(name);
self
}
/// Map a custom type to a friendly display name.
/// Exported under the `metadata` feature only.
///
/// ## Comments
///
/// Block doc-comments should be kept in a separate string slice.
///
/// Line doc-comments should be merged, with line-breaks, into a single string slice without a final termination line-break.
///
/// Leading white-spaces should be stripped, and each string slice always starts with the corresponding
/// doc-comment leader: `///` or `/**`.
///
/// Each line in non-block doc-comments should start with `///`.
#[cfg(feature = "metadata")]
#[inline(always)]
pub fn set_custom_type_with_comments<T>(&mut self, name: &str, comments: &[&str]) -> &mut Self {
self.custom_types
.add_type_with_comments::<T>(name, comments);
self
}
/// Map a custom type to a friendly display name.
///
/// ```
/// # use rhai::Module;
/// #[derive(Clone)]
/// struct TestStruct;
///
/// let name = std::any::type_name::<TestStruct>();
///
/// let mut module = Module::new();
///
/// module.set_custom_type_raw(name, "MyType");
///
/// assert_eq!(module.get_custom_type_display_by_name(name), Some("MyType"));
/// ```
#[inline(always)]
pub fn set_custom_type_raw(
&mut self,
type_name: impl Into<Identifier>,
display_name: impl Into<Identifier>,
) -> &mut Self {
self.custom_types.add(type_name, display_name);
self
}
/// Map a custom type to a friendly display name.
/// Exported under the `metadata` feature only.
///
/// ## Comments
///
/// Block doc-comments should be kept in a separate string slice.
///
/// Line doc-comments should be merged, with line-breaks, into a single string slice without a final termination line-break.
///
/// Leading white-spaces should be stripped, and each string slice always starts with the corresponding
/// doc-comment leader: `///` or `/**`.
///
/// Each line in non-block doc-comments should start with `///`.
#[cfg(feature = "metadata")]
#[inline(always)]
pub fn set_custom_type_with_comments_raw<C: Into<SmartString>>(
&mut self,
type_name: impl Into<Identifier>,
display_name: impl Into<Identifier>,
comments: impl IntoIterator<Item = C>,
) -> &mut Self {
self.custom_types
.add_with_comments(type_name, display_name, comments);
self
}
/// Get the display name of a registered custom type.
///
/// # Example
///
/// ```
/// # use rhai::Module;
/// #[derive(Clone)]
/// struct TestStruct;
///
/// let name = std::any::type_name::<TestStruct>();
///
/// let mut module = Module::new();
///
/// module.set_custom_type::<TestStruct>("MyType");
///
/// assert_eq!(module.get_custom_type_display_by_name(name), Some("MyType"));
/// ```
#[inline]
#[must_use]
pub fn get_custom_type_display_by_name(&self, type_name: &str) -> Option<&str> {
self.get_custom_type_by_name_raw(type_name)
.map(|typ| typ.display_name.as_str())
}
/// Get the display name of a registered custom type.
///
/// # Example
///
/// ```
/// # use rhai::Module;
/// #[derive(Clone)]
/// struct TestStruct;
///
/// let name = std::any::type_name::<TestStruct>();
///
/// let mut module = Module::new();
///
/// module.set_custom_type::<TestStruct>("MyType");
///
/// assert_eq!(module.get_custom_type_display::<TestStruct>(), Some("MyType"));
/// ```
#[inline(always)]
#[must_use]
pub fn get_custom_type_display<T>(&self) -> Option<&str> {
self.get_custom_type_display_by_name(type_name::<T>())
}
/// _(internals)_ Get a registered custom type .
/// Exported under the `internals` feature only.
#[cfg(feature = "internals")]
#[inline(always)]
#[must_use]
pub fn get_custom_type_raw<T>(&self) -> Option<&CustomTypeInfo> {
self.get_custom_type_by_name_raw(type_name::<T>())
}
/// Get a registered custom type .
#[cfg(not(feature = "internals"))]
#[inline(always)]
#[must_use]
pub fn get_custom_type_raw<T>(&self) -> Option<&CustomTypeInfo> {
self.get_custom_type_by_name_raw(type_name::<T>())
}
/// _(internals)_ Get a registered custom type by its type name.
/// Exported under the `internals` feature only.
#[cfg(feature = "internals")]
#[inline(always)]
#[must_use]
pub fn get_custom_type_by_name_raw(&self, type_name: &str) -> Option<&CustomTypeInfo> {
self.custom_types.get(type_name)
}
/// Get a registered custom type by its type name.
#[cfg(not(feature = "internals"))]
#[inline(always)]
#[must_use]
fn get_custom_type_by_name_raw(&self, type_name: &str) -> Option<&CustomTypeInfo> {
self.custom_types.get(type_name)
}
/// Returns `true` if this [`Module`] contains no items.
///
/// # Example
///
/// ```
/// # use rhai::Module;
/// let module = Module::new();
/// assert!(module.is_empty());
/// ```
#[inline]
#[must_use]
pub fn is_empty(&self) -> bool {
!self.flags.contains(ModuleFlags::INDEXED_GLOBAL_FUNCTIONS)
&& self
.functions
.as_ref()
.map_or(true, StraightHashMap::is_empty)
&& self.variables.is_empty()
&& self.modules.is_empty()
&& self.type_iterators.is_empty()
&& self
.all_functions
.as_ref()
.map_or(true, StraightHashMap::is_empty)
&& self
.all_variables
.as_ref()
.map_or(true, StraightHashMap::is_empty)
&& self.all_type_iterators.is_empty()
}
/// Is the [`Module`] indexed?
///
/// A module must be indexed before it can be used in an `import` statement.
///
/// # Example
///
/// ```
/// # use rhai::Module;
/// let mut module = Module::new();
/// assert!(module.is_indexed());
///
/// module.set_native_fn("foo", |x: &mut i64, y: i64| { *x = y; Ok(()) });
/// assert!(!module.is_indexed());
///
/// # #[cfg(not(feature = "no_module"))]
/// # {
/// module.build_index();
/// assert!(module.is_indexed());
/// # }
/// ```
#[inline(always)]
#[must_use]
pub const fn is_indexed(&self) -> bool {
self.flags.contains(ModuleFlags::INDEXED)
}
/// _(metadata)_ Generate signatures for all the non-private functions in the [`Module`].
/// Exported under the `metadata` feature only.
#[cfg(feature = "metadata")]
#[inline]
pub fn gen_fn_signatures(&self) -> impl Iterator<Item = String> + '_ {
self.iter_fn()
.filter(|&f| match f.metadata.access {
FnAccess::Public => true,
FnAccess::Private => false,
})
.map(FuncInfo::gen_signature)
}
/// Does a variable exist in the [`Module`]?
///
/// # Example
///
/// ```
/// # use rhai::Module;
/// let mut module = Module::new();
/// module.set_var("answer", 42_i64);
/// assert!(module.contains_var("answer"));
/// ```
#[inline(always)]
#[must_use]
pub fn contains_var(&self, name: &str) -> bool {
self.variables.contains_key(name)
}
/// Get the value of a [`Module`] variable.
///
/// # Example
///
/// ```
/// # use rhai::Module;
/// let mut module = Module::new();
/// module.set_var("answer", 42_i64);
/// assert_eq!(module.get_var_value::<i64>("answer").expect("answer should exist"), 42);
/// ```
#[inline]
#[must_use]
pub fn get_var_value<T: Variant + Clone>(&self, name: &str) -> Option<T> {
self.get_var(name).and_then(Dynamic::try_cast::<T>)
}
/// Get a [`Module`] variable as a [`Dynamic`].
///
/// # Example
///
/// ```
/// # use rhai::Module;
/// let mut module = Module::new();
/// module.set_var("answer", 42_i64);
/// assert_eq!(module.get_var("answer").expect("answer should exist").cast::<i64>(), 42);
/// ```
#[inline(always)]
#[must_use]
pub fn get_var(&self, name: &str) -> Option<Dynamic> {
self.variables.get(name).cloned()
}
/// Set a variable into the [`Module`].
///
/// If there is an existing variable of the same name, it is replaced.
///
/// # Example
///
/// ```
/// # use rhai::Module;
/// let mut module = Module::new();
/// module.set_var("answer", 42_i64);
/// assert_eq!(module.get_var_value::<i64>("answer").expect("answer should exist"), 42);
/// ```
#[inline]
pub fn set_var(
&mut self,
name: impl Into<Identifier>,
value: impl Variant + Clone,
) -> &mut Self {
let ident = name.into();
let value = Dynamic::from(value);
if self.is_indexed() {
let hash_var = crate::calc_var_hash(Some(""), &ident);
// Catch hash collisions in testing environment only.
#[cfg(feature = "testing-environ")]
if self
.all_variables
.as_ref()
.map_or(false, |f| f.contains_key(&hash_var))
{
panic!(
"Hash {} already exists when registering variable {}",
hash_var, ident
);
}
self.all_variables
.get_or_insert_with(Default::default)
.insert(hash_var, value.clone());
}
self.variables.insert(ident, value);
self
}
/// Get a namespace-qualified [`Module`] variable as a [`Dynamic`].
#[cfg(not(feature = "no_module"))]
#[inline]
pub(crate) fn get_qualified_var(&self, hash_var: u64) -> Option<Dynamic> {
self.all_variables
.as_ref()
.and_then(|c| c.get(&hash_var).cloned())
}
/// Set a script-defined function into the [`Module`].
///
/// If there is an existing function of the same name and number of arguments, it is replaced.
#[cfg(not(feature = "no_function"))]
#[inline]
pub fn set_script_fn(&mut self, fn_def: impl Into<Shared<crate::ast::ScriptFnDef>>) -> u64 {
let fn_def = fn_def.into();
// None + function name + number of arguments.
let namespace = FnNamespace::Internal;
let num_params = fn_def.params.len();
let hash_script = crate::calc_fn_hash(None, &fn_def.name, num_params);
#[cfg(not(feature = "no_object"))]
let (hash_script, namespace) =
fn_def
.this_type
.as_ref()
.map_or((hash_script, namespace), |this_type| {
(
crate::calc_typed_method_hash(hash_script, this_type),
FnNamespace::Global,
)
});
// Catch hash collisions in testing environment only.
#[cfg(feature = "testing-environ")]
if let Some(f) = self.functions.as_ref().and_then(|f| f.get(&hash_script)) {
panic!(
"Hash {} already exists when registering function {:#?}:\n{:#?}",
hash_script, fn_def, f
);
}
#[cfg(feature = "metadata")]
let params_info = fn_def.params.iter().map(Into::into).collect();
self.functions
.get_or_insert_with(|| new_hash_map(FN_MAP_SIZE))
.insert(
hash_script,
FuncInfo {
metadata: FuncInfoMetadata {
hash: hash_script,
name: fn_def.name.as_str().into(),
namespace,
access: fn_def.access,
#[cfg(not(feature = "no_object"))]
this_type: fn_def.this_type.clone(),
num_params,
param_types: <_>::default(),
#[cfg(feature = "metadata")]
params_info,
#[cfg(feature = "metadata")]
return_type: "".into(),
#[cfg(feature = "metadata")]
comments: <_>::default(),
}
.into(),
func: fn_def.into(),
},
);
self.flags
.remove(ModuleFlags::INDEXED | ModuleFlags::INDEXED_GLOBAL_FUNCTIONS);
hash_script
}
/// Get a shared reference to the script-defined function in the [`Module`] based on name
/// and number of parameters.
#[cfg(not(feature = "no_function"))]
#[inline]
#[must_use]
pub fn get_script_fn(
&self,
name: impl AsRef<str>,
num_params: usize,
) -> Option<&Shared<crate::ast::ScriptFnDef>> {
self.functions.as_ref().and_then(|lib| {
let name = name.as_ref();
lib.values()
.find(|&f| f.metadata.num_params == num_params && f.metadata.name == name)
.and_then(|f| f.func.get_script_fn_def())
})
}
/// Get a mutable reference to the underlying [`BTreeMap`] of sub-modules,
/// creating one if empty.
///
/// # WARNING
///
/// By taking a mutable reference, it is assumed that some sub-modules will be modified.
/// Thus the [`Module`] is automatically set to be non-indexed.
#[cfg(not(feature = "no_module"))]
#[inline]
#[must_use]
pub(crate) fn get_sub_modules_mut(&mut self) -> &mut BTreeMap<Identifier, SharedModule> {
// We must assume that the user has changed the sub-modules
// (otherwise why take a mutable reference?)
self.all_functions = None;
self.all_variables = None;
self.all_type_iterators.clear();
self.flags
.remove(ModuleFlags::INDEXED | ModuleFlags::INDEXED_GLOBAL_FUNCTIONS);
&mut self.modules
}
/// Does a sub-module exist in the [`Module`]?
///
/// # Example
///
/// ```
/// # use rhai::Module;
/// let mut module = Module::new();
/// let sub_module = Module::new();
/// module.set_sub_module("question", sub_module);
/// assert!(module.contains_sub_module("question"));
/// ```
#[inline(always)]
#[must_use]
pub fn contains_sub_module(&self, name: &str) -> bool {
self.modules.contains_key(name)
}
/// Get a sub-module in the [`Module`].
///
/// # Example
///
/// ```
/// # use rhai::Module;
/// let mut module = Module::new();
/// let sub_module = Module::new();
/// module.set_sub_module("question", sub_module);
/// assert!(module.get_sub_module("question").is_some());
/// ```
#[inline]
#[must_use]
pub fn get_sub_module(&self, name: &str) -> Option<&Self> {
self.modules.get(name).map(|m| &**m)
}
/// Set a sub-module into the [`Module`].
///
/// If there is an existing sub-module of the same name, it is replaced.
///
/// # Example
///
/// ```
/// # use rhai::Module;
/// let mut module = Module::new();
/// let sub_module = Module::new();
/// module.set_sub_module("question", sub_module);
/// assert!(module.get_sub_module("question").is_some());
/// ```
#[inline]
pub fn set_sub_module(
&mut self,
name: impl Into<Identifier>,
sub_module: impl Into<SharedModule>,
) -> &mut Self {
self.modules.insert(name.into(), sub_module.into());
self.flags
.remove(ModuleFlags::INDEXED | ModuleFlags::INDEXED_GLOBAL_FUNCTIONS);
self
}
/// Does the particular Rust function exist in the [`Module`]?
///
/// The [`u64`] hash is returned by the [`set_native_fn`][Module::set_native_fn] call.
///
/// # Example
///
/// ```
/// # use rhai::Module;
/// let mut module = Module::new();
/// let hash = module.set_native_fn("calc", || Ok(42_i64));
/// assert!(module.contains_fn(hash));
/// ```
#[inline]
#[must_use]
pub fn contains_fn(&self, hash_fn: u64) -> bool {
self.functions
.as_ref()
.map_or(false, |m| m.contains_key(&hash_fn))
}
/// _(metadata)_ Update the metadata (parameter names/types and return type) of a registered function.
/// Exported under the `metadata` feature only.
///
/// The [`u64`] hash is returned by the [`set_native_fn`][Module::set_native_fn] call.
///
/// ## Parameter Names and Types
///
/// Each parameter name/type pair should be a single string of the format: `var_name: type`.
///
/// ## Return Type
///
/// The _last entry_ in the list should be the _return type_ of the function.
/// In other words, the number of entries should be one larger than the number of parameters.
#[cfg(feature = "metadata")]
#[inline]
pub fn update_fn_metadata<S: Into<Identifier>>(
&mut self,
hash_fn: u64,
arg_names: impl IntoIterator<Item = S>,
) -> &mut Self {
let mut param_names = arg_names.into_iter().map(Into::into).collect::<Vec<_>>();
if let Some(f) = self.functions.as_mut().and_then(|m| m.get_mut(&hash_fn)) {
let (param_names, return_type_name) = if param_names.len() > f.metadata.num_params {
let return_type = param_names.pop().unwrap();
(param_names, return_type)
} else {
(param_names, crate::SmartString::new_const())
};
f.metadata.params_info = param_names.into_boxed_slice();
f.metadata.return_type = return_type_name;
}
self
}
/// _(metadata)_ Update the metadata (parameter names/types, return type and doc-comments) of a registered function.
/// Exported under the `metadata` feature only.
///
/// The [`u64`] hash is returned by the [`set_native_fn`][Module::set_native_fn] call.
///
/// ## Parameter Names and Types
///
/// Each parameter name/type pair should be a single string of the format: `var_name: type`.
///
/// ## Return Type
///
/// The _last entry_ in the list should be the _return type_ of the function. In other words,
/// the number of entries should be one larger than the number of parameters.
///
/// ## Comments
///
/// Block doc-comments should be kept in a separate string slice.
///
/// Line doc-comments should be merged, with line-breaks, into a single string slice without a final termination line-break.
///
/// Leading white-spaces should be stripped, and each string slice always starts with the corresponding
/// doc-comment leader: `///` or `/**`.
///
/// Each line in non-block doc-comments should start with `///`.
#[cfg(feature = "metadata")]
#[inline]
pub fn update_fn_metadata_with_comments<A: Into<Identifier>, C: Into<SmartString>>(
&mut self,
hash_fn: u64,
arg_names: impl IntoIterator<Item = A>,
comments: impl IntoIterator<Item = C>,
) -> &mut Self {
self.update_fn_metadata(hash_fn, arg_names);
self.functions
.as_mut()
.and_then(|m| m.get_mut(&hash_fn))
.unwrap()
.metadata
.comments = comments.into_iter().map(Into::into).collect();
self
}
/// Update the namespace of a registered function.
///
/// The [`u64`] hash is returned by the [`set_native_fn`][Module::set_native_fn] call.
#[inline]
pub fn update_fn_namespace(&mut self, hash_fn: u64, namespace: FnNamespace) -> &mut Self {
if let Some(f) = self.functions.as_mut().and_then(|m| m.get_mut(&hash_fn)) {
f.metadata.namespace = namespace;
self.flags
.remove(ModuleFlags::INDEXED | ModuleFlags::INDEXED_GLOBAL_FUNCTIONS);
}
self
}
/// Remap type ID.
#[inline]
#[must_use]
fn map_type(map: bool, type_id: TypeId) -> TypeId {
if !map {
return type_id;
}
if type_id == TypeId::of::<&str>() {
// Map &str to ImmutableString
return TypeId::of::<ImmutableString>();
}
if type_id == TypeId::of::<String>() {
// Map String to ImmutableString
return TypeId::of::<ImmutableString>();
}
type_id
}
/// Set a native Rust function into the [`Module`], returning a [`u64`] hash key.
///
/// If there is an existing Rust function of the same hash, it is replaced.
///
/// # WARNING - Low Level API
///
/// This function is very low level.
///
/// ## Parameter Names and Types
///
/// Each parameter name/type pair should be a single string of the format: `var_name: type`.
///
/// ## Return Type
///
/// The _last entry_ in the list should be the _return type_ of the function.
/// In other words, the number of entries should be one larger than the number of parameters.
#[inline(always)]
pub fn set_fn(
&mut self,
name: impl Into<Identifier>,
namespace: FnNamespace,
access: FnAccess,
arg_names: Option<&[&str]>,
arg_types: impl AsRef<[TypeId]>,
func: CallableFunction,
) -> u64 {
const EMPTY: &[&str] = &[];
let arg_names = arg_names.unwrap_or(EMPTY);
self._set_fn(name, namespace, access, arg_names, arg_types, EMPTY, func)
.metadata
.hash
}
/// _(metadata)_ Set a native Rust function into the [`Module`], returning a [`u64`] hash key.
/// Exported under the `metadata` feature only.
///
/// If there is an existing Rust function of the same hash, it is replaced.
///
/// # WARNING - Low Level API
///
/// This function is very low level.
///
/// ## Parameter Names and Types
///
/// Each parameter name/type pair should be a single string of the format: `var_name: type`.
///
/// ## Return Type
///
/// The _last entry_ in the list should be the _return type_ of the function.
/// In other words, the number of entries should be one larger than the number of parameters.
///
/// ## Comments
///
/// Block doc-comments should be kept in a separate string slice.
///
/// Line doc-comments should be merged, with line-breaks, into a single string slice without a final termination line-break.
///
/// Leading white-spaces should be stripped, and each string slice always starts with the corresponding
/// doc-comment leader: `///` or `/**`.
///
/// Each line in non-block doc-comments should start with `///`.
#[cfg(feature = "metadata")]
#[inline(always)]
pub fn set_fn_with_comments<C: AsRef<str>>(
&mut self,
name: impl Into<Identifier>,
namespace: FnNamespace,
access: FnAccess,
arg_names: Option<&[&str]>,
arg_types: impl AsRef<[TypeId]>,
comments: impl IntoIterator<Item = C>,
func: CallableFunction,
) -> u64 {
let arg_names = arg_names.unwrap_or(&[]);
self._set_fn(
name, namespace, access, arg_names, arg_types, comments, func,
)
.metadata
.hash
}
/// Set a native Rust function into the [`Module`], returning a [`u64`] hash key.
///
/// If there is an existing Rust function of the same hash, it is replaced.
#[inline]
fn _set_fn<A: AsRef<str>, C: AsRef<str>>(
&mut self,
name: impl Into<Identifier>,
namespace: FnNamespace,
access: FnAccess,
arg_names: impl IntoIterator<Item = A>,
arg_types: impl AsRef<[TypeId]>,
comments: impl IntoIterator<Item = C>,
func: CallableFunction,
) -> &mut FuncInfo {
let _arg_names = arg_names;
let _comments = comments;
let is_method = func.is_method();
let param_types = arg_types
.as_ref()
.iter()
.enumerate()
.map(|(i, &type_id)| Self::map_type(!is_method || i > 0, type_id))
.collect::<Vec<_>>();
let is_dynamic = param_types
.iter()
.any(|&type_id| type_id == TypeId::of::<Dynamic>());
#[cfg(feature = "metadata")]
let (param_names, return_type_name) = {
let mut names = _arg_names
.into_iter()
.map(|a| a.as_ref().into())
.collect::<Vec<_>>();
let return_type = if names.len() > param_types.len() {
names.pop().unwrap()
} else {
crate::SmartString::new_const()
};
names.shrink_to_fit();
(names, return_type)
};
let name = name.into();
let hash_base = calc_fn_hash(None, &name, param_types.len());
let hash_fn = calc_fn_hash_full(hash_base, param_types.iter().copied());
// Catch hash collisions in testing environment only.
#[cfg(feature = "testing-environ")]
if let Some(f) = self.functions.as_ref().and_then(|f| f.get(&hash_base)) {
panic!(
"Hash {} already exists when registering function {}:\n{:#?}",
hash_base, name, f
);
}
if is_dynamic {
self.dynamic_functions_filter.mark(hash_base);
}
self.flags
.remove(ModuleFlags::INDEXED | ModuleFlags::INDEXED_GLOBAL_FUNCTIONS);
let f = FuncInfo {
func,
metadata: FuncInfoMetadata {
hash: hash_fn,
name,
namespace,
access,
#[cfg(not(feature = "no_object"))]
this_type: None,
num_params: param_types.len(),
param_types: param_types.into_boxed_slice(),
#[cfg(feature = "metadata")]
params_info: param_names.into_boxed_slice(),
#[cfg(feature = "metadata")]
return_type: return_type_name,
#[cfg(feature = "metadata")]
comments: _comments.into_iter().map(|s| s.as_ref().into()).collect(),
}
.into(),
};
match self
.functions
.get_or_insert_with(|| new_hash_map(FN_MAP_SIZE))
.entry(hash_fn)
{
Entry::Occupied(mut entry) => {
entry.insert(f);
entry.into_mut()
}
Entry::Vacant(entry) => entry.insert(f),
}
}
/// Set a native Rust function into the [`Module`], returning a [`u64`] hash key.
///
/// If there is a similar existing Rust function, it is replaced.
///
/// # WARNING - Low Level API
///
/// This function is very low level.
///
/// # Arguments
///
/// A list of [`TypeId`]'s is taken as the argument types.
///
/// Arguments are simply passed in as a mutable array of [`&mut Dynamic`][Dynamic],
/// which is guaranteed to contain enough arguments of the correct types.
///
/// The function is assumed to be a _method_, meaning that the first argument should not be consumed.
/// All other arguments can be consumed.
///
/// To access a primary argument value (i.e. cloning is cheap), use: `args[n].as_xxx().unwrap()`
///
/// To access an argument value and avoid cloning, use `args[n].take().cast::<T>()`.
/// Notice that this will _consume_ the argument, replacing it with `()`.
///
/// To access the first mutable argument, use `args.get_mut(0).unwrap()`
///
/// # Function Metadata
///
/// No metadata for the function is registered. Use [`update_fn_metadata`][Module::update_fn_metadata] to add metadata.
///
/// # Example
///
/// ```
/// use rhai::{Module, FnNamespace, FnAccess};
///
/// let mut module = Module::new();
/// let hash = module.set_raw_fn("double_or_not", FnNamespace::Internal, FnAccess::Public,
/// // Pass parameter types via a slice with TypeId's
/// &[std::any::TypeId::of::<i64>(), std::any::TypeId::of::<bool>()],
/// // Fixed closure signature
/// |context, args| {
/// // 'args' is guaranteed to be the right length and of the correct types
///
/// // Get the second parameter by 'consuming' it
/// let double = args[1].take().cast::<bool>();
/// // Since it is a primary type, it can also be cheaply copied
/// let double = args[1].clone_cast::<bool>();
/// // Get a mutable reference to the first argument.
/// let mut x = args[0].write_lock::<i64>().unwrap();
///
/// let orig = *x;
///
/// if double {
/// *x *= 2; // the first argument can be mutated
/// }
///
/// Ok(orig) // return RhaiResult<T>
/// });
///
/// assert!(module.contains_fn(hash));
/// ```
#[inline(always)]
pub fn set_raw_fn<T: Variant + Clone>(
&mut self,
name: impl Into<Identifier>,
namespace: FnNamespace,
access: FnAccess,
arg_types: impl AsRef<[TypeId]>,
func: impl Fn(NativeCallContext, &mut FnCallArgs) -> RhaiResultOf<T> + SendSync + 'static,
) -> u64 {
let f = move |ctx: Option<NativeCallContext>, args: &mut FnCallArgs| {
func(ctx.unwrap(), args).map(Dynamic::from)
};
self.set_fn(
name,
namespace,
access,
None,
arg_types,
CallableFunction::Method {
func: Shared::new(f),
has_context: true,
is_pure: false,
},
)
}
/// Set a native Rust function into the [`Module`], returning a [`u64`] hash key.
///
/// If there is a similar existing Rust function, it is replaced.
///
/// # Function Namespace
///
/// The default function namespace is [`FnNamespace::Internal`].
/// Use [`update_fn_namespace`][Module::update_fn_namespace] to change it.
///
/// # Function Metadata
///
/// No metadata for the function is registered.
/// Use [`update_fn_metadata`][Module::update_fn_metadata] to add metadata.
///
/// # Example
///
/// ```
/// # use rhai::Module;
/// let mut module = Module::new();
/// let hash = module.set_native_fn("calc", || Ok(42_i64));
/// assert!(module.contains_fn(hash));
/// ```
#[inline]
pub fn set_native_fn<A: 'static, const N: usize, const C: bool, T, F>(
&mut self,
name: impl Into<Identifier>,
func: F,
) -> u64
where
T: Variant + Clone,
F: RegisterNativeFunction<A, N, C, T, true> + SendSync + 'static,
{
let fn_name = name.into();
let is_pure = true;
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
let is_pure = is_pure && (F::num_params() != 3 || fn_name != crate::engine::FN_IDX_SET);
#[cfg(not(feature = "no_object"))]
let is_pure =
is_pure && (F::num_params() != 2 || !fn_name.starts_with(crate::engine::FN_SET));
let func = func.into_callable_function(fn_name.clone(), is_pure);
self.set_fn(
fn_name,
FnNamespace::Internal,
FnAccess::Public,
None,
F::param_types(),
func,
)
}
/// Set a Rust getter function taking one mutable parameter, returning a [`u64`] hash key.
/// This function is automatically exposed to the global namespace.
///
/// If there is a similar existing Rust getter function, it is replaced.
///
/// # Function Metadata
///
/// No metadata for the function is registered.
/// Use [`update_fn_metadata`][Module::update_fn_metadata] to add metadata.
///
/// # Example
///
/// ```
/// # use rhai::Module;
/// let mut module = Module::new();
/// let hash = module.set_getter_fn("value", |x: &mut i64| { Ok(*x) });
/// assert!(module.contains_fn(hash));
/// ```
#[cfg(not(feature = "no_object"))]
#[inline(always)]
pub fn set_getter_fn<A, const C: bool, T, F>(&mut self, name: impl AsRef<str>, func: F) -> u64
where
A: Variant + Clone,
T: Variant + Clone,
F: RegisterNativeFunction<(Mut<A>,), 1, C, T, true> + SendSync + 'static,
{
let fn_name = crate::engine::make_getter(name.as_ref());
let func = func.into_callable_function(fn_name.clone(), true);
self.set_fn(
fn_name,
FnNamespace::Global,
FnAccess::Public,
None,
F::param_types(),
func,
)
}
/// Set a Rust setter function taking two parameters (the first one mutable) into the [`Module`],
/// returning a [`u64`] hash key.
/// This function is automatically exposed to the global namespace.
///
/// If there is a similar existing setter Rust function, it is replaced.
///
/// # Function Metadata
///
/// No metadata for the function is registered.
/// Use [`update_fn_metadata`][Module::update_fn_metadata] to add metadata.
///
/// # Example
///
/// ```
/// use rhai::{Module, ImmutableString};
///
/// let mut module = Module::new();
/// let hash = module.set_setter_fn("value", |x: &mut i64, y: ImmutableString| {
/// *x = y.len() as i64;
/// Ok(())
/// });
/// assert!(module.contains_fn(hash));
/// ```
#[cfg(not(feature = "no_object"))]
#[inline(always)]
pub fn set_setter_fn<A, const C: bool, T, F>(&mut self, name: impl AsRef<str>, func: F) -> u64
where
A: Variant + Clone,
T: Variant + Clone,
F: RegisterNativeFunction<(Mut<A>, T), 2, C, (), true> + SendSync + 'static,
{
let fn_name = crate::engine::make_setter(name.as_ref());
let func = func.into_callable_function(fn_name.clone(), false);
self.set_fn(
fn_name,
FnNamespace::Global,
FnAccess::Public,
None,
F::param_types(),
func,
)
}
/// Set a pair of Rust getter and setter functions into the [`Module`], returning both [`u64`] hash keys.
/// This is a short-hand for [`set_getter_fn`][Module::set_getter_fn] and [`set_setter_fn`][Module::set_setter_fn].
///
/// These function are automatically exposed to the global namespace.
///
/// If there are similar existing Rust functions, they are replaced.
///
/// # Function Metadata
///
/// No metadata for the function is registered.
/// Use [`update_fn_metadata`][Module::update_fn_metadata] to add metadata.
///
/// # Example
///
/// ```
/// use rhai::{Module, ImmutableString};
///
/// let mut module = Module::new();
/// let (hash_get, hash_set) = module.set_getter_setter_fn("value",
/// |x: &mut i64| { Ok(x.to_string().into()) },
/// |x: &mut i64, y: ImmutableString| {
/// *x = y.len() as i64;
/// Ok(())
/// }
/// );
/// assert!(module.contains_fn(hash_get));
/// assert!(module.contains_fn(hash_set));
/// ```
#[cfg(not(feature = "no_object"))]
#[inline(always)]
pub fn set_getter_setter_fn<
A: Variant + Clone,
const C1: bool,
const C2: bool,
T: Variant + Clone,
>(
&mut self,
name: impl AsRef<str>,
getter: impl RegisterNativeFunction<(Mut<A>,), 1, C1, T, true> + SendSync + 'static,
setter: impl RegisterNativeFunction<(Mut<A>, T), 2, C2, (), true> + SendSync + 'static,
) -> (u64, u64) {
(
self.set_getter_fn(name.as_ref(), getter),
self.set_setter_fn(name.as_ref(), setter),
)
}
/// Set a Rust index getter taking two parameters (the first one mutable) into the [`Module`],
/// returning a [`u64`] hash key.
/// This function is automatically exposed to the global namespace.
///
/// If there is a similar existing setter Rust function, it is replaced.
///
/// # Panics
///
/// Panics if the type is [`Array`][crate::Array] or [`Map`][crate::Map].
/// Indexers for arrays, object maps and strings cannot be registered.
///
/// # Function Metadata
///
/// No metadata for the function is registered.
/// Use [`update_fn_metadata`][Module::update_fn_metadata] to add metadata.
///
/// # Example
///
/// ```
/// use rhai::{Module, ImmutableString};
///
/// let mut module = Module::new();
/// let hash = module.set_indexer_get_fn(|x: &mut i64, y: ImmutableString| {
/// Ok(*x + y.len() as i64)
/// });
/// assert!(module.contains_fn(hash));
/// ```
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
#[inline]
pub fn set_indexer_get_fn<A, B, const C: bool, T, F>(&mut self, func: F) -> u64
where
A: Variant + Clone,
B: Variant + Clone,
T: Variant + Clone,
F: RegisterNativeFunction<(Mut<A>, B), 2, C, T, true> + SendSync + 'static,
{
#[cfg(not(feature = "no_index"))]
assert!(
TypeId::of::<A>() != TypeId::of::<crate::Array>(),
"Cannot register indexer for arrays."
);
#[cfg(not(feature = "no_object"))]
assert!(
TypeId::of::<A>() != TypeId::of::<crate::Map>(),
"Cannot register indexer for object maps."
);
assert!(
TypeId::of::<A>() != TypeId::of::<String>()
&& TypeId::of::<A>() != TypeId::of::<&str>()
&& TypeId::of::<A>() != TypeId::of::<ImmutableString>(),
"Cannot register indexer for strings."
);
self.set_fn(
crate::engine::FN_IDX_GET,
FnNamespace::Global,
FnAccess::Public,
None,
F::param_types(),
func.into_callable_function(crate::engine::FN_IDX_GET.into(), true),
)
}
/// Set a Rust index setter taking three parameters (the first one mutable) into the [`Module`],
/// returning a [`u64`] hash key.
/// This function is automatically exposed to the global namespace.
///
/// If there is a similar existing Rust function, it is replaced.
///
/// # Panics
///
/// Panics if the type is [`Array`][crate::Array] or [`Map`][crate::Map].
/// Indexers for arrays, object maps and strings cannot be registered.
///
/// # Function Metadata
///
/// No metadata for the function is registered.
/// Use [`update_fn_metadata`][Module::update_fn_metadata] to add metadata.
///
/// # Example
///
/// ```
/// use rhai::{Module, ImmutableString};
///
/// let mut module = Module::new();
/// let hash = module.set_indexer_set_fn(|x: &mut i64, y: ImmutableString, value: i64| {
/// *x = y.len() as i64 + value; Ok(())
/// });
/// assert!(module.contains_fn(hash));
/// ```
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
#[inline]
pub fn set_indexer_set_fn<A, B, const C: bool, T, F>(&mut self, func: F) -> u64
where
A: Variant + Clone,
B: Variant + Clone,
T: Variant + Clone,
F: RegisterNativeFunction<(Mut<A>, B, T), 3, C, (), true> + SendSync + 'static,
{
#[cfg(not(feature = "no_index"))]
assert!(
TypeId::of::<A>() != TypeId::of::<crate::Array>(),
"Cannot register indexer for arrays."
);
#[cfg(not(feature = "no_object"))]
assert!(
TypeId::of::<A>() != TypeId::of::<crate::Map>(),
"Cannot register indexer for object maps."
);
assert!(
TypeId::of::<A>() != TypeId::of::<String>()
&& TypeId::of::<A>() != TypeId::of::<&str>()
&& TypeId::of::<A>() != TypeId::of::<ImmutableString>(),
"Cannot register indexer for strings."
);
self.set_fn(
crate::engine::FN_IDX_SET,
FnNamespace::Global,
FnAccess::Public,
None,
F::param_types(),
func.into_callable_function(crate::engine::FN_IDX_SET.into(), false),
)
}
/// Set a pair of Rust index getter and setter functions into the [`Module`], returning both [`u64`] hash keys.
/// This is a short-hand for [`set_indexer_get_fn`][Module::set_indexer_get_fn] and
/// [`set_indexer_set_fn`][Module::set_indexer_set_fn].
///
/// These functions are automatically exposed to the global namespace.
///
/// If there are similar existing Rust functions, they are replaced.
///
/// # Panics
///
/// Panics if the type is [`Array`][crate::Array] or [`Map`][crate::Map].
/// Indexers for arrays, object maps and strings cannot be registered.
///
/// # Function Metadata
///
/// No metadata for the function is registered.
/// Use [`update_fn_metadata`][Module::update_fn_metadata] to add metadata.
///
/// # Example
///
/// ```
/// use rhai::{Module, ImmutableString};
///
/// let mut module = Module::new();
/// let (hash_get, hash_set) = module.set_indexer_get_set_fn(
/// |x: &mut i64, y: ImmutableString| {
/// Ok(*x + y.len() as i64)
/// },
/// |x: &mut i64, y: ImmutableString, value: i64| {
/// *x = y.len() as i64 + value; Ok(())
/// }
/// );
/// assert!(module.contains_fn(hash_get));
/// assert!(module.contains_fn(hash_set));
/// ```
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
#[inline(always)]
pub fn set_indexer_get_set_fn<
A: Variant + Clone,
B: Variant + Clone,
const C1: bool,
const C2: bool,
T: Variant + Clone,
>(
&mut self,
get_fn: impl RegisterNativeFunction<(Mut<A>, B), 2, C1, T, true> + SendSync + 'static,
set_fn: impl RegisterNativeFunction<(Mut<A>, B, T), 3, C2, (), true> + SendSync + 'static,
) -> (u64, u64) {
(
self.set_indexer_get_fn(get_fn),
self.set_indexer_set_fn(set_fn),
)
}
/// Look up a native Rust function by hash.
///
/// The [`u64`] hash is returned by the [`set_native_fn`][Module::set_native_fn] call.
#[inline]
#[must_use]
pub(crate) fn get_fn(&self, hash_native: u64) -> Option<&CallableFunction> {
self.functions
.as_ref()
.and_then(|m| m.get(&hash_native))
.map(|f| &f.func)
}
/// Can the particular function with [`Dynamic`] parameter(s) exist in the [`Module`]?
///
/// A `true` return value does not automatically imply that the function _must_ exist.
#[inline(always)]
#[must_use]
pub(crate) const fn may_contain_dynamic_fn(&self, hash_script: u64) -> bool {
!self.dynamic_functions_filter.is_absent(hash_script)
}
/// Does the particular namespace-qualified function exist in the [`Module`]?
///
/// The [`u64`] hash is calculated by [`build_index`][Module::build_index].
#[inline(always)]
#[must_use]
pub fn contains_qualified_fn(&self, hash_fn: u64) -> bool {
self.all_functions
.as_ref()
.map_or(false, |m| m.contains_key(&hash_fn))
}
/// Get a namespace-qualified function.
///
/// The [`u64`] hash is calculated by [`build_index`][Module::build_index].
#[cfg(not(feature = "no_module"))]
#[inline]
#[must_use]
pub(crate) fn get_qualified_fn(&self, hash_qualified_fn: u64) -> Option<&CallableFunction> {
self.all_functions
.as_ref()
.and_then(|m| m.get(&hash_qualified_fn))
}
/// Combine another [`Module`] into this [`Module`].
/// The other [`Module`] is _consumed_ to merge into this [`Module`].
#[inline]
pub fn combine(&mut self, other: Self) -> &mut Self {
self.modules.extend(other.modules);
self.variables.extend(other.variables);
match self.functions {
Some(ref mut m) if other.functions.is_some() => {
m.extend(other.functions.unwrap().into_iter())
}
Some(_) => (),
None => self.functions = other.functions,
}
self.dynamic_functions_filter += other.dynamic_functions_filter;
self.type_iterators.extend(other.type_iterators);
self.all_functions = None;
self.all_variables = None;
self.all_type_iterators.clear();
self.flags
.remove(ModuleFlags::INDEXED | ModuleFlags::INDEXED_GLOBAL_FUNCTIONS);
#[cfg(feature = "metadata")]
{
if !self.doc.is_empty() {
self.doc.push('\n');
}
self.doc.push_str(&other.doc);
}
self
}
/// Combine another [`Module`] into this [`Module`].
/// The other [`Module`] is _consumed_ to merge into this [`Module`].
/// Sub-modules are flattened onto the root [`Module`], with higher level overriding lower level.
#[inline]
pub fn combine_flatten(&mut self, other: Self) -> &mut Self {
for m in other.modules.into_values() {
self.combine_flatten(shared_take_or_clone(m));
}
self.variables.extend(other.variables);
match self.functions {
Some(ref mut m) if other.functions.is_some() => {
m.extend(other.functions.unwrap().into_iter())
}
Some(_) => (),
None => self.functions = other.functions,
}
self.dynamic_functions_filter += other.dynamic_functions_filter;
self.type_iterators.extend(other.type_iterators);
self.all_functions = None;
self.all_variables = None;
self.all_type_iterators.clear();
self.flags
.remove(ModuleFlags::INDEXED | ModuleFlags::INDEXED_GLOBAL_FUNCTIONS);
#[cfg(feature = "metadata")]
{
if !self.doc.is_empty() {
self.doc.push('\n');
}
self.doc.push_str(&other.doc);
}
self
}
/// Polyfill this [`Module`] with another [`Module`].
/// Only items not existing in this [`Module`] are added.
#[inline]
pub fn fill_with(&mut self, other: &Self) -> &mut Self {
for (k, v) in &other.modules {
if !self.modules.contains_key(k) {
self.modules.insert(k.clone(), v.clone());
}
}
for (k, v) in &other.variables {
if !self.variables.contains_key(k) {
self.variables.insert(k.clone(), v.clone());
}
}
if let Some(ref functions) = other.functions {
let others_len = functions.len();
for (&k, f) in functions.iter() {
let map = self
.functions
.get_or_insert_with(|| new_hash_map(FN_MAP_SIZE));
map.reserve(others_len);
map.entry(k).or_insert_with(|| f.clone());
}
}
self.dynamic_functions_filter += &other.dynamic_functions_filter;
for (&k, v) in &other.type_iterators {
self.type_iterators.entry(k).or_insert_with(|| v.clone());
}
self.all_functions = None;
self.all_variables = None;
self.all_type_iterators.clear();
self.flags
.remove(ModuleFlags::INDEXED | ModuleFlags::INDEXED_GLOBAL_FUNCTIONS);
#[cfg(feature = "metadata")]
{
if !self.doc.is_empty() {
self.doc.push('\n');
}
self.doc.push_str(&other.doc);
}
self
}
/// Merge another [`Module`] into this [`Module`].
#[inline(always)]
pub fn merge(&mut self, other: &Self) -> &mut Self {
self.merge_filtered(other, |_, _, _, _, _| true)
}
/// Merge another [`Module`] into this [`Module`] based on a filter predicate.
pub(crate) fn merge_filtered(
&mut self,
other: &Self,
_filter: impl Fn(FnNamespace, FnAccess, bool, &str, usize) -> bool + Copy,
) -> &mut Self {
for (k, v) in &other.modules {
let mut m = Self::new();
m.merge_filtered(v, _filter);
self.set_sub_module(k.clone(), m);
}
#[cfg(feature = "no_function")]
self.modules.extend(other.modules.clone());
self.variables.extend(other.variables.clone());
if let Some(ref functions) = other.functions {
match self.functions {
Some(ref mut m) => m.extend(
functions
.iter()
.filter(|&(.., f)| {
_filter(
f.metadata.namespace,
f.metadata.access,
f.func.is_script(),
f.metadata.name.as_str(),
f.metadata.num_params,
)
})
.map(|(&k, f)| (k, f.clone())),
),
None => self.functions = other.functions.clone(),
}
}
self.dynamic_functions_filter += &other.dynamic_functions_filter;
self.type_iterators.extend(other.type_iterators.clone());
self.all_functions = None;
self.all_variables = None;
self.all_type_iterators.clear();
self.flags
.remove(ModuleFlags::INDEXED | ModuleFlags::INDEXED_GLOBAL_FUNCTIONS);
#[cfg(feature = "metadata")]
{
if !self.doc.is_empty() {
self.doc.push('\n');
}
self.doc.push_str(&other.doc);
}
self
}
/// Filter out the functions, retaining only some script-defined functions based on a filter predicate.
#[cfg(not(feature = "no_function"))]
#[inline]
pub(crate) fn retain_script_functions(
&mut self,
filter: impl Fn(FnNamespace, FnAccess, &str, usize) -> bool,
) -> &mut Self {
self.functions = std::mem::take(&mut self.functions).map(|m| {
m.into_iter()
.filter(|(.., f)| {
if f.func.is_script() {
filter(
f.metadata.namespace,
f.metadata.access,
f.metadata.name.as_str(),
f.metadata.num_params,
)
} else {
false
}
})
.collect()
});
self.dynamic_functions_filter.clear();
self.all_functions = None;
self.all_variables = None;
self.all_type_iterators.clear();
self.flags
.remove(ModuleFlags::INDEXED | ModuleFlags::INDEXED_GLOBAL_FUNCTIONS);
self
}
/// Get the number of variables, functions and type iterators in the [`Module`].
#[inline(always)]
#[must_use]
pub fn count(&self) -> (usize, usize, usize) {
(
self.variables.len(),
self.functions.as_ref().map_or(0, StraightHashMap::len),
self.type_iterators.len(),
)
}
/// Get an iterator to the sub-modules in the [`Module`].
#[inline(always)]
pub fn iter_sub_modules(&self) -> impl Iterator<Item = (&str, &SharedModule)> {
self.iter_sub_modules_raw().map(|(k, m)| (k.as_str(), m))
}
/// Get an iterator to the sub-modules in the [`Module`].
#[inline(always)]
pub(crate) fn iter_sub_modules_raw(
&self,
) -> impl Iterator<Item = (&Identifier, &SharedModule)> {
self.modules.iter()
}
/// Get an iterator to the variables in the [`Module`].
#[inline(always)]
pub fn iter_var(&self) -> impl Iterator<Item = (&str, &Dynamic)> {
self.iter_var_raw().map(|(k, v)| (k.as_str(), v))
}
/// Get an iterator to the variables in the [`Module`].
#[inline(always)]
pub(crate) fn iter_var_raw(&self) -> impl Iterator<Item = (&Identifier, &Dynamic)> {
self.variables.iter()
}
/// Get an iterator to the custom types in the [`Module`].
#[inline(always)]
#[allow(dead_code)]
pub(crate) fn iter_custom_types(&self) -> impl Iterator<Item = (&str, &CustomTypeInfo)> {
self.custom_types.iter()
}
/// Get an iterator to the functions in the [`Module`].
#[inline]
#[allow(dead_code)]
pub(crate) fn iter_fn(&self) -> impl Iterator<Item = &FuncInfo> {
self.functions.iter().flat_map(StraightHashMap::values)
}
/// Get an iterator over all script-defined functions in the [`Module`].
///
/// Function metadata includes:
/// 1) Namespace ([`FnNamespace::Global`] or [`FnNamespace::Internal`]).
/// 2) Access mode ([`FnAccess::Public`] or [`FnAccess::Private`]).
/// 3) Function name (as string slice).
/// 4) Number of parameters.
/// 5) Shared reference to function definition [`ScriptFnDef`][crate::ast::ScriptFnDef].
#[cfg(not(feature = "no_function"))]
#[inline]
pub(crate) fn iter_script_fn(
&self,
) -> impl Iterator<
Item = (
FnNamespace,
FnAccess,
&str,
usize,
&Shared<crate::ast::ScriptFnDef>,
),
> + '_ {
self.iter_fn().filter(|&f| f.func.is_script()).map(|f| {
(
f.metadata.namespace,
f.metadata.access,
f.metadata.name.as_str(),
f.metadata.num_params,
f.func.get_script_fn_def().expect("script-defined function"),
)
})
}
/// Get an iterator over all script-defined functions in the [`Module`].
///
/// Function metadata includes:
/// 1) Namespace ([`FnNamespace::Global`] or [`FnNamespace::Internal`]).
/// 2) Access mode ([`FnAccess::Public`] or [`FnAccess::Private`]).
/// 3) Function name (as string slice).
/// 4) Number of parameters.
#[cfg(not(feature = "no_function"))]
#[cfg(not(feature = "internals"))]
#[inline]
pub fn iter_script_fn_info(
&self,
) -> impl Iterator<Item = (FnNamespace, FnAccess, &str, usize)> {
self.iter_fn().filter(|&f| f.func.is_script()).map(|f| {
(
f.metadata.namespace,
f.metadata.access,
f.metadata.name.as_str(),
f.metadata.num_params,
)
})
}
/// _(internals)_ Get an iterator over all script-defined functions in the [`Module`].
/// Exported under the `internals` feature only.
///
/// Function metadata includes:
/// 1) Namespace ([`FnNamespace::Global`] or [`FnNamespace::Internal`]).
/// 2) Access mode ([`FnAccess::Public`] or [`FnAccess::Private`]).
/// 3) Function name (as string slice).
/// 4) Number of parameters.
/// 5) _(internals)_ Shared reference to function definition [`ScriptFnDef`][crate::ast::ScriptFnDef].
#[cfg(not(feature = "no_function"))]
#[cfg(feature = "internals")]
#[inline(always)]
pub fn iter_script_fn_info(
&self,
) -> impl Iterator<
Item = (
FnNamespace,
FnAccess,
&str,
usize,
&Shared<crate::ast::ScriptFnDef>,
),
> {
self.iter_script_fn()
}
/// Create a new [`Module`] by evaluating an [`AST`][crate::AST].
///
/// The entire [`AST`][crate::AST] is encapsulated into each function, allowing functions to
/// cross-call each other.
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// use rhai::{Engine, Module, Scope};
///
/// let engine = Engine::new();
/// let ast = engine.compile("let answer = 42; export answer;")?;
/// let module = Module::eval_ast_as_new(Scope::new(), &ast, &engine)?;
/// assert!(module.contains_var("answer"));
/// assert_eq!(module.get_var_value::<i64>("answer").expect("answer should exist"), 42);
/// # Ok(())
/// # }
/// ```
#[cfg(not(feature = "no_module"))]
#[inline(always)]
pub fn eval_ast_as_new(
scope: crate::Scope,
ast: &crate::AST,
engine: &crate::Engine,
) -> RhaiResultOf<Self> {
let mut scope = scope;
let global = &mut crate::eval::GlobalRuntimeState::new(engine);
Self::eval_ast_as_new_raw(engine, &mut scope, global, ast)
}
/// Create a new [`Module`] by evaluating an [`AST`][crate::AST].
///
/// The entire [`AST`][crate::AST] is encapsulated into each function, allowing functions to
/// cross-call each other.
///
/// # WARNING - Low Level API
///
/// This function is very low level.
///
/// In particular, the [`global`][crate::GlobalRuntimeState] parameter allows the entire
/// calling environment to be encapsulated, including automatic global constants.
#[cfg(not(feature = "no_module"))]
pub fn eval_ast_as_new_raw(
engine: &crate::Engine,
scope: &mut crate::Scope,
global: &mut crate::eval::GlobalRuntimeState,
ast: &crate::AST,
) -> RhaiResultOf<Self> {
// Save global state
let orig_scope_len = scope.len();
let orig_imports_len = global.num_imports();
let orig_source = global.source.clone();
#[cfg(not(feature = "no_function"))]
let orig_lib_len = global.lib.len();
#[cfg(not(feature = "no_function"))]
let orig_constants = std::mem::take(&mut global.constants);
// Run the script
let caches = &mut crate::eval::Caches::new();
let result = engine.eval_ast_with_scope_raw(global, caches, scope, ast);
// Create new module
let mut module = Self::new();
// Extra modules left become sub-modules
let mut imports = Vec::new();
if result.is_ok() {
global
.scan_imports_raw()
.skip(orig_imports_len)
.for_each(|(k, m)| {
imports.push((k.clone(), m.clone()));
module.set_sub_module(k.clone(), m.clone());
});
}
// Restore global state
#[cfg(not(feature = "no_function"))]
let constants = std::mem::replace(&mut global.constants, orig_constants);
global.truncate_imports(orig_imports_len);
#[cfg(not(feature = "no_function"))]
global.lib.truncate(orig_lib_len);
global.source = orig_source;
// The return value is thrown away and not used
let _ = result?;
// Encapsulated environment
let environ = Shared::new(crate::func::EncapsulatedEnviron {
#[cfg(not(feature = "no_function"))]
lib: ast.shared_lib().clone(),
imports,
#[cfg(not(feature = "no_function"))]
constants,
});
// Variables with an alias left in the scope become module variables
let mut i = scope.len();
while i > 0 {
i -= 1;
let (mut value, mut aliases) = if i >= orig_scope_len {
let (_, v, a) = scope.pop_entry().expect("not empty");
(v, a)
} else {
let (_, v, a) = scope.get_entry_by_index(i);
(v.clone(), a.to_vec())
};
value.deep_scan(|v| {
if let Some(fn_ptr) = v.downcast_mut::<crate::FnPtr>() {
fn_ptr.set_encapsulated_environ(Some(environ.clone()));
}
});
match aliases.len() {
0 => (),
1 => {
let alias = aliases.pop().unwrap();
if !module.contains_var(&alias) {
module.set_var(alias, value);
}
}
_ => {
// Avoid cloning the last value
let mut first_alias = None;
for alias in aliases {
if module.contains_var(&alias) {
continue;
}
if first_alias.is_none() {
first_alias = Some(alias);
} else {
module.set_var(alias, value.clone());
}
}
if let Some(alias) = first_alias {
module.set_var(alias, value);
}
}
}
}
// Non-private functions defined become module functions
#[cfg(not(feature = "no_function"))]
ast.iter_fn_def()
.filter(|&f| match f.access {
FnAccess::Public => true,
FnAccess::Private => false,
})
.for_each(|f| {
let hash = module.set_script_fn(f.clone());
let f = module.functions.as_mut().unwrap().get_mut(&hash).unwrap();
// Encapsulate AST environment
if let CallableFunction::Script {
environ: ref mut e, ..
} = f.func
{
*e = Some(environ.clone());
}
});
module.id = ast.source_raw().cloned();
#[cfg(feature = "metadata")]
module.set_doc(ast.doc());
module.build_index();
Ok(module)
}
/// Does the [`Module`] contain indexed functions that have been exposed to the global namespace?
///
/// # Panics
///
/// Panics if the [`Module`] is not yet indexed via [`build_index`][Module::build_index].
#[inline(always)]
#[must_use]
pub const fn contains_indexed_global_functions(&self) -> bool {
self.flags.contains(ModuleFlags::INDEXED_GLOBAL_FUNCTIONS)
}
/// Scan through all the sub-modules in the [`Module`] and build a hash index of all
/// variables and functions as one flattened namespace.
///
/// If the [`Module`] is already indexed, this method has no effect.
pub fn build_index(&mut self) -> &mut Self {
// Collect a particular module.
fn index_module<'a>(
module: &'a Module,
path: &mut Vec<&'a str>,
variables: &mut StraightHashMap<Dynamic>,
functions: &mut StraightHashMap<CallableFunction>,
type_iterators: &mut BTreeMap<TypeId, Shared<IteratorFn>>,
) -> bool {
let mut contains_indexed_global_functions = false;
for (name, m) in &module.modules {
// Index all the sub-modules first.
path.push(name);
if index_module(m, path, variables, functions, type_iterators) {
contains_indexed_global_functions = true;
}
path.pop();
}
// Index all variables
for (var_name, value) in &module.variables {
let hash_var = crate::calc_var_hash(path.iter().copied(), var_name);
// Catch hash collisions in testing environment only.
#[cfg(feature = "testing-environ")]
assert!(
!variables.contains_key(&hash_var),
"Hash {} already exists when indexing variable {}",
hash_var,
var_name
);
variables.insert(hash_var, value.clone());
}
// Index all type iterators
for (&type_id, func) in &module.type_iterators {
type_iterators.insert(type_id, func.clone());
}
// Index all functions
for (&hash, f) in module.functions.iter().flatten() {
match f.metadata.namespace {
FnNamespace::Global => {
// Catch hash collisions in testing environment only.
#[cfg(feature = "testing-environ")]
if let Some(fx) = functions.get(&hash) {
panic!(
"Hash {} already exists when indexing function {:#?}:\n{:#?}",
hash, f.func, fx
);
}
// Flatten all functions with global namespace
functions.insert(hash, f.func.clone());
contains_indexed_global_functions = true;
}
FnNamespace::Internal => (),
}
match f.metadata.access {
FnAccess::Public => (),
FnAccess::Private => continue, // Do not index private functions
}
if f.func.is_script() {
#[cfg(not(feature = "no_function"))]
{
let hash_script = crate::calc_fn_hash(
path.iter().copied(),
&f.metadata.name,
f.metadata.num_params,
);
#[cfg(not(feature = "no_object"))]
let hash_script = f
.metadata
.this_type
.as_ref()
.map_or(hash_script, |this_type| {
crate::calc_typed_method_hash(hash_script, this_type)
});
// Catch hash collisions in testing environment only.
#[cfg(feature = "testing-environ")]
if let Some(fx) = functions.get(&hash_script) {
panic!(
"Hash {} already exists when indexing function {:#?}:\n{:#?}",
hash_script, f.func, fx
);
}
functions.insert(hash_script, f.func.clone());
}
} else {
let hash_fn = calc_native_fn_hash(
path.iter().copied(),
f.metadata.name.as_str(),
&f.metadata.param_types,
);
// Catch hash collisions in testing environment only.
#[cfg(feature = "testing-environ")]
if let Some(fx) = functions.get(&hash_fn) {
panic!(
"Hash {} already exists when indexing function {:#?}:\n{:#?}",
hash_fn, f.func, fx
);
}
functions.insert(hash_fn, f.func.clone());
}
}
contains_indexed_global_functions
}
if !self.is_indexed() {
let mut path = Vec::with_capacity(4);
let mut variables = new_hash_map(self.variables.len());
let mut functions =
new_hash_map(self.functions.as_ref().map_or(0, StraightHashMap::len));
let mut type_iterators = BTreeMap::new();
path.push("");
let has_global_functions = index_module(
self,
&mut path,
&mut variables,
&mut functions,
&mut type_iterators,
);
self.flags
.set(ModuleFlags::INDEXED_GLOBAL_FUNCTIONS, has_global_functions);
self.all_variables = (!variables.is_empty()).then_some(variables);
self.all_functions = (!functions.is_empty()).then_some(functions);
self.all_type_iterators = type_iterators;
self.flags |= ModuleFlags::INDEXED;
}
self
}
/// Does a type iterator exist in the entire module tree?
#[inline(always)]
#[must_use]
pub fn contains_qualified_iter(&self, id: TypeId) -> bool {
self.all_type_iterators.contains_key(&id)
}
/// Does a type iterator exist in the module?
#[inline(always)]
#[must_use]
pub fn contains_iter(&self, id: TypeId) -> bool {
self.type_iterators.contains_key(&id)
}
/// Set a type iterator into the [`Module`].
#[inline(always)]
pub fn set_iter(
&mut self,
type_id: TypeId,
func: impl Fn(Dynamic) -> Box<dyn Iterator<Item = Dynamic>> + SendSync + 'static,
) -> &mut Self {
self.set_iter_result(type_id, move |x| {
Box::new(func(x).map(Ok)) as Box<dyn Iterator<Item = RhaiResultOf<Dynamic>>>
})
}
/// Set a fallible type iterator into the [`Module`].
#[inline]
pub fn set_iter_result(
&mut self,
type_id: TypeId,
func: impl Fn(Dynamic) -> Box<dyn Iterator<Item = RhaiResultOf<Dynamic>>> + SendSync + 'static,
) -> &mut Self {
let func = Shared::new(func);
if self.is_indexed() {
self.all_type_iterators.insert(type_id, func.clone());
}
self.type_iterators.insert(type_id, func);
self
}
/// Set a type iterator into the [`Module`].
#[inline(always)]
pub fn set_iterable<T>(&mut self) -> &mut Self
where
T: Variant + Clone + IntoIterator,
<T as IntoIterator>::Item: Variant + Clone,
{
self.set_iter(TypeId::of::<T>(), |obj: Dynamic| {
Box::new(obj.cast::<T>().into_iter().map(Dynamic::from))
})
}
/// Set a fallible type iterator into the [`Module`].
#[inline(always)]
pub fn set_iterable_result<T, X>(&mut self) -> &mut Self
where
T: Variant + Clone + IntoIterator<Item = RhaiResultOf<X>>,
X: Variant + Clone,
{
self.set_iter_result(TypeId::of::<T>(), |obj: Dynamic| {
Box::new(obj.cast::<T>().into_iter().map(|v| v.map(Dynamic::from)))
})
}
/// Set an iterator type into the [`Module`] as a type iterator.
#[inline(always)]
pub fn set_iterator<T>(&mut self) -> &mut Self
where
T: Variant + Clone + Iterator,
<T as Iterator>::Item: Variant + Clone,
{
self.set_iter(TypeId::of::<T>(), |obj: Dynamic| {
Box::new(obj.cast::<T>().map(Dynamic::from))
})
}
/// Set a iterator type into the [`Module`] as a fallible type iterator.
#[inline(always)]
pub fn set_iterator_result<T, X>(&mut self) -> &mut Self
where
T: Variant + Clone + Iterator<Item = RhaiResultOf<X>>,
X: Variant + Clone,
{
self.set_iter_result(TypeId::of::<T>(), |obj: Dynamic| {
Box::new(obj.cast::<T>().map(|v| v.map(Dynamic::from)))
})
}
/// Get the specified type iterator.
#[cfg(not(feature = "no_module"))]
#[inline]
#[must_use]
pub(crate) fn get_qualified_iter(&self, id: TypeId) -> Option<&IteratorFn> {
self.all_type_iterators.get(&id).map(|f| &**f)
}
/// Get the specified type iterator.
#[inline]
#[must_use]
pub(crate) fn get_iter(&self, id: TypeId) -> Option<&IteratorFn> {
self.type_iterators.get(&id).map(|f| &**f)
}
}
/// Module containing all built-in [module resolvers][ModuleResolver].
#[cfg(not(feature = "no_module"))]
pub mod resolvers;
#[cfg(not(feature = "no_module"))]
pub use resolvers::ModuleResolver;