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
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
//! Main module defining the script evaluation [`Engine`].

use crate::ast::{Expr, FnCallExpr, Ident, OpAssignment, ReturnType, Stmt};
use crate::dynamic::{map_std_type_name, AccessMode, Union, Variant};
use crate::fn_native::{
    CallableFunction, IteratorFn, OnDebugCallback, OnPrintCallback, OnVarCallback,
};
use crate::module::NamespaceRef;
use crate::optimize::OptimizationLevel;
use crate::packages::{Package, StandardPackage};
use crate::r#unsafe::unsafe_cast_var_name_to_lifetime;
use crate::syntax::CustomSyntax;
use crate::token::Token;
use crate::utils::get_hasher;
use crate::{
    Dynamic, EvalAltResult, Identifier, ImmutableString, Module, Position, RhaiResult, Scope,
    Shared, StaticVec,
};
#[cfg(feature = "no_std")]
use std::prelude::v1::*;
use std::{
    any::{type_name, TypeId},
    borrow::Cow,
    collections::{BTreeMap, BTreeSet},
    fmt,
    hash::{Hash, Hasher},
    num::{NonZeroU8, NonZeroUsize},
    ops::{Deref, DerefMut},
};

#[cfg(not(feature = "no_index"))]
use crate::Array;

#[cfg(not(feature = "no_object"))]
use crate::Map;

#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
use crate::ast::FnCallHashes;

pub type Precedence = NonZeroU8;

/// _(INTERNALS)_ A stack of imported [modules][Module].
/// Exported under the `internals` feature only.
///
/// # Volatile Data Structure
///
/// This type is volatile and may change.
//
// # Implementation Notes
//
// We cannot use Cow<str> here because `eval` may load a [module][Module] and
// the module name will live beyond the AST of the eval script text.
// The best we can do is a shared reference.
//
// This implementation splits the module names from the shared modules to improve data locality.
// Most usage will be looking up a particular key from the list and then getting the module that
// corresponds to that key.
#[derive(Clone, Default)]
pub struct Imports {
    keys: StaticVec<Identifier>,
    modules: StaticVec<Shared<Module>>,
}

impl Imports {
    /// Get the length of this stack of imported [modules][Module].
    #[inline(always)]
    pub fn len(&self) -> usize {
        self.keys.len()
    }
    /// Is this stack of imported [modules][Module] empty?
    #[inline(always)]
    pub fn is_empty(&self) -> bool {
        self.keys.is_empty()
    }
    /// Get the imported [modules][Module] at a particular index.
    #[inline(always)]
    pub fn get(&self, index: usize) -> Option<Shared<Module>> {
        self.modules.get(index).cloned()
    }
    /// Get the imported [modules][Module] at a particular index.
    #[allow(dead_code)]
    #[inline(always)]
    pub(crate) fn get_mut(&mut self, index: usize) -> Option<&mut Shared<Module>> {
        self.modules.get_mut(index)
    }
    /// Get the index of an imported [modules][Module] by name.
    #[inline(always)]
    pub fn find(&self, name: &str) -> Option<usize> {
        self.keys
            .iter()
            .enumerate()
            .rev()
            .find_map(|(i, key)| if *key == name { Some(i) } else { None })
    }
    /// Push an imported [modules][Module] onto the stack.
    #[inline(always)]
    pub fn push(&mut self, name: impl Into<Identifier>, module: impl Into<Shared<Module>>) {
        self.keys.push(name.into());
        self.modules.push(module.into());
    }
    /// Truncate the stack of imported [modules][Module] to a particular length.
    #[inline(always)]
    pub fn truncate(&mut self, size: usize) {
        self.keys.truncate(size);
        self.modules.truncate(size);
    }
    /// Get an iterator to this stack of imported [modules][Module] in reverse order.
    #[allow(dead_code)]
    #[inline(always)]
    pub fn iter(&self) -> impl Iterator<Item = (&str, &Module)> {
        self.keys
            .iter()
            .zip(self.modules.iter())
            .rev()
            .map(|(name, module)| (name.as_str(), module.as_ref()))
    }
    /// Get an iterator to this stack of imported [modules][Module] in reverse order.
    #[allow(dead_code)]
    #[inline(always)]
    pub(crate) fn iter_raw(&self) -> impl Iterator<Item = (&Identifier, &Shared<Module>)> {
        self.keys.iter().rev().zip(self.modules.iter().rev())
    }
    /// Get an iterator to this stack of imported [modules][Module] in forward order.
    #[allow(dead_code)]
    #[inline(always)]
    pub(crate) fn scan_raw(&self) -> impl Iterator<Item = (&Identifier, &Shared<Module>)> {
        self.keys.iter().zip(self.modules.iter())
    }
    /// Get a consuming iterator to this stack of imported [modules][Module] in reverse order.
    #[inline(always)]
    pub fn into_iter(self) -> impl Iterator<Item = (Identifier, Shared<Module>)> {
        self.keys
            .into_iter()
            .rev()
            .zip(self.modules.into_iter().rev())
    }
    /// Does the specified function hash key exist in this stack of imported [modules][Module]?
    #[allow(dead_code)]
    #[inline(always)]
    pub fn contains_fn(&self, hash: u64) -> bool {
        self.modules.iter().any(|m| m.contains_qualified_fn(hash))
    }
    /// Get specified function via its hash key.
    #[inline(always)]
    pub fn get_fn(&self, hash: u64) -> Option<(&CallableFunction, Option<&Identifier>)> {
        self.modules
            .iter()
            .rev()
            .find_map(|m| m.get_qualified_fn(hash).map(|f| (f, m.id_raw())))
    }
    /// Does the specified [`TypeId`][std::any::TypeId] iterator exist in this stack of
    /// imported [modules][Module]?
    #[allow(dead_code)]
    #[inline(always)]
    pub fn contains_iter(&self, id: TypeId) -> bool {
        self.modules.iter().any(|m| m.contains_qualified_iter(id))
    }
    /// Get the specified [`TypeId`][std::any::TypeId] iterator.
    #[inline(always)]
    pub fn get_iter(&self, id: TypeId) -> Option<IteratorFn> {
        self.modules
            .iter()
            .rev()
            .find_map(|m| m.get_qualified_iter(id))
    }
}

impl fmt::Debug for Imports {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("Imports")?;

        if self.is_empty() {
            f.debug_map().finish()
        } else {
            f.debug_map()
                .entries(self.keys.iter().zip(self.modules.iter()))
                .finish()
        }
    }
}

#[cfg(not(feature = "unchecked"))]
#[cfg(debug_assertions)]
#[cfg(not(feature = "no_function"))]
pub const MAX_CALL_STACK_DEPTH: usize = 8;
#[cfg(not(feature = "unchecked"))]
#[cfg(debug_assertions)]
pub const MAX_EXPR_DEPTH: usize = 32;
#[cfg(not(feature = "unchecked"))]
#[cfg(not(feature = "no_function"))]
#[cfg(debug_assertions)]
pub const MAX_FUNCTION_EXPR_DEPTH: usize = 16;

#[cfg(not(feature = "unchecked"))]
#[cfg(not(debug_assertions))]
#[cfg(not(feature = "no_function"))]
pub const MAX_CALL_STACK_DEPTH: usize = 64;
#[cfg(not(feature = "unchecked"))]
#[cfg(not(debug_assertions))]
pub const MAX_EXPR_DEPTH: usize = 64;
#[cfg(not(feature = "unchecked"))]
#[cfg(not(feature = "no_function"))]
#[cfg(not(debug_assertions))]
pub const MAX_FUNCTION_EXPR_DEPTH: usize = 32;

pub const MAX_DYNAMIC_PARAMETERS: usize = 16;

pub const KEYWORD_PRINT: &str = "print";
pub const KEYWORD_DEBUG: &str = "debug";
pub const KEYWORD_TYPE_OF: &str = "type_of";
pub const KEYWORD_EVAL: &str = "eval";
pub const KEYWORD_FN_PTR: &str = "Fn";
pub const KEYWORD_FN_PTR_CALL: &str = "call";
pub const KEYWORD_FN_PTR_CURRY: &str = "curry";
#[cfg(not(feature = "no_closure"))]
pub const KEYWORD_IS_SHARED: &str = "is_shared";
pub const KEYWORD_IS_DEF_VAR: &str = "is_def_var";
#[cfg(not(feature = "no_function"))]
pub const KEYWORD_IS_DEF_FN: &str = "is_def_fn";
pub const KEYWORD_THIS: &str = "this";
#[cfg(not(feature = "no_function"))]
pub const KEYWORD_GLOBAL: &str = "global";
#[cfg(not(feature = "no_object"))]
pub const FN_GET: &str = "get$";
#[cfg(not(feature = "no_object"))]
pub const FN_SET: &str = "set$";
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
pub const FN_IDX_GET: &str = "index$get$";
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
pub const FN_IDX_SET: &str = "index$set$";
#[cfg(not(feature = "no_function"))]
pub const FN_ANONYMOUS: &str = "anon$";

/// Standard equality comparison operator.
pub const OP_EQUALS: &str = "==";

/// Standard method function for containment testing.
///
/// The `in` operator is implemented as a call to this method.
pub const OP_CONTAINS: &str = "contains";

/// Standard concatenation operator token.
pub const TOKEN_OP_CONCAT: Token = Token::PlusAssign;

/// Method of chaining.
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
#[derive(Debug, Clone, Copy, Eq, PartialEq, Hash)]
enum ChainType {
    /// Indexing.
    #[cfg(not(feature = "no_index"))]
    Index,
    /// Dotting.
    #[cfg(not(feature = "no_object"))]
    Dot,
}

/// Value of a chaining argument.
#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
#[derive(Debug, Clone, Hash)]
enum ChainArgument {
    /// Dot-property access.
    #[cfg(not(feature = "no_object"))]
    Property(Position),
    /// Arguments to a dot method call.
    #[cfg(not(feature = "no_object"))]
    MethodCallArgs(StaticVec<Dynamic>, StaticVec<Position>),
    /// Index value.
    #[cfg(not(feature = "no_index"))]
    IndexValue(Dynamic, Position),
}

#[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
impl ChainArgument {
    /// Return the `Dynamic` value.
    ///
    /// # Panics
    ///
    /// Panics if not `ChainArgument::IndexValue`.
    #[inline(always)]
    #[cfg(not(feature = "no_index"))]
    pub fn as_index_value(self) -> Dynamic {
        match self {
            #[cfg(not(feature = "no_object"))]
            Self::Property(_) | Self::MethodCallArgs(_, _) => {
                panic!("expecting ChainArgument::IndexValue")
            }
            Self::IndexValue(value, _) => value,
        }
    }
    /// Return the `StaticVec<Dynamic>` value.
    ///
    /// # Panics
    ///
    /// Panics if not `ChainArgument::MethodCallArgs`.
    #[inline(always)]
    #[cfg(not(feature = "no_object"))]
    pub fn as_fn_call_args(self) -> (StaticVec<Dynamic>, StaticVec<Position>) {
        match self {
            Self::Property(_) => {
                panic!("expecting ChainArgument::MethodCallArgs")
            }
            #[cfg(not(feature = "no_index"))]
            Self::IndexValue(_, _) => {
                panic!("expecting ChainArgument::MethodCallArgs")
            }
            Self::MethodCallArgs(values, positions) => (values, positions),
        }
    }
}

#[cfg(not(feature = "no_object"))]
impl From<(StaticVec<Dynamic>, StaticVec<Position>)> for ChainArgument {
    #[inline(always)]
    fn from((values, positions): (StaticVec<Dynamic>, StaticVec<Position>)) -> Self {
        Self::MethodCallArgs(values, positions)
    }
}

#[cfg(not(feature = "no_index"))]
impl From<(Dynamic, Position)> for ChainArgument {
    #[inline(always)]
    fn from((value, pos): (Dynamic, Position)) -> Self {
        Self::IndexValue(value, pos)
    }
}

/// A type that encapsulates a mutation target for an expression with side effects.
#[derive(Debug)]
pub enum Target<'a> {
    /// The target is a mutable reference to a `Dynamic` value somewhere.
    Ref(&'a mut Dynamic),
    /// The target is a mutable reference to a Shared `Dynamic` value.
    /// It holds both the access guard and the original shared value.
    #[cfg(not(feature = "no_closure"))]
    #[cfg(not(feature = "no_object"))]
    LockGuard((crate::dynamic::DynamicWriteLock<'a, Dynamic>, Dynamic)),
    /// The target is a temporary `Dynamic` value (i.e. the mutation can cause no side effects).
    Value(Dynamic),
    /// The target is a character inside a String.
    /// This is necessary because directly pointing to a char inside a String is impossible.
    #[cfg(not(feature = "no_index"))]
    StringChar(&'a mut Dynamic, usize, Dynamic),
}

impl<'a> Target<'a> {
    /// Is the `Target` a reference pointing to other data?
    #[allow(dead_code)]
    #[inline(always)]
    pub fn is_ref(&self) -> bool {
        match self {
            Self::Ref(_) => true,
            #[cfg(not(feature = "no_closure"))]
            #[cfg(not(feature = "no_object"))]
            Self::LockGuard(_) => true,
            Self::Value(_) => false,
            #[cfg(not(feature = "no_index"))]
            Self::StringChar(_, _, _) => false,
        }
    }
    /// Is the `Target` an owned value?
    #[allow(dead_code)]
    #[inline(always)]
    pub fn is_value(&self) -> bool {
        match self {
            Self::Ref(_) => false,
            #[cfg(not(feature = "no_closure"))]
            #[cfg(not(feature = "no_object"))]
            Self::LockGuard(_) => false,
            Self::Value(_) => true,
            #[cfg(not(feature = "no_index"))]
            Self::StringChar(_, _, _) => false,
        }
    }
    /// Is the `Target` a shared value?
    #[cfg(not(feature = "no_closure"))]
    #[inline(always)]
    pub fn is_shared(&self) -> bool {
        match self {
            Self::Ref(r) => r.is_shared(),
            #[cfg(not(feature = "no_closure"))]
            #[cfg(not(feature = "no_object"))]
            Self::LockGuard(_) => true,
            Self::Value(r) => r.is_shared(),
            #[cfg(not(feature = "no_index"))]
            Self::StringChar(_, _, _) => false,
        }
    }
    /// Is the `Target` a specific type?
    #[allow(dead_code)]
    #[inline(always)]
    pub fn is<T: Variant + Clone>(&self) -> bool {
        match self {
            Self::Ref(r) => r.is::<T>(),
            #[cfg(not(feature = "no_closure"))]
            #[cfg(not(feature = "no_object"))]
            Self::LockGuard((r, _)) => r.is::<T>(),
            Self::Value(r) => r.is::<T>(),
            #[cfg(not(feature = "no_index"))]
            Self::StringChar(_, _, _) => TypeId::of::<T>() == TypeId::of::<char>(),
        }
    }
    /// Get the value of the `Target` as a `Dynamic`, cloning a referenced value if necessary.
    #[inline(always)]
    pub fn take_or_clone(self) -> Dynamic {
        match self {
            Self::Ref(r) => r.clone(), // Referenced value is cloned
            #[cfg(not(feature = "no_closure"))]
            #[cfg(not(feature = "no_object"))]
            Self::LockGuard((_, orig)) => orig, // Original value is simply taken
            Self::Value(v) => v,       // Owned value is simply taken
            #[cfg(not(feature = "no_index"))]
            Self::StringChar(_, _, ch) => ch, // Character is taken
        }
    }
    /// Take a `&mut Dynamic` reference from the `Target`.
    #[inline(always)]
    pub fn take_ref(self) -> Option<&'a mut Dynamic> {
        match self {
            Self::Ref(r) => Some(r),
            _ => None,
        }
    }
    /// Convert a shared or reference `Target` into a target with an owned value.
    #[inline(always)]
    pub fn into_owned(self) -> Target<'static> {
        self.take_or_clone().into()
    }
    /// Propagate a changed value back to the original source.
    /// This has no effect except for string indexing.
    #[cfg(not(feature = "no_object"))]
    #[inline(always)]
    pub fn propagate_changed_value(&mut self) -> Result<(), Box<EvalAltResult>> {
        match self {
            Self::Ref(_) | Self::Value(_) => Ok(()),
            #[cfg(not(feature = "no_closure"))]
            Self::LockGuard(_) => Ok(()),
            #[cfg(not(feature = "no_index"))]
            Self::StringChar(_, _, ch) => {
                let char_value = ch.clone();
                self.set_value(char_value, Position::NONE)
            }
        }
    }
    /// Update the value of the `Target`.
    pub fn set_value(
        &mut self,
        new_val: Dynamic,
        _pos: Position,
    ) -> Result<(), Box<EvalAltResult>> {
        match self {
            Self::Ref(r) => **r = new_val,
            #[cfg(not(feature = "no_closure"))]
            #[cfg(not(feature = "no_object"))]
            Self::LockGuard((r, _)) => **r = new_val,
            Self::Value(_) => panic!("cannot update a value"),
            #[cfg(not(feature = "no_index"))]
            Self::StringChar(s, index, _) => {
                let s = &mut *s
                    .write_lock::<ImmutableString>()
                    .expect("never fails because `StringChar` always holds an `ImmutableString`");

                // Replace the character at the specified index position
                let new_ch = new_val.as_char().map_err(|err| {
                    Box::new(EvalAltResult::ErrorMismatchDataType(
                        "char".to_string(),
                        err.to_string(),
                        _pos,
                    ))
                })?;

                let index = *index;

                *s = s
                    .chars()
                    .enumerate()
                    .map(|(i, ch)| if i == index { new_ch } else { ch })
                    .collect();
            }
        }

        Ok(())
    }
}

impl<'a> From<&'a mut Dynamic> for Target<'a> {
    #[inline(always)]
    fn from(value: &'a mut Dynamic) -> Self {
        #[cfg(not(feature = "no_closure"))]
        #[cfg(not(feature = "no_object"))]
        if value.is_shared() {
            // Cloning is cheap for a shared value
            let container = value.clone();
            return Self::LockGuard((
                value
                    .write_lock::<Dynamic>()
                    .expect("never fails when casting to `Dynamic`"),
                container,
            ));
        }

        Self::Ref(value)
    }
}

impl Deref for Target<'_> {
    type Target = Dynamic;

    #[inline(always)]
    fn deref(&self) -> &Dynamic {
        match self {
            Self::Ref(r) => *r,
            #[cfg(not(feature = "no_closure"))]
            #[cfg(not(feature = "no_object"))]
            Self::LockGuard((r, _)) => &**r,
            Self::Value(ref r) => r,
            #[cfg(not(feature = "no_index"))]
            Self::StringChar(_, _, ref r) => r,
        }
    }
}

impl AsRef<Dynamic> for Target<'_> {
    #[inline(always)]
    fn as_ref(&self) -> &Dynamic {
        self
    }
}

impl DerefMut for Target<'_> {
    #[inline(always)]
    fn deref_mut(&mut self) -> &mut Dynamic {
        match self {
            Self::Ref(r) => *r,
            #[cfg(not(feature = "no_closure"))]
            #[cfg(not(feature = "no_object"))]
            Self::LockGuard((r, _)) => r.deref_mut(),
            Self::Value(ref mut r) => r,
            #[cfg(not(feature = "no_index"))]
            Self::StringChar(_, _, ref mut r) => r,
        }
    }
}

impl AsMut<Dynamic> for Target<'_> {
    #[inline(always)]
    fn as_mut(&mut self) -> &mut Dynamic {
        self
    }
}

impl<T: Into<Dynamic>> From<T> for Target<'_> {
    #[inline(always)]
    fn from(value: T) -> Self {
        Self::Value(value.into())
    }
}

/// An entry in a function resolution cache.
#[derive(Debug, Clone)]
pub struct FnResolutionCacheEntry {
    /// Function.
    pub func: CallableFunction,
    /// Optional source.
    pub source: Option<Identifier>,
}

/// A function resolution cache.
pub type FnResolutionCache = BTreeMap<u64, Option<Box<FnResolutionCacheEntry>>>;

/// _(INTERNALS)_ A type that holds all the current states of the [`Engine`].
/// Exported under the `internals` feature only.
///
/// # Volatile Data Structure
///
/// This type is volatile and may change.
#[derive(Debug, Clone, Default)]
pub struct State {
    /// Source of the current context.
    pub source: Option<Identifier>,
    /// Normally, access to variables are parsed with a relative offset into the scope to avoid a lookup.
    /// In some situation, e.g. after running an `eval` statement, subsequent offsets become mis-aligned.
    /// When that happens, this flag is turned on to force a scope lookup by name.
    pub always_search: bool,
    /// Level of the current scope.  The global (root) level is zero, a new block
    /// (or function call) is one level higher, and so on.
    pub scope_level: usize,
    /// Number of operations performed.
    pub operations: u64,
    /// Number of modules loaded.
    pub modules: usize,
    /// Embedded module resolver.
    #[cfg(not(feature = "no_module"))]
    pub resolver: Option<Shared<crate::module::resolvers::StaticModuleResolver>>,
    /// Function resolution cache and free list.
    fn_resolution_caches: (StaticVec<FnResolutionCache>, Vec<FnResolutionCache>),
}

impl State {
    /// Is the state currently at global (root) level?
    #[inline(always)]
    pub fn is_global(&self) -> bool {
        self.scope_level == 0
    }
    /// Get a mutable reference to the current function resolution cache.
    #[inline(always)]
    pub fn fn_resolution_cache_mut(&mut self) -> &mut FnResolutionCache {
        if self.fn_resolution_caches.0.is_empty() {
            // Push a new function resolution cache if the stack is empty
            self.fn_resolution_caches.0.push(BTreeMap::new());
        }
        self.fn_resolution_caches.0.last_mut().expect(
            "never fails because there is at least one function resolution cache by this point",
        )
    }
    /// Push an empty function resolution cache onto the stack and make it current.
    #[allow(dead_code)]
    #[inline(always)]
    pub fn push_fn_resolution_cache(&mut self) {
        self.fn_resolution_caches
            .0
            .push(self.fn_resolution_caches.1.pop().unwrap_or_default());
    }
    /// Remove the current function resolution cache from the stack and make the last one current.
    ///
    /// # Panics
    ///
    /// Panics if there are no more function resolution cache in the stack.
    #[inline(always)]
    pub fn pop_fn_resolution_cache(&mut self) {
        let mut cache = self
            .fn_resolution_caches
            .0
            .pop()
            .expect("there should be at least one function resolution cache");
        cache.clear();
        self.fn_resolution_caches.1.push(cache);
    }
}

/// _(INTERNALS)_ A type containing all the limits imposed by the [`Engine`].
/// Exported under the `internals` feature only.
///
/// # Volatile Data Structure
///
/// This type is volatile and may change.
#[cfg(not(feature = "unchecked"))]
#[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct Limits {
    /// Maximum levels of call-stack to prevent infinite recursion.
    ///
    /// Set to zero to effectively disable function calls.
    ///
    /// Not available under `no_function`.
    #[cfg(not(feature = "no_function"))]
    pub max_call_stack_depth: usize,
    /// Maximum depth of statements/expressions at global level.
    pub max_expr_depth: Option<NonZeroUsize>,
    /// Maximum depth of statements/expressions in functions.
    ///
    /// Not available under `no_function`.
    #[cfg(not(feature = "no_function"))]
    pub max_function_expr_depth: Option<NonZeroUsize>,
    /// Maximum number of operations allowed to run.
    pub max_operations: Option<std::num::NonZeroU64>,
    /// Maximum number of [modules][Module] allowed to load.
    ///
    /// Set to zero to effectively disable loading any [module][Module].
    ///
    /// Not available under `no_module`.
    #[cfg(not(feature = "no_module"))]
    pub max_modules: usize,
    /// Maximum length of a [string][ImmutableString].
    pub max_string_size: Option<NonZeroUsize>,
    /// Maximum length of an [array][Array].
    ///
    /// Not available under `no_index`.
    #[cfg(not(feature = "no_index"))]
    pub max_array_size: Option<NonZeroUsize>,
    /// Maximum number of properties in an [object map][Map].
    ///
    /// Not available under `no_object`.
    #[cfg(not(feature = "no_object"))]
    pub max_map_size: Option<NonZeroUsize>,
}

/// Context of a script evaluation process.
#[derive(Debug)]
pub struct EvalContext<'a, 'x, 'px, 'm, 's, 't, 'pt> {
    pub(crate) engine: &'a Engine,
    pub(crate) scope: &'x mut Scope<'px>,
    pub(crate) mods: &'m mut Imports,
    pub(crate) state: &'s mut State,
    pub(crate) lib: &'a [&'a Module],
    pub(crate) this_ptr: &'t mut Option<&'pt mut Dynamic>,
    pub(crate) level: usize,
}

impl<'x, 'px> EvalContext<'_, 'x, 'px, '_, '_, '_, '_> {
    /// The current [`Engine`].
    #[inline(always)]
    pub fn engine(&self) -> &Engine {
        self.engine
    }
    /// The current source.
    #[inline(always)]
    pub fn source(&self) -> Option<&str> {
        self.state.source.as_ref().map(|s| s.as_str())
    }
    /// The current [`Scope`].
    #[inline(always)]
    pub fn scope(&self) -> &Scope {
        self.scope
    }
    /// Mutable reference to the current [`Scope`].
    #[inline(always)]
    pub fn scope_mut(&mut self) -> &mut &'x mut Scope<'px> {
        &mut self.scope
    }
    /// Get an iterator over the current set of modules imported via `import` statements.
    #[cfg(not(feature = "no_module"))]
    #[inline(always)]
    pub fn iter_imports(&self) -> impl Iterator<Item = (&str, &Module)> {
        self.mods.iter()
    }
    /// _(INTERNALS)_ The current set of modules imported via `import` statements.
    /// Exported under the `internals` feature only.
    #[cfg(feature = "internals")]
    #[cfg(not(feature = "no_module"))]
    #[inline(always)]
    pub fn imports(&self) -> &Imports {
        self.mods
    }
    /// Get an iterator over the namespaces containing definition of all script-defined functions.
    #[inline(always)]
    pub fn iter_namespaces(&self) -> impl Iterator<Item = &Module> {
        self.lib.iter().cloned()
    }
    /// _(INTERNALS)_ The current set of namespaces containing definitions of all script-defined functions.
    /// Exported under the `internals` feature only.
    #[cfg(feature = "internals")]
    #[inline(always)]
    pub fn namespaces(&self) -> &[&Module] {
        self.lib
    }
    /// The current bound `this` pointer, if any.
    #[inline(always)]
    pub fn this_ptr(&self) -> Option<&Dynamic> {
        self.this_ptr.as_ref().map(|v| &**v)
    }
    /// The current nesting level of function calls.
    #[inline(always)]
    pub fn call_level(&self) -> usize {
        self.level
    }
}

/// Rhai main scripting engine.
///
/// # Thread Safety
///
/// [`Engine`] is re-entrant.
///
/// Currently, [`Engine`] is neither [`Send`] nor [`Sync`].
/// Use the `sync` feature to make it [`Send`] `+` [`Sync`].
///
/// # Example
///
/// ```
/// # fn main() -> Result<(), Box<rhai::EvalAltResult>> {
/// use rhai::Engine;
///
/// let engine = Engine::new();
///
/// let result = engine.eval::<i64>("40 + 2")?;
///
/// println!("Answer: {}", result);  // prints 42
/// # Ok(())
/// # }
/// ```
pub struct Engine {
    /// A module containing all functions directly loaded into the Engine.
    pub(crate) global_namespace: Module,
    /// A collection of all modules loaded into the global namespace of the Engine.
    pub(crate) global_modules: StaticVec<Shared<Module>>,
    /// A collection of all sub-modules directly loaded into the Engine.
    pub(crate) global_sub_modules: BTreeMap<Identifier, Shared<Module>>,

    /// A module resolution service.
    #[cfg(not(feature = "no_module"))]
    pub(crate) module_resolver: Box<dyn crate::ModuleResolver>,

    /// A map mapping type names to pretty-print names.
    pub(crate) type_names: BTreeMap<Identifier, Box<Identifier>>,

    /// An empty [`ImmutableString`] for cloning purposes.
    pub(crate) empty_string: ImmutableString,

    /// A set of symbols to disable.
    pub(crate) disabled_symbols: BTreeSet<Identifier>,
    /// A map containing custom keywords and precedence to recognize.
    pub(crate) custom_keywords: BTreeMap<Identifier, Option<Precedence>>,
    /// Custom syntax.
    pub(crate) custom_syntax: BTreeMap<Identifier, Box<CustomSyntax>>,
    /// Callback closure for resolving variable access.
    pub(crate) resolve_var: Option<OnVarCallback>,

    /// Callback closure for implementing the `print` command.
    pub(crate) print: OnPrintCallback,
    /// Callback closure for implementing the `debug` command.
    pub(crate) debug: OnDebugCallback,
    /// Callback closure for progress reporting.
    #[cfg(not(feature = "unchecked"))]
    pub(crate) progress: Option<crate::fn_native::OnProgressCallback>,

    /// Optimize the AST after compilation.
    pub(crate) optimization_level: OptimizationLevel,

    /// Max limits.
    #[cfg(not(feature = "unchecked"))]
    pub(crate) limits: Limits,
}

impl fmt::Debug for Engine {
    #[inline(always)]
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("Engine")
    }
}

impl Default for Engine {
    #[inline(always)]
    fn default() -> Self {
        Self::new()
    }
}

/// Make getter function
#[cfg(not(feature = "no_object"))]
#[inline(always)]
pub fn make_getter(id: &str) -> String {
    format!("{}{}", FN_GET, id)
}

/// Make setter function
#[cfg(not(feature = "no_object"))]
#[inline(always)]
pub fn make_setter(id: &str) -> String {
    format!("{}{}", FN_SET, id)
}

/// Is this function an anonymous function?
#[cfg(not(feature = "no_function"))]
#[inline(always)]
pub fn is_anonymous_fn(fn_name: &str) -> bool {
    fn_name.starts_with(FN_ANONYMOUS)
}

/// Print to stdout
#[inline(always)]
fn default_print(_s: &str) {
    #[cfg(not(feature = "no_std"))]
    #[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
    println!("{}", _s);
}

/// Debug to stdout
#[inline(always)]
fn default_debug(_s: &str, _source: Option<&str>, _pos: Position) {
    #[cfg(not(feature = "no_std"))]
    #[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
    if let Some(source) = _source {
        println!("{}{:?} | {}", source, _pos, _s);
    } else if _pos.is_none() {
        println!("{}", _s);
    } else {
        println!("{:?} | {}", _pos, _s);
    }
}

impl Engine {
    /// Create a new [`Engine`]
    #[inline]
    pub fn new() -> Self {
        // Create the new scripting Engine
        let mut engine = Self {
            global_namespace: Default::default(),
            global_modules: Default::default(),
            global_sub_modules: Default::default(),

            #[cfg(not(feature = "no_module"))]
            #[cfg(not(feature = "no_std"))]
            #[cfg(not(any(target_arch = "wasm32", target_arch = "wasm64")))]
            module_resolver: Box::new(crate::module::resolvers::FileModuleResolver::new()),
            #[cfg(not(feature = "no_module"))]
            #[cfg(any(feature = "no_std", target_arch = "wasm32",))]
            module_resolver: Box::new(crate::module::resolvers::DummyModuleResolver::new()),

            type_names: Default::default(),
            empty_string: Default::default(),
            disabled_symbols: Default::default(),
            custom_keywords: Default::default(),
            custom_syntax: Default::default(),

            // variable resolver
            resolve_var: None,

            // default print/debug implementations
            print: Box::new(default_print),
            debug: Box::new(default_debug),

            // progress callback
            #[cfg(not(feature = "unchecked"))]
            progress: None,

            // optimization level
            optimization_level: Default::default(),

            #[cfg(not(feature = "unchecked"))]
            limits: Limits {
                #[cfg(not(feature = "no_function"))]
                max_call_stack_depth: MAX_CALL_STACK_DEPTH,
                max_expr_depth: NonZeroUsize::new(MAX_EXPR_DEPTH),
                #[cfg(not(feature = "no_function"))]
                max_function_expr_depth: NonZeroUsize::new(MAX_FUNCTION_EXPR_DEPTH),
                max_operations: None,
                #[cfg(not(feature = "no_module"))]
                max_modules: usize::MAX,
                max_string_size: None,
                #[cfg(not(feature = "no_index"))]
                max_array_size: None,
                #[cfg(not(feature = "no_object"))]
                max_map_size: None,
            },
        };

        engine.global_namespace.internal = true;
        engine.register_global_module(StandardPackage::new().as_shared_module());

        engine
    }

    /// Create a new [`Engine`] with minimal built-in functions.
    ///
    /// Use [`register_global_module`][Engine::register_global_module] to add packages of functions.
    #[inline(always)]
    pub fn new_raw() -> Self {
        let mut engine = Self {
            global_namespace: Default::default(),
            global_modules: Default::default(),
            global_sub_modules: Default::default(),

            #[cfg(not(feature = "no_module"))]
            module_resolver: Box::new(crate::module::resolvers::DummyModuleResolver::new()),

            type_names: Default::default(),
            empty_string: Default::default(),
            disabled_symbols: Default::default(),
            custom_keywords: Default::default(),
            custom_syntax: Default::default(),

            resolve_var: None,

            print: Box::new(|_| {}),
            debug: Box::new(|_, _, _| {}),

            #[cfg(not(feature = "unchecked"))]
            progress: None,

            optimization_level: Default::default(),

            #[cfg(not(feature = "unchecked"))]
            limits: Limits {
                #[cfg(not(feature = "no_function"))]
                max_call_stack_depth: MAX_CALL_STACK_DEPTH,
                max_expr_depth: NonZeroUsize::new(MAX_EXPR_DEPTH),
                #[cfg(not(feature = "no_function"))]
                max_function_expr_depth: NonZeroUsize::new(MAX_FUNCTION_EXPR_DEPTH),
                max_operations: None,
                #[cfg(not(feature = "no_module"))]
                max_modules: usize::MAX,
                max_string_size: None,
                #[cfg(not(feature = "no_index"))]
                max_array_size: None,
                #[cfg(not(feature = "no_object"))]
                max_map_size: None,
            },
        };

        engine.global_namespace.internal = true;

        engine
    }

    /// Search for a module within an imports stack.
    #[inline]
    pub(crate) fn search_imports(
        &self,
        mods: &Imports,
        state: &mut State,
        namespace: &NamespaceRef,
    ) -> Option<Shared<Module>> {
        let root = &namespace[0].name;

        // Qualified - check if the root module is directly indexed
        let index = if state.always_search {
            None
        } else {
            namespace.index()
        };

        if let Some(index) = index {
            let offset = mods.len() - index.get();
            Some(
                mods.get(offset)
                    .expect("never fails because offset should be within range"),
            )
        } else {
            mods.find(root)
                .map(|n| {
                    mods.get(n)
                        .expect("never fails because the index came from `find`")
                })
                .or_else(|| self.global_sub_modules.get(root).cloned())
        }
    }

    /// Search for a variable within the scope or within imports,
    /// depending on whether the variable name is namespace-qualified.
    pub(crate) fn search_namespace<'s>(
        &self,
        scope: &'s mut Scope,
        mods: &mut Imports,
        state: &mut State,
        lib: &[&Module],
        this_ptr: &'s mut Option<&mut Dynamic>,
        expr: &Expr,
    ) -> Result<(Target<'s>, Position), Box<EvalAltResult>> {
        match expr {
            Expr::Variable(Some(_), _, _) => {
                self.search_scope_only(scope, mods, state, lib, this_ptr, expr)
            }
            Expr::Variable(None, var_pos, v) => match v.as_ref() {
                // Normal variable access
                (_, None, _) => self.search_scope_only(scope, mods, state, lib, this_ptr, expr),
                // Qualified variable
                (_, Some((hash_var, modules)), var_name) => {
                    let module = self.search_imports(mods, state, modules).ok_or_else(|| {
                        EvalAltResult::ErrorModuleNotFound(
                            modules[0].name.to_string(),
                            modules[0].pos,
                        )
                    })?;
                    let target = module.get_qualified_var(*hash_var).map_err(|mut err| {
                        match *err {
                            EvalAltResult::ErrorVariableNotFound(ref mut err_name, _) => {
                                *err_name = format!("{}{}", modules, var_name);
                            }
                            _ => (),
                        }
                        err.fill_position(*var_pos)
                    })?;

                    // Module variables are constant
                    let mut target = target.clone();
                    target.set_access_mode(AccessMode::ReadOnly);
                    Ok((target.into(), *var_pos))
                }
            },
            _ => unreachable!("Expr::Variable expected, but gets {:?}", expr),
        }
    }

    /// Search for a variable within the scope
    ///
    /// # Panics
    ///
    /// Panics if `expr` is not [`Expr::Variable`].
    pub(crate) fn search_scope_only<'s>(
        &self,
        scope: &'s mut Scope,
        mods: &mut Imports,
        state: &mut State,
        lib: &[&Module],
        this_ptr: &'s mut Option<&mut Dynamic>,
        expr: &Expr,
    ) -> Result<(Target<'s>, Position), Box<EvalAltResult>> {
        // Make sure that the pointer indirection is taken only when absolutely necessary.

        let (index, var_pos) = match expr {
            // Check if the variable is `this`
            Expr::Variable(None, pos, v) if v.0.is_none() && v.2 == KEYWORD_THIS => {
                return if let Some(val) = this_ptr {
                    Ok(((*val).into(), *pos))
                } else {
                    EvalAltResult::ErrorUnboundThis(*pos).into()
                }
            }
            _ if state.always_search => (0, expr.position()),
            Expr::Variable(Some(i), pos, _) => (i.get() as usize, *pos),
            Expr::Variable(None, pos, v) => (v.0.map(NonZeroUsize::get).unwrap_or(0), *pos),
            _ => unreachable!("Expr::Variable expected, but gets {:?}", expr),
        };

        // Check the variable resolver, if any
        if let Some(ref resolve_var) = self.resolve_var {
            let context = EvalContext {
                engine: self,
                scope,
                mods,
                state,
                lib,
                this_ptr,
                level: 0,
            };
            if let Some(mut result) = resolve_var(
                expr.get_variable_name(true)
                    .expect("`expr` should be `Variable`"),
                index,
                &context,
            )
            .map_err(|err| err.fill_position(var_pos))?
            {
                result.set_access_mode(AccessMode::ReadOnly);
                return Ok((result.into(), var_pos));
            }
        }

        let index = if index > 0 {
            scope.len() - index
        } else {
            // Find the variable in the scope
            let var_name = expr
                .get_variable_name(true)
                .expect("`expr` should be `Variable`");
            scope
                .get_index(var_name)
                .ok_or_else(|| EvalAltResult::ErrorVariableNotFound(var_name.to_string(), var_pos))?
                .0
        };

        let val = scope.get_mut_by_index(index);

        Ok((val.into(), var_pos))
    }

    /// Chain-evaluate a dot/index chain.
    /// [`Position`] in [`EvalAltResult`] is [`NONE`][Position::NONE] and must be set afterwards.
    #[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
    fn eval_dot_index_chain_helper(
        &self,
        mods: &mut Imports,
        state: &mut State,
        lib: &[&Module],
        this_ptr: &mut Option<&mut Dynamic>,
        target: &mut Target,
        root: (&str, Position),
        rhs: &Expr,
        idx_values: &mut StaticVec<ChainArgument>,
        chain_type: ChainType,
        level: usize,
        new_val: Option<((Dynamic, Position), (Option<OpAssignment>, Position))>,
    ) -> Result<(Dynamic, bool), Box<EvalAltResult>> {
        fn match_chain_type(expr: &Expr) -> ChainType {
            match expr {
                #[cfg(not(feature = "no_index"))]
                Expr::Index(_, _) => ChainType::Index,
                #[cfg(not(feature = "no_object"))]
                Expr::Dot(_, _) => ChainType::Dot,
                _ => unreachable!("`expr` should only be `Index` or `Dot`, but got {:?}", expr),
            }
        }

        let is_ref = target.is_ref();

        // Pop the last index value
        let idx_val = idx_values
            .pop()
            .expect("never fails because an index chain is never empty");

        match chain_type {
            #[cfg(not(feature = "no_index"))]
            ChainType::Index => {
                let pos = rhs.position();

                match rhs {
                    // xxx[idx].expr... | xxx[idx][expr]...
                    Expr::Dot(x, x_pos) | Expr::Index(x, x_pos) => {
                        let idx_pos = x.lhs.position();
                        let idx_val = idx_val.as_index_value();
                        let obj_ptr = &mut self.get_indexed_mut(
                            mods, state, lib, target, idx_val, idx_pos, false, true, level,
                        )?;
                        let rhs_chain = match_chain_type(rhs);

                        self.eval_dot_index_chain_helper(
                            mods, state, lib, this_ptr, obj_ptr, root, &x.rhs, idx_values,
                            rhs_chain, level, new_val,
                        )
                        .map_err(|err| err.fill_position(*x_pos))
                    }
                    // xxx[rhs] op= new_val
                    _ if new_val.is_some() => {
                        let ((mut new_val, new_pos), (op_info, op_pos)) =
                            new_val.expect("never fails because `new_val` is `Some`");
                        let idx_val = idx_val.as_index_value();

                        #[cfg(not(feature = "no_index"))]
                        let mut idx_val_for_setter = idx_val.clone();

                        match self.get_indexed_mut(
                            mods, state, lib, target, idx_val, pos, true, false, level,
                        ) {
                            // Indexed value is a reference - update directly
                            Ok(obj_ptr) => {
                                self.eval_op_assignment(
                                    mods, state, lib, op_info, op_pos, obj_ptr, root, new_val,
                                    new_pos,
                                )?;
                                return Ok((Dynamic::UNIT, true));
                            }
                            // Can't index - try to call an index setter
                            #[cfg(not(feature = "no_index"))]
                            Err(err) if matches!(*err, EvalAltResult::ErrorIndexingType(_, _)) => {}
                            // Any other error
                            Err(err) => return Err(err),
                        }

                        // Try to call index setter
                        let hash_set =
                            FnCallHashes::from_native(crate::calc_fn_hash(FN_IDX_SET, 3));
                        let args = &mut [target, &mut idx_val_for_setter, &mut new_val];

                        self.exec_fn_call(
                            mods, state, lib, FN_IDX_SET, hash_set, args, is_ref, true, new_pos,
                            None, level,
                        )?;

                        Ok((Dynamic::UNIT, true))
                    }
                    // xxx[rhs]
                    _ => {
                        let idx_val = idx_val.as_index_value();
                        self.get_indexed_mut(
                            mods, state, lib, target, idx_val, pos, false, true, level,
                        )
                        .map(|v| (v.take_or_clone(), false))
                    }
                }
            }

            #[cfg(not(feature = "no_object"))]
            ChainType::Dot => {
                match rhs {
                    // xxx.fn_name(arg_expr_list)
                    Expr::FnCall(x, pos) if !x.is_qualified() && new_val.is_none() => {
                        let FnCallExpr { name, hashes, .. } = x.as_ref();
                        let mut args = idx_val.as_fn_call_args();
                        self.make_method_call(
                            mods, state, lib, name, *hashes, target, &mut args, *pos, level,
                        )
                    }
                    // xxx.fn_name(...) = ???
                    Expr::FnCall(_, _) if new_val.is_some() => {
                        unreachable!("method call cannot be assigned to")
                    }
                    // xxx.module::fn_name(...) - syntax error
                    Expr::FnCall(_, _) => {
                        unreachable!("function call in dot chain should not be namespace-qualified")
                    }
                    // {xxx:map}.id op= ???
                    Expr::Property(x) if target.is::<Map>() && new_val.is_some() => {
                        let (name, pos) = &x.2;
                        let index = name.into();
                        let val = self.get_indexed_mut(
                            mods, state, lib, target, index, *pos, true, false, level,
                        )?;
                        let ((new_val, new_pos), (op_info, op_pos)) =
                            new_val.expect("never fails because `new_val` is `Some`");
                        self.eval_op_assignment(
                            mods, state, lib, op_info, op_pos, val, root, new_val, new_pos,
                        )?;
                        Ok((Dynamic::UNIT, true))
                    }
                    // {xxx:map}.id
                    Expr::Property(x) if target.is::<Map>() => {
                        let (name, pos) = &x.2;
                        let index = name.into();
                        let val = self.get_indexed_mut(
                            mods, state, lib, target, index, *pos, false, false, level,
                        )?;

                        Ok((val.take_or_clone(), false))
                    }
                    // xxx.id op= ???
                    Expr::Property(x) if new_val.is_some() => {
                        let ((getter, hash_get), (setter, hash_set), (name, pos)) = x.as_ref();
                        let ((mut new_val, new_pos), (op_info, op_pos)) =
                            new_val.expect("never fails because `new_val` is `Some`");

                        if op_info.is_some() {
                            let hash = FnCallHashes::from_native(*hash_get);
                            let mut args = [target.as_mut()];
                            let (mut orig_val, _) = self
                                .exec_fn_call(
                                    mods, state, lib, getter, hash, &mut args, is_ref, true, *pos,
                                    None, level,
                                )
                                .or_else(|err| match *err {
                                    // Try an indexer if property does not exist
                                    EvalAltResult::ErrorDotExpr(_, _) => {
                                        let prop = name.into();
                                        self.get_indexed_mut(
                                            mods, state, lib, target, prop, *pos, false, true,
                                            level,
                                        )
                                        .map(|v| (v.take_or_clone(), false))
                                        .map_err(
                                            |idx_err| match *idx_err {
                                                EvalAltResult::ErrorIndexingType(_, _) => err,
                                                _ => idx_err,
                                            },
                                        )
                                    }
                                    _ => Err(err),
                                })?;
                            let obj_ptr = (&mut orig_val).into();
                            self.eval_op_assignment(
                                mods, state, lib, op_info, op_pos, obj_ptr, root, new_val, new_pos,
                            )?;
                            new_val = orig_val;
                        }

                        let hash = FnCallHashes::from_native(*hash_set);
                        let mut args = [target.as_mut(), &mut new_val];
                        self.exec_fn_call(
                            mods, state, lib, setter, hash, &mut args, is_ref, true, *pos, None,
                            level,
                        )
                        .or_else(|err| match *err {
                            // Try an indexer if property does not exist
                            EvalAltResult::ErrorDotExpr(_, _) => {
                                let mut prop = name.into();
                                let args = &mut [target, &mut prop, &mut new_val];
                                let hash_set =
                                    FnCallHashes::from_native(crate::calc_fn_hash(FN_IDX_SET, 3));
                                self.exec_fn_call(
                                    mods, state, lib, FN_IDX_SET, hash_set, args, is_ref, true,
                                    *pos, None, level,
                                )
                                .map_err(
                                    |idx_err| match *idx_err {
                                        EvalAltResult::ErrorIndexingType(_, _) => err,
                                        _ => idx_err,
                                    },
                                )
                            }
                            _ => Err(err),
                        })
                    }
                    // xxx.id
                    Expr::Property(x) => {
                        let ((getter, hash_get), _, (name, pos)) = x.as_ref();
                        let hash = FnCallHashes::from_native(*hash_get);
                        let mut args = [target.as_mut()];
                        self.exec_fn_call(
                            mods, state, lib, getter, hash, &mut args, is_ref, true, *pos, None,
                            level,
                        )
                        .map_or_else(
                            |err| match *err {
                                // Try an indexer if property does not exist
                                EvalAltResult::ErrorDotExpr(_, _) => {
                                    let prop = name.into();
                                    self.get_indexed_mut(
                                        mods, state, lib, target, prop, *pos, false, true, level,
                                    )
                                    .map(|v| (v.take_or_clone(), false))
                                    .map_err(|idx_err| {
                                        match *idx_err {
                                            EvalAltResult::ErrorIndexingType(_, _) => err,
                                            _ => idx_err,
                                        }
                                    })
                                }
                                _ => Err(err),
                            },
                            |(v, _)| Ok((v, false)),
                        )
                    }
                    // {xxx:map}.sub_lhs[expr] | {xxx:map}.sub_lhs.expr
                    Expr::Index(x, x_pos) | Expr::Dot(x, x_pos) if target.is::<Map>() => {
                        let mut val = match &x.lhs {
                            Expr::Property(p) => {
                                let (name, pos) = &p.2;
                                let index = name.into();
                                self.get_indexed_mut(
                                    mods, state, lib, target, index, *pos, false, true, level,
                                )?
                            }
                            // {xxx:map}.fn_name(arg_expr_list)[expr] | {xxx:map}.fn_name(arg_expr_list).expr
                            Expr::FnCall(x, pos) if !x.is_qualified() => {
                                let FnCallExpr { name, hashes, .. } = x.as_ref();
                                let mut args = idx_val.as_fn_call_args();
                                let (val, _) = self.make_method_call(
                                    mods, state, lib, name, *hashes, target, &mut args, *pos, level,
                                )?;
                                val.into()
                            }
                            // {xxx:map}.module::fn_name(...) - syntax error
                            Expr::FnCall(_, _) => unreachable!(
                                "function call in dot chain should not be namespace-qualified"
                            ),
                            // Others - syntax error
                            expr => unreachable!("invalid dot expression: {:?}", expr),
                        };
                        let rhs_chain = match_chain_type(rhs);

                        self.eval_dot_index_chain_helper(
                            mods, state, lib, this_ptr, &mut val, root, &x.rhs, idx_values,
                            rhs_chain, level, new_val,
                        )
                        .map_err(|err| err.fill_position(*x_pos))
                    }
                    // xxx.sub_lhs[expr] | xxx.sub_lhs.expr
                    Expr::Index(x, x_pos) | Expr::Dot(x, x_pos) => {
                        match &x.lhs {
                            // xxx.prop[expr] | xxx.prop.expr
                            Expr::Property(p) => {
                                let ((getter, hash_get), (setter, hash_set), (name, pos)) =
                                    p.as_ref();
                                let rhs_chain = match_chain_type(rhs);
                                let hash_get = FnCallHashes::from_native(*hash_get);
                                let hash_set = FnCallHashes::from_native(*hash_set);
                                let mut arg_values = [target.as_mut(), &mut Default::default()];
                                let args = &mut arg_values[..1];
                                let (mut val, updated) = self
                                    .exec_fn_call(
                                        mods, state, lib, getter, hash_get, args, is_ref, true,
                                        *pos, None, level,
                                    )
                                    .or_else(|err| match *err {
                                        // Try an indexer if property does not exist
                                        EvalAltResult::ErrorDotExpr(_, _) => {
                                            let prop = name.into();
                                            self.get_indexed_mut(
                                                mods, state, lib, target, prop, *pos, false, true,
                                                level,
                                            )
                                            .map(|v| (v.take_or_clone(), false))
                                            .map_err(
                                                |idx_err| match *idx_err {
                                                    EvalAltResult::ErrorIndexingType(_, _) => err,
                                                    _ => idx_err,
                                                },
                                            )
                                        }
                                        _ => Err(err),
                                    })?;

                                let val = &mut val;

                                let (result, may_be_changed) = self
                                    .eval_dot_index_chain_helper(
                                        mods,
                                        state,
                                        lib,
                                        this_ptr,
                                        &mut val.into(),
                                        root,
                                        &x.rhs,
                                        idx_values,
                                        rhs_chain,
                                        level,
                                        new_val,
                                    )
                                    .map_err(|err| err.fill_position(*x_pos))?;

                                // Feed the value back via a setter just in case it has been updated
                                if updated || may_be_changed {
                                    // Re-use args because the first &mut parameter will not be consumed
                                    let mut arg_values = [target.as_mut(), val];
                                    let args = &mut arg_values;
                                    self.exec_fn_call(
                                        mods, state, lib, setter, hash_set, args, is_ref, true,
                                        *pos, None, level,
                                    )
                                    .or_else(
                                        |err| match *err {
                                            // Try an indexer if property does not exist
                                            EvalAltResult::ErrorDotExpr(_, _) => {
                                                let mut prop = name.into();
                                                let args = &mut [target.as_mut(), &mut prop, val];
                                                let hash_set = FnCallHashes::from_native(
                                                    crate::calc_fn_hash(FN_IDX_SET, 3),
                                                );
                                                self.exec_fn_call(
                                                    mods, state, lib, FN_IDX_SET, hash_set, args,
                                                    is_ref, true, *pos, None, level,
                                                )
                                                .or_else(|idx_err| match *idx_err {
                                                    EvalAltResult::ErrorIndexingType(_, _) => {
                                                        // If there is no setter, no need to feed it back because
                                                        // the property is read-only
                                                        Ok((Dynamic::UNIT, false))
                                                    }
                                                    _ => Err(idx_err),
                                                })
                                            }
                                            _ => Err(err),
                                        },
                                    )?;
                                }

                                Ok((result, may_be_changed))
                            }
                            // xxx.fn_name(arg_expr_list)[expr] | xxx.fn_name(arg_expr_list).expr
                            Expr::FnCall(f, pos) if !f.is_qualified() => {
                                let FnCallExpr { name, hashes, .. } = f.as_ref();
                                let rhs_chain = match_chain_type(rhs);
                                let mut args = idx_val.as_fn_call_args();
                                let (mut val, _) = self.make_method_call(
                                    mods, state, lib, name, *hashes, target, &mut args, *pos, level,
                                )?;
                                let val = &mut val;
                                let target = &mut val.into();

                                self.eval_dot_index_chain_helper(
                                    mods, state, lib, this_ptr, target, root, &x.rhs, idx_values,
                                    rhs_chain, level, new_val,
                                )
                                .map_err(|err| err.fill_position(*pos))
                            }
                            // xxx.module::fn_name(...) - syntax error
                            Expr::FnCall(_, _) => unreachable!(
                                "function call in dot chain should not be namespace-qualified"
                            ),
                            // Others - syntax error
                            expr => unreachable!("invalid dot expression: {:?}", expr),
                        }
                    }
                    // Syntax error
                    _ => EvalAltResult::ErrorDotExpr("".into(), rhs.position()).into(),
                }
            }
        }
    }

    /// Evaluate a dot/index chain.
    #[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
    fn eval_dot_index_chain(
        &self,
        scope: &mut Scope,
        mods: &mut Imports,
        state: &mut State,
        lib: &[&Module],
        this_ptr: &mut Option<&mut Dynamic>,
        expr: &Expr,
        level: usize,
        new_val: Option<((Dynamic, Position), (Option<OpAssignment>, Position))>,
    ) -> RhaiResult {
        let (crate::ast::BinaryExpr { lhs, rhs }, chain_type, op_pos) = match expr {
            #[cfg(not(feature = "no_index"))]
            Expr::Index(x, pos) => (x.as_ref(), ChainType::Index, *pos),
            #[cfg(not(feature = "no_object"))]
            Expr::Dot(x, pos) => (x.as_ref(), ChainType::Dot, *pos),
            _ => unreachable!("index or dot chain expected, but gets {:?}", expr),
        };

        let idx_values = &mut Default::default();

        self.eval_indexed_chain(
            scope, mods, state, lib, this_ptr, rhs, chain_type, idx_values, 0, level,
        )?;

        match lhs {
            // id.??? or id[???]
            Expr::Variable(_, var_pos, x) => {
                #[cfg(not(feature = "unchecked"))]
                self.inc_operations(state, *var_pos)?;

                let (target, _) = self.search_namespace(scope, mods, state, lib, this_ptr, lhs)?;

                let obj_ptr = &mut target.into();
                let root = (x.2.as_str(), *var_pos);
                self.eval_dot_index_chain_helper(
                    mods, state, lib, &mut None, obj_ptr, root, rhs, idx_values, chain_type, level,
                    new_val,
                )
                .map(|(v, _)| v)
                .map_err(|err| err.fill_position(op_pos))
            }
            // {expr}.??? = ??? or {expr}[???] = ???
            _ if new_val.is_some() => unreachable!("cannot assign to an expression"),
            // {expr}.??? or {expr}[???]
            expr => {
                let value = self.eval_expr(scope, mods, state, lib, this_ptr, expr, level)?;
                let obj_ptr = &mut value.into();
                let root = ("", expr.position());
                self.eval_dot_index_chain_helper(
                    mods, state, lib, this_ptr, obj_ptr, root, rhs, idx_values, chain_type, level,
                    new_val,
                )
                .map(|(v, _)| v)
                .map_err(|err| err.fill_position(op_pos))
            }
        }
    }

    /// Evaluate a chain of indexes and store the results in a [`StaticVec`].
    /// [`StaticVec`] is used to avoid an allocation in the overwhelming cases of
    /// just a few levels of indexing.
    #[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
    fn eval_indexed_chain(
        &self,
        scope: &mut Scope,
        mods: &mut Imports,
        state: &mut State,
        lib: &[&Module],
        this_ptr: &mut Option<&mut Dynamic>,
        expr: &Expr,
        _parent_chain_type: ChainType,
        idx_values: &mut StaticVec<ChainArgument>,
        size: usize,
        level: usize,
    ) -> Result<(), Box<EvalAltResult>> {
        #[cfg(not(feature = "unchecked"))]
        self.inc_operations(state, expr.position())?;

        match expr {
            #[cfg(not(feature = "no_object"))]
            Expr::FnCall(x, _) if _parent_chain_type == ChainType::Dot && !x.is_qualified() => {
                let mut arg_positions: StaticVec<_> = Default::default();

                let mut arg_values = x
                    .args
                    .iter()
                    .inspect(|arg_expr| arg_positions.push(arg_expr.position()))
                    .map(|arg_expr| {
                        self.eval_expr(scope, mods, state, lib, this_ptr, arg_expr, level)
                            .map(Dynamic::flatten)
                    })
                    .collect::<Result<StaticVec<_>, _>>()?;

                x.literal_args
                    .iter()
                    .inspect(|(_, pos)| arg_positions.push(*pos))
                    .for_each(|(v, _)| arg_values.push(v.clone()));

                idx_values.push((arg_values, arg_positions).into());
            }
            #[cfg(not(feature = "no_object"))]
            Expr::FnCall(_, _) if _parent_chain_type == ChainType::Dot => {
                unreachable!("function call in dot chain should not be namespace-qualified")
            }

            #[cfg(not(feature = "no_object"))]
            Expr::Property(x) if _parent_chain_type == ChainType::Dot => {
                idx_values.push(ChainArgument::Property((x.2).1))
            }
            Expr::Property(_) => unreachable!("unexpected Expr::Property for indexing"),

            Expr::Index(x, _) | Expr::Dot(x, _) => {
                let crate::ast::BinaryExpr { lhs, rhs, .. } = x.as_ref();

                // Evaluate in left-to-right order
                let lhs_val = match lhs {
                    #[cfg(not(feature = "no_object"))]
                    Expr::Property(x) if _parent_chain_type == ChainType::Dot => {
                        ChainArgument::Property((x.2).1)
                    }
                    Expr::Property(_) => unreachable!("unexpected Expr::Property for indexing"),

                    #[cfg(not(feature = "no_object"))]
                    Expr::FnCall(x, _)
                        if _parent_chain_type == ChainType::Dot && !x.is_qualified() =>
                    {
                        let mut arg_positions: StaticVec<_> = Default::default();

                        let mut arg_values = x
                            .args
                            .iter()
                            .inspect(|arg_expr| arg_positions.push(arg_expr.position()))
                            .map(|arg_expr| {
                                self.eval_expr(scope, mods, state, lib, this_ptr, arg_expr, level)
                                    .map(Dynamic::flatten)
                            })
                            .collect::<Result<StaticVec<_>, _>>()?;

                        x.literal_args
                            .iter()
                            .inspect(|(_, pos)| arg_positions.push(*pos))
                            .for_each(|(v, _)| arg_values.push(v.clone()));

                        (arg_values, arg_positions).into()
                    }
                    #[cfg(not(feature = "no_object"))]
                    Expr::FnCall(_, _) if _parent_chain_type == ChainType::Dot => {
                        unreachable!("function call in dot chain should not be namespace-qualified")
                    }
                    #[cfg(not(feature = "no_object"))]
                    expr if _parent_chain_type == ChainType::Dot => {
                        unreachable!("invalid dot expression: {:?}", expr);
                    }
                    #[cfg(not(feature = "no_index"))]
                    _ if _parent_chain_type == ChainType::Index => self
                        .eval_expr(scope, mods, state, lib, this_ptr, lhs, level)
                        .map(|v| (v.flatten(), lhs.position()).into())?,
                    expr => unreachable!("unknown chained expression: {:?}", expr),
                };

                // Push in reverse order
                let chain_type = match expr {
                    #[cfg(not(feature = "no_index"))]
                    Expr::Index(_, _) => ChainType::Index,
                    #[cfg(not(feature = "no_object"))]
                    Expr::Dot(_, _) => ChainType::Dot,
                    _ => unreachable!("index or dot chain expected, but gets {:?}", expr),
                };
                self.eval_indexed_chain(
                    scope, mods, state, lib, this_ptr, rhs, chain_type, idx_values, size, level,
                )?;

                idx_values.push(lhs_val);
            }

            #[cfg(not(feature = "no_object"))]
            _ if _parent_chain_type == ChainType::Dot => {
                unreachable!("invalid dot expression: {:?}", expr);
            }
            #[cfg(not(feature = "no_index"))]
            _ if _parent_chain_type == ChainType::Index => idx_values.push(
                self.eval_expr(scope, mods, state, lib, this_ptr, expr, level)
                    .map(|v| (v.flatten(), expr.position()).into())?,
            ),
            _ => unreachable!("unknown chained expression: {:?}", expr),
        }

        Ok(())
    }

    /// Get the value at the indexed position of a base type.
    /// [`Position`] in [`EvalAltResult`] may be None and should be set afterwards.
    #[cfg(any(not(feature = "no_index"), not(feature = "no_object")))]
    fn get_indexed_mut<'t>(
        &self,
        mods: &mut Imports,
        state: &mut State,
        lib: &[&Module],
        target: &'t mut Dynamic,
        mut idx: Dynamic,
        idx_pos: Position,
        _create: bool,
        indexers: bool,
        level: usize,
    ) -> Result<Target<'t>, Box<EvalAltResult>> {
        #[cfg(not(feature = "unchecked"))]
        self.inc_operations(state, Position::NONE)?;

        match target {
            #[cfg(not(feature = "no_index"))]
            Dynamic(Union::Array(arr, _, _)) => {
                // val_array[idx]
                let index = idx
                    .as_int()
                    .map_err(|err| self.make_type_mismatch_err::<crate::INT>(err, idx_pos))?;

                let arr_len = arr.len();

                #[cfg(not(feature = "unchecked"))]
                let arr_idx = if index < 0 {
                    // Count from end if negative
                    arr_len
                        - index
                            .checked_abs()
                            .ok_or_else(|| {
                                Box::new(EvalAltResult::ErrorArrayBounds(arr_len, index, idx_pos))
                            })
                            .and_then(|n| {
                                if n as usize > arr_len {
                                    Err(EvalAltResult::ErrorArrayBounds(arr_len, index, idx_pos)
                                        .into())
                                } else {
                                    Ok(n as usize)
                                }
                            })?
                } else {
                    index as usize
                };
                #[cfg(feature = "unchecked")]
                let arr_idx = if index < 0 {
                    // Count from end if negative
                    arr_len - index.abs() as usize
                } else {
                    index as usize
                };

                arr.get_mut(arr_idx)
                    .map(Target::from)
                    .ok_or_else(|| EvalAltResult::ErrorArrayBounds(arr_len, index, idx_pos).into())
            }

            #[cfg(not(feature = "no_object"))]
            Dynamic(Union::Map(map, _, _)) => {
                // val_map[idx]
                let index = &*idx.read_lock::<ImmutableString>().ok_or_else(|| {
                    self.make_type_mismatch_err::<ImmutableString>(idx.type_name(), idx_pos)
                })?;

                if _create && !map.contains_key(index.as_str()) {
                    map.insert(index.clone().into(), Default::default());
                }

                Ok(map
                    .get_mut(index.as_str())
                    .map(Target::from)
                    .unwrap_or_else(|| Target::from(Dynamic::UNIT)))
            }

            #[cfg(not(feature = "no_index"))]
            Dynamic(Union::Str(s, _, _)) => {
                // val_string[idx]
                let index = idx
                    .as_int()
                    .map_err(|err| self.make_type_mismatch_err::<crate::INT>(err, idx_pos))?;

                let (ch, offset) = if index >= 0 {
                    // Count from end if negative
                    let offset = index as usize;
                    (
                        s.chars().nth(offset).ok_or_else(|| {
                            let chars_len = s.chars().count();
                            EvalAltResult::ErrorStringBounds(chars_len, index, idx_pos)
                        })?,
                        offset,
                    )
                } else if let Some(index) = index.checked_abs() {
                    let offset = index as usize;
                    (
                        s.chars().rev().nth(offset - 1).ok_or_else(|| {
                            let chars_len = s.chars().count();
                            EvalAltResult::ErrorStringBounds(chars_len, index, idx_pos)
                        })?,
                        offset,
                    )
                } else {
                    let chars_len = s.chars().count();
                    return EvalAltResult::ErrorStringBounds(chars_len, index, idx_pos).into();
                };

                Ok(Target::StringChar(target, offset, ch.into()))
            }

            _ if indexers => {
                let args = &mut [target, &mut idx];
                let hash_get = FnCallHashes::from_native(crate::calc_fn_hash(FN_IDX_GET, 2));

                self.exec_fn_call(
                    mods, state, lib, FN_IDX_GET, hash_get, args, true, true, idx_pos, None, level,
                )
                .map(|(v, _)| v.into())
            }

            _ => EvalAltResult::ErrorIndexingType(
                self.map_type_name(target.type_name()).into(),
                Position::NONE,
            )
            .into(),
        }
    }

    /// Evaluate an expression.
    pub(crate) fn eval_expr(
        &self,
        scope: &mut Scope,
        mods: &mut Imports,
        state: &mut State,
        lib: &[&Module],
        this_ptr: &mut Option<&mut Dynamic>,
        expr: &Expr,
        level: usize,
    ) -> RhaiResult {
        #[cfg(not(feature = "unchecked"))]
        self.inc_operations(state, expr.position())?;

        let result = match expr {
            Expr::DynamicConstant(x, _) => Ok(x.as_ref().clone()),
            Expr::IntegerConstant(x, _) => Ok((*x).into()),
            #[cfg(not(feature = "no_float"))]
            Expr::FloatConstant(x, _) => Ok((*x).into()),
            Expr::StringConstant(x, _) => Ok(x.clone().into()),
            Expr::CharConstant(x, _) => Ok((*x).into()),

            Expr::Variable(None, var_pos, x) if x.0.is_none() && x.2 == KEYWORD_THIS => this_ptr
                .as_deref()
                .cloned()
                .ok_or_else(|| EvalAltResult::ErrorUnboundThis(*var_pos).into()),
            Expr::Variable(_, _, _) => self
                .search_namespace(scope, mods, state, lib, this_ptr, expr)
                .map(|(val, _)| val.take_or_clone()),

            // Statement block
            Expr::Stmt(x) if x.is_empty() => Ok(Dynamic::UNIT),
            Expr::Stmt(x) => {
                self.eval_stmt_block(scope, mods, state, lib, this_ptr, x, true, level)
            }

            // lhs[idx_expr]
            #[cfg(not(feature = "no_index"))]
            Expr::Index(_, _) => {
                self.eval_dot_index_chain(scope, mods, state, lib, this_ptr, expr, level, None)
            }

            // lhs.dot_rhs
            #[cfg(not(feature = "no_object"))]
            Expr::Dot(_, _) => {
                self.eval_dot_index_chain(scope, mods, state, lib, this_ptr, expr, level, None)
            }

            // `... ${...} ...`
            Expr::InterpolatedString(x) => {
                let mut pos = expr.position();
                let mut result: Dynamic = self.empty_string.clone().into();

                for expr in x.iter() {
                    let item = self.eval_expr(scope, mods, state, lib, this_ptr, expr, level)?;
                    self.eval_op_assignment(
                        mods,
                        state,
                        lib,
                        Some(OpAssignment::new(TOKEN_OP_CONCAT)),
                        pos,
                        (&mut result).into(),
                        ("", Position::NONE),
                        item,
                        expr.position(),
                    )?;
                    pos = expr.position();
                }

                assert!(
                    result.is::<ImmutableString>(),
                    "interpolated string must be a string"
                );

                Ok(result)
            }

            #[cfg(not(feature = "no_index"))]
            Expr::Array(x, _) => {
                let mut arr = Array::with_capacity(x.len());
                for item in x.as_ref() {
                    arr.push(
                        self.eval_expr(scope, mods, state, lib, this_ptr, item, level)?
                            .flatten(),
                    );
                }
                Ok(arr.into())
            }

            #[cfg(not(feature = "no_object"))]
            Expr::Map(x, _) => {
                let mut map = x.1.clone();
                for (Ident { name: key, .. }, expr) in &x.0 {
                    let value_ref = map
                        .get_mut(key.as_str())
                        .expect("never fails because the template should contain all the keys");
                    *value_ref = self
                        .eval_expr(scope, mods, state, lib, this_ptr, expr, level)?
                        .flatten();
                }
                Ok(map.into())
            }

            // Namespace-qualified function call
            Expr::FnCall(x, pos) if x.is_qualified() => {
                let FnCallExpr {
                    name,
                    namespace,
                    hashes,
                    args,
                    literal_args: c_args,
                    ..
                } = x.as_ref();
                let namespace = namespace
                    .as_ref()
                    .expect("never fails because function call is qualified");
                let hash = hashes.native_hash();
                self.make_qualified_function_call(
                    scope, mods, state, lib, this_ptr, namespace, name, args, c_args, hash, *pos,
                    level,
                )
            }

            // Normal function call
            Expr::FnCall(x, pos) => {
                let FnCallExpr {
                    name,
                    capture,
                    hashes,
                    args,
                    literal_args: c_args,
                    ..
                } = x.as_ref();
                self.make_function_call(
                    scope, mods, state, lib, this_ptr, name, args, c_args, *hashes, *pos, *capture,
                    level,
                )
            }

            Expr::And(x, _) => {
                Ok((self
                    .eval_expr(scope, mods, state, lib, this_ptr, &x.lhs, level)?
                    .as_bool()
                    .map_err(|err| self.make_type_mismatch_err::<bool>(err, x.lhs.position()))?
                    && // Short-circuit using &&
                self
                    .eval_expr(scope, mods, state, lib, this_ptr, &x.rhs, level)?
                    .as_bool()
                    .map_err(|err| self.make_type_mismatch_err::<bool>(err, x.rhs.position()))?)
                .into())
            }

            Expr::Or(x, _) => {
                Ok((self
                    .eval_expr(scope, mods, state, lib, this_ptr, &x.lhs, level)?
                    .as_bool()
                    .map_err(|err| self.make_type_mismatch_err::<bool>(err, x.lhs.position()))?
                    || // Short-circuit using ||
                self
                    .eval_expr(scope, mods, state, lib, this_ptr, &x.rhs, level)?
                    .as_bool()
                    .map_err(|err| self.make_type_mismatch_err::<bool>(err, x.rhs.position()))?)
                .into())
            }

            Expr::BoolConstant(x, _) => Ok((*x).into()),
            Expr::Unit(_) => Ok(Dynamic::UNIT),

            Expr::Custom(custom, _) => {
                let expressions = custom
                    .keywords
                    .iter()
                    .map(Into::into)
                    .collect::<StaticVec<_>>();
                let key_token = custom.tokens.first().expect(
                    "never fails because a custom syntax stream must contain at least one token",
                );
                let custom_def = self
                                    .custom_syntax.get(key_token)
                                    .expect("never fails because the custom syntax leading token should match with definition");
                let mut context = EvalContext {
                    engine: self,
                    scope,
                    mods,
                    state,
                    lib,
                    this_ptr,
                    level,
                };
                (custom_def.func)(&mut context, &expressions)
            }

            _ => unreachable!("expression cannot be evaluated: {:?}", expr),
        };

        #[cfg(not(feature = "unchecked"))]
        self.check_data_size(&result)
            .map_err(|err| err.fill_position(expr.position()))?;

        result
    }

    /// Evaluate a statements block.
    pub(crate) fn eval_stmt_block(
        &self,
        scope: &mut Scope,
        mods: &mut Imports,
        state: &mut State,
        lib: &[&Module],
        this_ptr: &mut Option<&mut Dynamic>,
        statements: &[Stmt],
        restore_prev_state: bool,
        level: usize,
    ) -> RhaiResult {
        if statements.is_empty() {
            return Ok(Dynamic::UNIT);
        }

        let mut _extra_fn_resolution_cache = false;
        let prev_always_search = state.always_search;
        let prev_scope_len = scope.len();
        let prev_mods_len = mods.len();

        if restore_prev_state {
            state.scope_level += 1;
        }

        let result = statements.iter().try_fold(Dynamic::UNIT, |_, stmt| {
            let _mods_len = mods.len();

            let r = self.eval_stmt(scope, mods, state, lib, this_ptr, stmt, level)?;

            #[cfg(not(feature = "no_module"))]
            if matches!(stmt, Stmt::Import(_, _, _)) {
                // Get the extra modules - see if any functions are marked global.
                // Without global functions, the extra modules never affect function resolution.
                if mods
                    .scan_raw()
                    .skip(_mods_len)
                    .any(|(_, m)| m.contains_indexed_global_functions())
                {
                    if _extra_fn_resolution_cache {
                        // When new module is imported with global functions and there is already
                        // a new cache, clear it - notice that this is expensive as all function
                        // resolutions must start again
                        state.fn_resolution_cache_mut().clear();
                    } else if restore_prev_state {
                        // When new module is imported with global functions, push a new cache
                        state.push_fn_resolution_cache();
                        _extra_fn_resolution_cache = true;
                    } else {
                        // When the block is to be evaluated in-place, just clear the current cache
                        state.fn_resolution_cache_mut().clear();
                    }
                }
            }

            Ok(r)
        });

        if _extra_fn_resolution_cache {
            // If imports list is modified, pop the functions lookup cache
            state.pop_fn_resolution_cache();
        }

        if restore_prev_state {
            scope.rewind(prev_scope_len);
            mods.truncate(prev_mods_len);
            state.scope_level -= 1;

            // The impact of new local variables goes away at the end of a block
            // because any new variables introduced will go out of scope
            state.always_search = prev_always_search;
        }

        result
    }

    pub(crate) fn eval_op_assignment(
        &self,
        mods: &mut Imports,
        state: &mut State,
        lib: &[&Module],
        op_info: Option<OpAssignment>,
        op_pos: Position,
        mut target: Target,
        root: (&str, Position),
        mut new_value: Dynamic,
        new_value_pos: Position,
    ) -> Result<(), Box<EvalAltResult>> {
        if target.is_read_only() {
            // Assignment to constant variable
            return EvalAltResult::ErrorAssignmentToConstant(root.0.to_string(), root.1).into();
        }

        if let Some(OpAssignment {
            hash_op_assign,
            hash_op,
            op,
        }) = op_info
        {
            let mut lock_guard;
            let lhs_ptr_inner;

            #[cfg(not(feature = "no_closure"))]
            let target_is_shared = target.is_shared();
            #[cfg(feature = "no_closure")]
            let target_is_shared = false;

            if target_is_shared {
                lock_guard = target
                    .write_lock::<Dynamic>()
                    .expect("never fails when casting to `Dynamic`");
                lhs_ptr_inner = &mut *lock_guard;
            } else {
                lhs_ptr_inner = &mut *target;
            }

            let hash = hash_op_assign;
            let args = &mut [lhs_ptr_inner, &mut new_value];

            match self.call_native_fn(mods, state, lib, op, hash, args, true, true, op_pos) {
                Ok(_) => (),
                Err(err) if matches!(err.as_ref(), EvalAltResult::ErrorFunctionNotFound(f, _) if f.starts_with(op)) =>
                {
                    // Expand to `var = var op rhs`
                    let op = &op[..op.len() - 1]; // extract operator without =

                    // Run function
                    let (value, _) = self
                        .call_native_fn(mods, state, lib, op, hash_op, args, true, false, op_pos)?;

                    *args[0] = value.flatten();
                }
                err => return err.map(|_| ()),
            }

            Ok(())
        } else {
            // Normal assignment
            target.set_value(new_value, new_value_pos)?;
            Ok(())
        }
    }

    /// Evaluate a statement.
    ///
    /// # Safety
    ///
    /// This method uses some unsafe code, mainly for avoiding cloning of local variable names via
    /// direct lifetime casting.
    pub(crate) fn eval_stmt(
        &self,
        scope: &mut Scope,
        mods: &mut Imports,
        state: &mut State,
        lib: &[&Module],
        this_ptr: &mut Option<&mut Dynamic>,
        stmt: &Stmt,
        level: usize,
    ) -> RhaiResult {
        #[cfg(not(feature = "unchecked"))]
        self.inc_operations(state, stmt.position())?;

        let result = match stmt {
            // No-op
            Stmt::Noop(_) => Ok(Dynamic::UNIT),

            // Expression as statement
            Stmt::Expr(expr) => Ok(self
                .eval_expr(scope, mods, state, lib, this_ptr, expr, level)?
                .flatten()),

            // var op= rhs
            Stmt::Assignment(x, op_pos) if x.0.is_variable_access(false) => {
                let (lhs_expr, op_info, rhs_expr) = x.as_ref();
                let rhs_val = self
                    .eval_expr(scope, mods, state, lib, this_ptr, rhs_expr, level)?
                    .flatten();
                let (lhs_ptr, pos) =
                    self.search_namespace(scope, mods, state, lib, this_ptr, lhs_expr)?;

                let var_name = lhs_expr
                    .get_variable_name(false)
                    .expect("never fails because `lhs_ptr` is a `Variable`s");

                if !lhs_ptr.is_ref() {
                    return EvalAltResult::ErrorAssignmentToConstant(var_name.to_string(), pos)
                        .into();
                }

                #[cfg(not(feature = "unchecked"))]
                self.inc_operations(state, pos)?;

                self.eval_op_assignment(
                    mods,
                    state,
                    lib,
                    op_info.clone(),
                    *op_pos,
                    lhs_ptr,
                    (var_name, pos),
                    rhs_val,
                    rhs_expr.position(),
                )?;
                Ok(Dynamic::UNIT)
            }

            // lhs op= rhs
            Stmt::Assignment(x, op_pos) => {
                let (lhs_expr, op_info, rhs_expr) = x.as_ref();
                let rhs_val = self
                    .eval_expr(scope, mods, state, lib, this_ptr, rhs_expr, level)?
                    .flatten();
                let _new_val = Some(((rhs_val, rhs_expr.position()), (op_info.clone(), *op_pos)));

                // Must be either `var[index] op= val` or `var.prop op= val`
                match lhs_expr {
                    // name op= rhs (handled above)
                    Expr::Variable(_, _, _) => {
                        unreachable!("Expr::Variable case should already been handled")
                    }
                    // idx_lhs[idx_expr] op= rhs
                    #[cfg(not(feature = "no_index"))]
                    Expr::Index(_, _) => {
                        self.eval_dot_index_chain(
                            scope, mods, state, lib, this_ptr, lhs_expr, level, _new_val,
                        )?;
                        Ok(Dynamic::UNIT)
                    }
                    // dot_lhs.dot_rhs op= rhs
                    #[cfg(not(feature = "no_object"))]
                    Expr::Dot(_, _) => {
                        self.eval_dot_index_chain(
                            scope, mods, state, lib, this_ptr, lhs_expr, level, _new_val,
                        )?;
                        Ok(Dynamic::UNIT)
                    }
                    _ => unreachable!("cannot assign to expression: {:?}", lhs_expr),
                }
            }

            // Block scope
            Stmt::Block(statements, _) if statements.is_empty() => Ok(Dynamic::UNIT),
            Stmt::Block(statements, _) => {
                self.eval_stmt_block(scope, mods, state, lib, this_ptr, statements, true, level)
            }

            // If statement
            Stmt::If(expr, x, _) => {
                let guard_val = self
                    .eval_expr(scope, mods, state, lib, this_ptr, expr, level)?
                    .as_bool()
                    .map_err(|err| self.make_type_mismatch_err::<bool>(err, expr.position()))?;

                if guard_val {
                    if !x.0.is_empty() {
                        self.eval_stmt_block(scope, mods, state, lib, this_ptr, &x.0, true, level)
                    } else {
                        Ok(Dynamic::UNIT)
                    }
                } else {
                    if !x.1.is_empty() {
                        self.eval_stmt_block(scope, mods, state, lib, this_ptr, &x.1, true, level)
                    } else {
                        Ok(Dynamic::UNIT)
                    }
                }
            }

            // Switch statement
            Stmt::Switch(match_expr, x, _) => {
                let (table, def_stmt) = x.as_ref();

                let value = self.eval_expr(scope, mods, state, lib, this_ptr, match_expr, level)?;

                if value.is_hashable() {
                    let hasher = &mut get_hasher();
                    value.hash(hasher);
                    let hash = hasher.finish();

                    table.get(&hash).and_then(|t| {
                        if let Some(condition) = &t.0 {
                            match self
                                .eval_expr(scope, mods, state, lib, this_ptr, &condition, level)
                                .and_then(|v| {
                                    v.as_bool().map_err(|err| {
                                        self.make_type_mismatch_err::<bool>(
                                            err,
                                            condition.position(),
                                        )
                                    })
                                }) {
                                Ok(true) => (),
                                Ok(false) => return None,
                                Err(err) => return Some(Err(err)),
                            }
                        }

                        let statements = &t.1;

                        Some(if !statements.is_empty() {
                            self.eval_stmt_block(
                                scope, mods, state, lib, this_ptr, statements, true, level,
                            )
                        } else {
                            Ok(Dynamic::UNIT)
                        })
                    })
                } else {
                    // Non-hashable values never match any specific clause
                    None
                }
                .unwrap_or_else(|| {
                    // Default match clause
                    if !def_stmt.is_empty() {
                        self.eval_stmt_block(
                            scope, mods, state, lib, this_ptr, def_stmt, true, level,
                        )
                    } else {
                        Ok(Dynamic::UNIT)
                    }
                })
            }

            // While loop
            Stmt::While(expr, body, _) => loop {
                let condition = if !expr.is_unit() {
                    self.eval_expr(scope, mods, state, lib, this_ptr, expr, level)?
                        .as_bool()
                        .map_err(|err| self.make_type_mismatch_err::<bool>(err, expr.position()))?
                } else {
                    true
                };

                if !condition {
                    return Ok(Dynamic::UNIT);
                }
                if !body.is_empty() {
                    match self.eval_stmt_block(scope, mods, state, lib, this_ptr, body, true, level)
                    {
                        Ok(_) => (),
                        Err(err) => match *err {
                            EvalAltResult::LoopBreak(false, _) => (),
                            EvalAltResult::LoopBreak(true, _) => return Ok(Dynamic::UNIT),
                            _ => return Err(err),
                        },
                    }
                }
            },

            // Do loop
            Stmt::Do(body, expr, is_while, _) => loop {
                if !body.is_empty() {
                    match self.eval_stmt_block(scope, mods, state, lib, this_ptr, body, true, level)
                    {
                        Ok(_) => (),
                        Err(err) => match *err {
                            EvalAltResult::LoopBreak(false, _) => continue,
                            EvalAltResult::LoopBreak(true, _) => return Ok(Dynamic::UNIT),
                            _ => return Err(err),
                        },
                    }
                }

                let condition = self
                    .eval_expr(scope, mods, state, lib, this_ptr, expr, level)?
                    .as_bool()
                    .map_err(|err| self.make_type_mismatch_err::<bool>(err, expr.position()))?;

                if condition ^ *is_while {
                    return Ok(Dynamic::UNIT);
                }
            },

            // For loop
            Stmt::For(expr, x, _) => {
                let (Ident { name, .. }, statements) = x.as_ref();
                let iter_obj = self
                    .eval_expr(scope, mods, state, lib, this_ptr, expr, level)?
                    .flatten();
                let iter_type = iter_obj.type_id();

                // lib should only contain scripts, so technically they cannot have iterators

                // Search order:
                // 1) Global namespace - functions registered via Engine::register_XXX
                // 2) Global modules - packages
                // 3) Imported modules - functions marked with global namespace
                // 4) Global sub-modules - functions marked with global namespace
                let func = self
                    .global_namespace
                    .get_iter(iter_type)
                    .or_else(|| {
                        self.global_modules
                            .iter()
                            .find_map(|m| m.get_iter(iter_type))
                    })
                    .or_else(|| mods.get_iter(iter_type))
                    .or_else(|| {
                        self.global_sub_modules
                            .values()
                            .find_map(|m| m.get_qualified_iter(iter_type))
                    });

                if let Some(func) = func {
                    // Add the loop variable
                    let var_name: Cow<'_, str> = if state.is_global() {
                        name.to_string().into()
                    } else {
                        unsafe_cast_var_name_to_lifetime(name).into()
                    };
                    scope.push(var_name, ());
                    let index = scope.len() - 1;
                    state.scope_level += 1;

                    for iter_value in func(iter_obj) {
                        let loop_var = scope.get_mut_by_index(index);
                        let value = iter_value.flatten();

                        #[cfg(not(feature = "no_closure"))]
                        let loop_var_is_shared = loop_var.is_shared();
                        #[cfg(feature = "no_closure")]
                        let loop_var_is_shared = false;

                        if loop_var_is_shared {
                            let mut value_ref = loop_var
                                .write_lock()
                                .expect("never fails when casting to `Dynamic`");
                            *value_ref = value;
                        } else {
                            *loop_var = value;
                        }

                        #[cfg(not(feature = "unchecked"))]
                        self.inc_operations(state, statements.position())?;

                        if statements.is_empty() {
                            continue;
                        }

                        let result = self.eval_stmt_block(
                            scope, mods, state, lib, this_ptr, statements, true, level,
                        );

                        match result {
                            Ok(_) => (),
                            Err(err) => match *err {
                                EvalAltResult::LoopBreak(false, _) => (),
                                EvalAltResult::LoopBreak(true, _) => break,
                                _ => return Err(err),
                            },
                        }
                    }

                    state.scope_level -= 1;
                    scope.rewind(scope.len() - 1);
                    Ok(Dynamic::UNIT)
                } else {
                    EvalAltResult::ErrorFor(expr.position()).into()
                }
            }

            // Continue statement
            Stmt::Continue(pos) => EvalAltResult::LoopBreak(false, *pos).into(),

            // Break statement
            Stmt::Break(pos) => EvalAltResult::LoopBreak(true, *pos).into(),

            // Namespace-qualified function call
            Stmt::FnCall(x, pos) if x.is_qualified() => {
                let FnCallExpr {
                    name,
                    namespace,
                    hashes,
                    args,
                    literal_args: c_args,
                    ..
                } = x.as_ref();
                let namespace = namespace
                    .as_ref()
                    .expect("never fails because function call is qualified");
                let hash = hashes.native_hash();
                self.make_qualified_function_call(
                    scope, mods, state, lib, this_ptr, namespace, name, args, c_args, hash, *pos,
                    level,
                )
            }

            // Normal function call
            Stmt::FnCall(x, pos) => {
                let FnCallExpr {
                    name,
                    capture,
                    hashes,
                    args,
                    literal_args: c_args,
                    ..
                } = x.as_ref();
                self.make_function_call(
                    scope, mods, state, lib, this_ptr, name, args, c_args, *hashes, *pos, *capture,
                    level,
                )
            }

            // Try/Catch statement
            Stmt::TryCatch(x, _, _) => {
                let (try_stmt, err_var, catch_stmt) = x.as_ref();

                let result = self
                    .eval_stmt_block(scope, mods, state, lib, this_ptr, try_stmt, true, level)
                    .map(|_| Dynamic::UNIT);

                match result {
                    Ok(_) => result,
                    Err(err) if err.is_pseudo_error() => Err(err),
                    Err(err) if !err.is_catchable() => Err(err),
                    Err(mut err) => {
                        let err_value = match *err {
                            EvalAltResult::ErrorRuntime(ref x, _) => x.clone(),

                            #[cfg(feature = "no_object")]
                            _ => {
                                err.take_position();
                                err.to_string().into()
                            }
                            #[cfg(not(feature = "no_object"))]
                            _ => {
                                use crate::INT;

                                let mut err_map: Map = Default::default();
                                let err_pos = err.take_position();

                                err_map.insert("message".into(), err.to_string().into());

                                state
                                    .source
                                    .as_ref()
                                    .map(|source| err_map.insert("source".into(), source.into()));

                                if err_pos.is_none() {
                                    // No position info
                                } else {
                                    let line = err_pos.line().expect("never fails because a non-NONE `Position` always has a line number") as INT;
                                    let position = if err_pos.is_beginning_of_line() {
                                        0
                                    } else {
                                        err_pos.position().expect("never fails because a non-NONE `Position` always has a character position")
                                    } as INT;
                                    err_map.insert("line".into(), line.into());
                                    err_map.insert("position".into(), position.into());
                                }

                                err.dump_fields(&mut err_map);
                                err_map.into()
                            }
                        };

                        let orig_scope_len = scope.len();
                        state.scope_level += 1;

                        err_var.as_ref().map(|Ident { name, .. }| {
                            scope.push(unsafe_cast_var_name_to_lifetime(name), err_value)
                        });

                        let result = self.eval_stmt_block(
                            scope, mods, state, lib, this_ptr, catch_stmt, true, level,
                        );

                        state.scope_level -= 1;
                        scope.rewind(orig_scope_len);

                        match result {
                            Ok(_) => Ok(Dynamic::UNIT),
                            Err(result_err) => match *result_err {
                                // Re-throw exception
                                EvalAltResult::ErrorRuntime(Dynamic(Union::Unit(_, _, _)), pos) => {
                                    err.set_position(pos);
                                    Err(err)
                                }
                                _ => Err(result_err),
                            },
                        }
                    }
                }
            }

            // Return value
            Stmt::Return(ReturnType::Return, Some(expr), pos) => EvalAltResult::Return(
                self.eval_expr(scope, mods, state, lib, this_ptr, expr, level)?
                    .flatten(),
                *pos,
            )
            .into(),

            // Empty return
            Stmt::Return(ReturnType::Return, None, pos) => {
                EvalAltResult::Return(Dynamic::UNIT, *pos).into()
            }

            // Throw value
            Stmt::Return(ReturnType::Exception, Some(expr), pos) => EvalAltResult::ErrorRuntime(
                self.eval_expr(scope, mods, state, lib, this_ptr, expr, level)?
                    .flatten(),
                *pos,
            )
            .into(),

            // Empty throw
            Stmt::Return(ReturnType::Exception, None, pos) => {
                EvalAltResult::ErrorRuntime(Dynamic::UNIT, *pos).into()
            }

            // Let/const statement
            Stmt::Let(expr, x, export, _) | Stmt::Const(expr, x, export, _) => {
                let name = &x.name;
                let entry_type = match stmt {
                    Stmt::Let(_, _, _, _) => AccessMode::ReadWrite,
                    Stmt::Const(_, _, _, _) => AccessMode::ReadOnly,
                    _ => unreachable!("should be Stmt::Let or Stmt::Const, but gets {:?}", stmt),
                };

                let value = self
                    .eval_expr(scope, mods, state, lib, this_ptr, expr, level)?
                    .flatten();

                let (var_name, _alias): (Cow<'_, str>, _) = if state.is_global() {
                    #[cfg(not(feature = "no_function"))]
                    if entry_type == AccessMode::ReadOnly && lib.iter().any(|&m| !m.is_empty()) {
                        let global = if let Some(index) = mods.find(KEYWORD_GLOBAL) {
                            match mods
                                .get_mut(index)
                                .expect("never fails because the index came from `find`")
                            {
                                m if m.internal => Some(m),
                                _ => None,
                            }
                        } else {
                            // Create automatic global module
                            let mut global = Module::new();
                            global.internal = true;
                            mods.push(KEYWORD_GLOBAL, global);
                            Some(
                                mods.get_mut(mods.len() - 1)
                                    .expect("never fails because the global module was just added"),
                            )
                        };

                        if let Some(global) = global {
                            Shared::get_mut(global)
                                .expect("never fails because the global module is never shared")
                                .set_var(name.clone(), value.clone());
                        }
                    }

                    (
                        name.to_string().into(),
                        if *export { Some(name.clone()) } else { None },
                    )
                } else if *export {
                    unreachable!("exported variable not on global level");
                } else {
                    (unsafe_cast_var_name_to_lifetime(name).into(), None)
                };

                scope.push_dynamic_value(var_name, entry_type, value);

                #[cfg(not(feature = "no_module"))]
                _alias.map(|alias| scope.add_entry_alias(scope.len() - 1, alias));

                Ok(Dynamic::UNIT)
            }

            // Import statement
            #[cfg(not(feature = "no_module"))]
            Stmt::Import(expr, export, _pos) => {
                // Guard against too many modules
                #[cfg(not(feature = "unchecked"))]
                if state.modules >= self.max_modules() {
                    return EvalAltResult::ErrorTooManyModules(*_pos).into();
                }

                if let Some(path) = self
                    .eval_expr(scope, mods, state, lib, this_ptr, &expr, level)?
                    .try_cast::<ImmutableString>()
                {
                    use crate::ModuleResolver;

                    let source = state.source.as_ref().map(|s| s.as_str());
                    let expr_pos = expr.position();

                    let module = state
                        .resolver
                        .as_ref()
                        .and_then(|r| match r.resolve(self, source, &path, expr_pos) {
                            Ok(m) => return Some(Ok(m)),
                            Err(err) => match *err {
                                EvalAltResult::ErrorModuleNotFound(_, _) => None,
                                _ => return Some(Err(err)),
                            },
                        })
                        .unwrap_or_else(|| {
                            self.module_resolver.resolve(self, source, &path, expr_pos)
                        })?;

                    export.as_ref().map(|x| x.name.clone()).map(|name| {
                        if !module.is_indexed() {
                            // Index the module (making a clone copy if necessary) if it is not indexed
                            let mut module = crate::fn_native::shared_take_or_clone(module);
                            module.build_index();
                            mods.push(name, module);
                        } else {
                            mods.push(name, module);
                        }
                    });

                    state.modules += 1;

                    Ok(Dynamic::UNIT)
                } else {
                    Err(self.make_type_mismatch_err::<ImmutableString>("", expr.position()))
                }
            }

            // Export statement
            #[cfg(not(feature = "no_module"))]
            Stmt::Export(list, _) => {
                for (Ident { name, pos, .. }, rename) in list.iter() {
                    // Mark scope variables as public
                    if let Some(index) = scope.get_index(name).map(|(i, _)| i) {
                        let alias = rename.as_ref().map(|x| &x.name).unwrap_or_else(|| name);
                        scope.add_entry_alias(index, alias.clone());
                    } else {
                        return EvalAltResult::ErrorVariableNotFound(name.to_string(), *pos).into();
                    }
                }
                Ok(Dynamic::UNIT)
            }

            // Share statement
            #[cfg(not(feature = "no_closure"))]
            Stmt::Share(name) => {
                scope.get_index(name).map(|(index, _)| {
                    let val = scope.get_mut_by_index(index);

                    if !val.is_shared() {
                        // Replace the variable with a shared value.
                        *val = std::mem::take(val).into_shared();
                    }
                });
                Ok(Dynamic::UNIT)
            }
        };

        #[cfg(not(feature = "unchecked"))]
        self.check_data_size(&result)
            .map_err(|err| err.fill_position(stmt.position()))?;

        result
    }

    /// Check a result to ensure that the data size is within allowable limit.
    #[cfg(not(feature = "unchecked"))]
    fn check_data_size(&self, result: &RhaiResult) -> Result<(), Box<EvalAltResult>> {
        let result = match result {
            Err(_) => return Ok(()),
            Ok(r) => r,
        };

        // If no data size limits, just return
        let mut _has_limit = self.limits.max_string_size.is_some();
        #[cfg(not(feature = "no_index"))]
        {
            _has_limit = _has_limit || self.limits.max_array_size.is_some();
        }
        #[cfg(not(feature = "no_object"))]
        {
            _has_limit = _has_limit || self.limits.max_map_size.is_some();
        }

        if !_has_limit {
            return Ok(());
        }

        // Recursively calculate the size of a value (especially `Array` and `Map`)
        fn calc_size(value: &Dynamic) -> (usize, usize, usize) {
            match value {
                #[cfg(not(feature = "no_index"))]
                Dynamic(Union::Array(arr, _, _)) => {
                    let mut arrays = 0;
                    let mut maps = 0;

                    arr.iter().for_each(|value| match value {
                        Dynamic(Union::Array(_, _, _)) => {
                            let (a, m, _) = calc_size(value);
                            arrays += a;
                            maps += m;
                        }
                        #[cfg(not(feature = "no_object"))]
                        Dynamic(Union::Map(_, _, _)) => {
                            let (a, m, _) = calc_size(value);
                            arrays += a;
                            maps += m;
                        }
                        _ => arrays += 1,
                    });

                    (arrays, maps, 0)
                }
                #[cfg(not(feature = "no_object"))]
                Dynamic(Union::Map(map, _, _)) => {
                    let mut arrays = 0;
                    let mut maps = 0;

                    map.values().for_each(|value| match value {
                        #[cfg(not(feature = "no_index"))]
                        Dynamic(Union::Array(_, _, _)) => {
                            let (a, m, _) = calc_size(value);
                            arrays += a;
                            maps += m;
                        }
                        Dynamic(Union::Map(_, _, _)) => {
                            let (a, m, _) = calc_size(value);
                            arrays += a;
                            maps += m;
                        }
                        _ => maps += 1,
                    });

                    (arrays, maps, 0)
                }
                Dynamic(Union::Str(s, _, _)) => (0, 0, s.len()),
                _ => (0, 0, 0),
            }
        }

        let (_arr, _map, s) = calc_size(result);

        if s > self
            .limits
            .max_string_size
            .map_or(usize::MAX, NonZeroUsize::get)
        {
            return EvalAltResult::ErrorDataTooLarge(
                "Length of string".to_string(),
                Position::NONE,
            )
            .into();
        }

        #[cfg(not(feature = "no_index"))]
        if _arr
            > self
                .limits
                .max_array_size
                .map_or(usize::MAX, NonZeroUsize::get)
        {
            return EvalAltResult::ErrorDataTooLarge("Size of array".to_string(), Position::NONE)
                .into();
        }

        #[cfg(not(feature = "no_object"))]
        if _map
            > self
                .limits
                .max_map_size
                .map_or(usize::MAX, NonZeroUsize::get)
        {
            return EvalAltResult::ErrorDataTooLarge(
                "Size of object map".to_string(),
                Position::NONE,
            )
            .into();
        }

        Ok(())
    }

    /// Check if the number of operations stay within limit.
    #[cfg(not(feature = "unchecked"))]
    pub(crate) fn inc_operations(
        &self,
        state: &mut State,
        pos: Position,
    ) -> Result<(), Box<EvalAltResult>> {
        state.operations += 1;

        // Guard against too many operations
        if self.max_operations() > 0 && state.operations > self.max_operations() {
            return EvalAltResult::ErrorTooManyOperations(pos).into();
        }

        // Report progress - only in steps
        if let Some(ref progress) = self.progress {
            if let Some(token) = progress(state.operations) {
                // Terminate script if progress returns a termination token
                return EvalAltResult::ErrorTerminated(token, pos).into();
            }
        }

        Ok(())
    }

    /// Pretty-print a type name.
    ///
    /// If a type is registered via [`register_type_with_name`][Engine::register_type_with_name],
    /// the type name provided for the registration will be used.
    #[inline(always)]
    pub fn map_type_name<'a>(&'a self, name: &'a str) -> &'a str {
        self.type_names
            .get(name)
            .map(|s| s.as_str())
            .unwrap_or_else(|| map_std_type_name(name))
    }

    /// Make a `Box<`[`EvalAltResult<ErrorMismatchDataType>`][EvalAltResult::ErrorMismatchDataType]`>`.
    #[inline(always)]
    pub(crate) fn make_type_mismatch_err<T>(&self, typ: &str, pos: Position) -> Box<EvalAltResult> {
        EvalAltResult::ErrorMismatchDataType(
            self.map_type_name(type_name::<T>()).into(),
            typ.into(),
            pos,
        )
        .into()
    }
}