Skip to content
This repository
tree: 9e5350d8b5
Fetching contributors…

Octocat-spinner-32-eaf2f5

Cannot retrieve contributors at this time

file 3043 lines (2678 sloc) 115.89 kb
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 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042
using Niecza;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Threading;
using System.Text;
using System.Net.Sockets;

namespace Niecza {
    // IForeignInterpreter is used for runtime loading of the Perl 5
    // interop module (the CLR likes us to use interfaces for inter-module
    // communication like this).
    public interface IForeignInterpreter {
        Variable Eval(string code);
    }
    // Since Mono.Posix is not available on Windows, we want to access it
    // using late binding so that Niecza will at least load on Windows.
    // Of course actually trying to use the POSIX stuff on Windows will die.
    class PosixWrapper {
        static readonly Assembly Mono_Posix;
        static readonly Type Syscall, AccessModes, FilePermissions, Stat, Signum, Stdlib;

        // copied from Mono.Posix.dll; constant values are part of the
        // stable ABI so these can't change
        public const int R_OK = 1;
        public const int W_OK = 2;
        public const int X_OK = 4;
        public const int F_OK = 8;

        // references to methods that can be directly called
        public readonly static Func<uint> getuid, geteuid, getgid, getegid;
        public readonly static Func<uint,uint,int> setreuid, setregid;
        public readonly static Func<string,int> system, rmdir;

        // methods and fields that must be used through wrappers
        static readonly MethodInfo m_stat, m_access, m_raise, m_chmod;
        static readonly FieldInfo f_dev, f_ino, f_mode, f_nlink, f_uid, f_gid,
            f_rdev, f_size, f_blksize, f_blocks, f_atime, f_mtime, f_ctime;

        // wrappers for methods that need to be wrapped, typically because
        // they take or return a data type defined in Mono.Posix
        public static int access(string pathname, int mode) {
            return (int) m_access.Invoke(null, new object[] {
                pathname, Enum.ToObject(AccessModes, mode) });
        }

        public static void raise(string sig) {
            m_raise.Invoke(null, new object[] { Enum.Parse(Signum, sig) });
        }

        public static long[] stat(string pathname) {
            object[] args = new object[] { pathname, null };
            long[] res = new long[14];
            res[0] = (int) m_stat.Invoke(null, args);

            res[1] = (long)(ulong)f_dev.GetValue(args[1]);
            res[2] = (long)(ulong)f_ino.GetValue(args[1]);
            res[3] = ((IConvertible)f_mode.GetValue(args[1])).ToInt64(null);
            res[4] = (long)(ulong)f_nlink.GetValue(args[1]);
            res[5] = (uint)f_uid.GetValue(args[1]);
            res[6] = (uint)f_gid.GetValue(args[1]);
            res[7] = (long)(ulong)f_rdev.GetValue(args[1]);
            res[8] = (long)f_size.GetValue(args[1]);
            res[9] = (long)f_blksize.GetValue(args[1]);
            res[10] = (long)f_blocks.GetValue(args[1]);
            res[11] = (long)f_atime.GetValue(args[1]);
            res[12] = (long)f_mtime.GetValue(args[1]);
            res[13] = (long)f_ctime.GetValue(args[1]);

            return res;
        }

        public static int chmod(string pathname, int mode) {
            return (int) m_chmod.Invoke(null, new object[] {
                pathname, Enum.ToObject(FilePermissions, mode) });
        }

        static PosixWrapper() {
            Mono_Posix = Assembly.Load("Mono.Posix, Version=2.0.0.0, Culture=neutral, PublicKeyToken=0738eb9f132ed756");
            Syscall = Mono_Posix.GetType("Mono.Unix.Native.Syscall", true);
            AccessModes = Mono_Posix.GetType("Mono.Unix.Native.AccessModes", true);
            Stat = Mono_Posix.GetType("Mono.Unix.Native.Stat", true);
            FilePermissions = Mono_Posix.GetType("Mono.Unix.Native.FilePermissions", true);
            Signum = Mono_Posix.GetType("Mono.Unix.Native.Signum", true);
            Stdlib = Mono_Posix.GetType("Mono.Unix.Native.Stdlib", true);

            getuid = (Func<uint>)Delegate.CreateDelegate(typeof(Func<uint>),
                    Syscall.GetMethod("getuid"));
            geteuid = (Func<uint>)Delegate.CreateDelegate(typeof(Func<uint>),
                    Syscall.GetMethod("geteuid"));
            getgid = (Func<uint>)Delegate.CreateDelegate(typeof(Func<uint>),
                    Syscall.GetMethod("getgid"));
            getegid = (Func<uint>)Delegate.CreateDelegate(typeof(Func<uint>),
                    Syscall.GetMethod("getegid"));

            setreuid = (Func<uint,uint,int>)Delegate.CreateDelegate(
                typeof(Func<uint,uint,int>), Syscall.GetMethod("setreuid"));
            setregid = (Func<uint,uint,int>)Delegate.CreateDelegate(
                typeof(Func<uint,uint,int>), Syscall.GetMethod("setregid"));

            system = (Func<string,int>)Delegate.CreateDelegate(
                typeof(Func<string,int>), Stdlib.GetMethod("system"));
            rmdir = (Func<string,int>)Delegate.CreateDelegate(
                typeof(Func<string,int>), Syscall.GetMethod("rmdir"));

            m_stat = Syscall.GetMethod("stat");
            m_access = Syscall.GetMethod("access");
            m_raise = Stdlib.GetMethod("raise", new Type[] { Signum });
            m_chmod = Syscall.GetMethod("chmod");

            f_dev = Stat.GetField("st_dev");
            f_ino = Stat.GetField("st_ino");
            f_mode = Stat.GetField("st_mode");
            f_nlink = Stat.GetField("st_nlink");
            f_uid = Stat.GetField("st_uid");
            f_gid = Stat.GetField("st_gid");
            f_rdev = Stat.GetField("st_rdev");
            f_size = Stat.GetField("st_size");
            f_blksize = Stat.GetField("st_blksize");
            f_blocks = Stat.GetField("st_blocks");
            f_atime = Stat.GetField("st_atime");
            f_mtime = Stat.GetField("st_mtime");
            f_ctime = Stat.GetField("st_ctime");
        }
    }

    // A special variable type used to implement lvalue returns from substr.
    class SubstrLValue: Variable {
        Variable backing;
        int from;
        int length;

        private SubstrLValue() {}
        public SubstrLValue(Variable backing, int from, int length) {
            this.backing = backing;
            this.from = from;
            this.length = length;
        }

        public override P6any Fetch() {
            string str = backing.Fetch().mo.mro_raw_Str.Get(backing);
            string sub = Builtins.LaxSubstring2(str, from, length);
            return sub == null ? Compartment.Top.StrMO.typeObj :
                Kernel.BoxRaw(sub,Compartment.Top.StrMO);
        }

        public override void Store(P6any v) {
            string str = backing.Fetch().mo.mro_raw_Str.Get(backing);
            int left = (from < 0) ? 0 : (from > str.Length) ? str.Length : from;
            int right = ((length > (str.Length - left)) ? (str.Length - left) :
                (length < 0) ? 0 : length) + left;
            string lfr = str.Substring(0, left);
            string mfr = v.mo.mro_raw_Str.Get(v);
            string rfr = str.Substring(right);
            backing.Store(Kernel.BoxRaw<string>(lfr + mfr + rfr, Compartment.Top.StrMO));
        }

        public override void Freeze(Niecza.Serialization.FreezeBuffer fb) {
            fb.Byte((byte)Niecza.Serialization.SerializationCode.SubstrLValue);
            fb.ObjRef(backing);
            fb.Int(from);
            fb.Int(length);
        }
        internal static object Thaw(Niecza.Serialization.ThawBuffer tb) {
            var n = new SubstrLValue();
            tb.Register(n);
            n.backing = (Variable) tb.ObjRef();
            n.from = tb.Int();
            n.length = tb.Int();
            return n;
        }
    }

[AttributeUsage(AttributeTargets.Method)]
    class CpsAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Method)]
    class ImplicitFrameAttribute : Attribute { }
[AttributeUsage(AttributeTargets.Method)]
    class ImplicitConstsAttribute : Attribute { }
}

// The special feature of this class is that Q:CgOp operations which are not
// recognized by the code generator are automatically turned into method calls
// against this class.
//
// We use the convention that lowercase methods are intended to be called from
// Perl 6 code while uppercase-starting methods are support routines.
public partial class Builtins {
    // When calling builtins, the binder is often bypassed, so we need to
    // check arguement types ourselves. This is the really simple version
    // that doesn't handle junctions, not often used.
    public static P6any NominalCheck(string name, STable mo, Variable v) {
        P6any r = v.Fetch();
        if (!r.mo.HasType(mo))
            throw new NieczaException("Nominal type check failed for " + name +
                    " needed " + mo.name + " got " + r.mo.name);
        return r;
    }

    // Type-check val against any, tracking state appropriately for
    // junctions.
    static void CheckSpecialArg(Compartment s, int ix, ref int pivot,
            ref uint rank, P6any val) {
        if (val.mo.is_any) {
            // fine as is
        } else if (val.mo.HasType(s.JunctionMO)) {
            int jtype = Kernel.UnboxAny<int>((P6any)(val as P6opaque).slots[0]) / 2;
            if ((uint)jtype < rank) {
                rank = (uint)jtype;
                pivot = ix;
            }
        } else {
            throw new NieczaException("Nominal type check failed for #" + ix +
                    " needed Any got " + val.mo.name);
        }
    }

    // This function implements the actual looping part of autothreading
    internal static Variable AutoThread(Compartment c, P6any j,
            Func<Variable,Variable> dgt) {
        P6opaque j_ = (P6opaque)j;
        P6any listObj = (P6any) j_.slots[1];
        Variable[] list = Kernel.UnboxAny<Variable[]>(listObj);
        Variable[] nlist = new Variable[list.Length];
        for (int i = 0; i < list.Length; i++) {
            nlist[i] = dgt(list[i]);
        }
        P6any newList = Kernel.BoxRaw(nlist, c.ParcelMO);
        P6opaque newJunc = new P6opaque(c.JunctionMO);
        newJunc.slots[0] = j_.slots[0];
        newJunc.slots[1] = newList;
        return newJunc;
    }

    // These three functions implement type checking and junctional
    // autothreading for signatures like (Any, Any).
    //
    // You need to pass a reference to the function in so that these may
    // call it for autothreading.
    public static Variable HandleSpecial1(Constants c, Variable av0, P6any ao0,
            Func<Constants,Variable,Variable> dgt) {
        uint jrank = uint.MaxValue;
        int jpivot = -1;

        CheckSpecialArg(c.setting, 0, ref jpivot, ref jrank, ao0);

        if (jpivot < 0) return dgt(c, av0);

        return AutoThread(c.setting, ao0, (n) => dgt(c,n));
    }
    public static Variable HandleSpecial2(Constants c, Variable av0, Variable av1,
            P6any ao0, P6any ao1, Func<Constants,Variable,Variable,Variable> dgt) {
        uint jrank = uint.MaxValue;
        int jpivot = -1;

        CheckSpecialArg(c.setting, 0, ref jpivot, ref jrank, ao0);
        CheckSpecialArg(c.setting, 1, ref jpivot, ref jrank, ao1);

        if (jpivot < 0) return dgt(c, av0, av1);

        Variable[] avs = new Variable[] { av0, av1 };
        return AutoThread(c.setting, avs[jpivot].Fetch(), delegate(Variable n) {
            avs[jpivot] = n; return dgt(c, avs[0], avs[1]); });
    }
    public static Variable HandleSpecial3(Constants c, Variable av0, Variable av1,
            Variable av2, P6any ao0, P6any ao1, P6any ao2,
            Func<Constants,Variable,Variable,Variable,Variable> dgt) {
        uint jrank = uint.MaxValue;
        int jpivot = -1;
        var s = c.setting;

        CheckSpecialArg(s, 0, ref jpivot, ref jrank, ao0);
        CheckSpecialArg(s, 1, ref jpivot, ref jrank, ao1);
        CheckSpecialArg(s, 2, ref jpivot, ref jrank, ao2);

        if (jpivot < 0) return dgt(c, av0, av1, av2);

        Variable[] avs = new Variable[] { av0, av1, av2 };
        return AutoThread(s, avs[jpivot].Fetch(), delegate(Variable n) {
            avs[jpivot] = n; return dgt(c, avs[0], avs[1], avs[2]); });
    }

    // Truncating substrings useful in some places
    public static string LaxSubstring(string str, int from) {
        if (from < 0 || from > str.Length)
            return null;
        return str.Substring(from);
    }

    public static string LaxSubstring2(string str, int from, int l) {
        if (from < 0 || from > str.Length) return null;
        if (l >= str.Length - from) l = str.Length - from;
        if (l < 0) return null;
        return str.Substring(from, l);
    }

    // Here begins the Niecza numerics system. Every CORE number is assigned
    // to one of these six groups.
    public const int NR_FIXINT = 0;
    public const int NR_BIGINT = 1;
    public const int NR_FIXRAT = 2;
    public const int NR_FATRAT = 3;
    public const int NR_FLOAT = 4;
    public const int NR_COMPLEX = 5;

    // Coerce a value to numeric and return the group code
    public static P6any GetNumber(Variable v, P6any o, out int rank) {
        if (o.mo.num_rank >= 0) {
            rank = o.mo.num_rank;
        } else {
            if (o.Does(Compartment.Top.RealMO)) {
                rank = NR_FLOAT;
                o = Kernel.RunInferior(o.InvokeMethod(Kernel.GetInferiorRoot(), "Bridge", new Variable[] { v }, null)).Fetch();
                return o;
            }
            o = o.mo.mro_Numeric.Get(v).Fetch();
            rank = o.mo.num_rank;
            if (rank < 0)
                throw new NieczaException("Not a valid primitive number " +
                        o.mo.name);
        }
        if (rank == NR_FIXINT && o is BoxObject<BigInteger>)
            rank = NR_BIGINT;
        return o;
    }

    // If a number is <= NR_COMPLEX, return it as if at NR_COMPLEX
    public static Complex PromoteToComplex(int rank, P6any vret) {
        Rat r; FatRat fr;
        if (!vret.IsDefined()) return new Complex(0,0);

        switch (rank) {
            case NR_FIXINT:
                return new Complex(Kernel.UnboxAny<int>(vret), 0);
            case NR_BIGINT:
                return new Complex((double)Kernel.UnboxAny<BigInteger>(vret), 0);
            case NR_FIXRAT:
                r = Kernel.UnboxAny<Rat>(vret);
                return new Complex((double)r.num / (double)r.den, 0);
            case NR_FATRAT:
                fr = Kernel.UnboxAny<FatRat>(vret);
                return new Complex((double)fr.num / (double)fr.den, 0);
            case NR_FLOAT:
                return new Complex(Kernel.UnboxAny<double>(vret), 0);
            case NR_COMPLEX:
            default:
                return Kernel.UnboxAny<Complex>(vret);
        }
    }

    // If a number is <= NR_FLOAT, return it as if at NR_FLOAT
    public static double PromoteToFloat(int rank, P6any vret) {
        Rat r; FatRat fr;
        if (!vret.IsDefined()) return 0;

        switch (rank) {
            case NR_FIXINT:
                return Kernel.UnboxAny<int>(vret);
            case NR_BIGINT:
                return (double)Kernel.UnboxAny<BigInteger>(vret);
            case NR_FIXRAT:
                r = Kernel.UnboxAny<Rat>(vret);
                return (double)r.num / (double)r.den;
            case NR_FATRAT:
                fr = Kernel.UnboxAny<FatRat>(vret);
                return (double)fr.num / (double)fr.den;
            case NR_FLOAT:
            default:
                return Kernel.UnboxAny<double>(vret);
        }
    }

    // If a number is <= NR_FATRAT, return it as if at NR_FATRAT
    public static FatRat PromoteToFatRat(int rank, P6any vret) {
        Rat r;
        if (!vret.IsDefined()) return new FatRat(BigInteger.Zero,BigInteger.One);

        switch (rank) {
            case NR_FIXINT:
                return new FatRat(Kernel.UnboxAny<int>(vret), BigInteger.One);
            case NR_BIGINT:
                return new FatRat(Kernel.UnboxAny<BigInteger>(vret), BigInteger.One);
            case NR_FIXRAT:
                r = Kernel.UnboxAny<Rat>(vret);
                return new FatRat(r.num, r.den);
            case NR_FATRAT:
            default:
                return Kernel.UnboxAny<FatRat>(vret);
        }
    }

    // If a number is <= NR_FIXRAT, return it as if at NR_FIXRAT
    public static Rat PromoteToFixRat(int rank, P6any vret) {
        if (!vret.IsDefined()) return new Rat(BigInteger.Zero, 1);

        switch (rank) {
            case NR_FIXINT:
                return new Rat(Kernel.UnboxAny<int>(vret), 1);
            case NR_BIGINT:
                return new Rat(Kernel.UnboxAny<BigInteger>(vret), 1);
            case NR_FIXRAT:
            default:
                return Kernel.UnboxAny<Rat>(vret);
        }
    }

    // If a number is <= NR_BIGINT, return it as if at NR_BIGINT
    public static BigInteger PromoteToBigInt(int rank, P6any vret) {
        if (!vret.IsDefined()) return BigInteger.Zero;

        switch (rank) {
            case NR_FIXINT:
                return Kernel.UnboxAny<int>(vret);
            case NR_BIGINT:
            default:
                return Kernel.UnboxAny<BigInteger>(vret);
        }
    }

    // If a number is <= NR_FIXINT, return it as if at NR_FIXINT
    public static int PromoteToFixInt(int rank, P6any vret) {
        if (!vret.IsDefined()) return 0;
        return Kernel.UnboxAny<int>(vret);
    }

    // Produce a number from an int
    public static Variable MakeInt(int v) {
        return Kernel.BoxAnyMO<int>(v, Compartment.Top.IntMO);
    }

    public static Variable MakeInt(BigInteger v) {
        int vs;
        if (v.AsInt32(out vs)) return Kernel.BoxAnyMO<int>(vs, Compartment.Top.IntMO);
        else return Kernel.BoxAnyMO<BigInteger>(v, Compartment.Top.IntMO);
    }

    public static Variable MakeInt(long v) {
        if (v <= (long)int.MaxValue && v >= (long)int.MinValue)
            return Kernel.BoxAnyMO<int>((int)v, Compartment.Top.IntMO);
        else return Kernel.BoxAnyMO<BigInteger>(v, Compartment.Top.IntMO);
    }

    // Coerce a number to a real rational value - note that this loses
    // the "inexact" annotation carried by Nums
    public static void GetAsRational(Variable v,
            out BigInteger num, out BigInteger den) {
        int rk;
        P6any n = GetNumber(v, v.Fetch(), out rk);

        if (rk == NR_COMPLEX || rk == NR_FLOAT) {
            double dbl = 0;
            if (rk == NR_COMPLEX) {
                Complex c = Kernel.UnboxAny<Complex>(n);
                if (c.im != 0)
                    throw new NieczaException("Complex cannot be used here");
                dbl = c.re;
            } else {
                dbl = Kernel.UnboxAny<double>(n);
            }
            ulong bits = (ulong)BitConverter.DoubleToInt64Bits(dbl);
            num = (bits & ((1UL << 52) - 1)) + (1UL << 52);
            den = (1UL << 52);
            if ((bits & (1UL << 63)) != 0) num = -num;
            int power = ((int)((bits >> 52) & 0x7FF)) - 0x3FF;
            if (power > 0) num <<= power;
            else den <<= -power;
            SimplifyFrac(ref num, ref den);
        }
        else if (rk == NR_FATRAT) {
            FatRat r = Kernel.UnboxAny<FatRat>(n);
            num = r.num; den = r.den;
        }
        else if (rk == NR_FIXRAT) {
            Rat r = Kernel.UnboxAny<Rat>(n);
            num = r.num; den = r.den;
        }
        else if (rk == NR_BIGINT) {
            num = Kernel.UnboxAny<BigInteger>(n); den = BigInteger.One;
        }
        else {
            num = Kernel.UnboxAny<int>(n); den = BigInteger.One;
        }
    }

    // Coerce a real number to an integer, truncating towards 0
    public static bool GetAsInteger(Variable v, out int small,
            out BigInteger big) {
        int rk;
        P6any n = GetNumber(v, v.Fetch(), out rk);
        small = 0;

        if (rk == NR_COMPLEX || rk == NR_FLOAT) {
            double dbl = 0;
            if (rk == NR_COMPLEX) {
                Complex c = Kernel.UnboxAny<Complex>(n);
                if (c.im != 0)
                    throw new NieczaException("Complex cannot be used here");
                dbl = c.re;
            } else {
                dbl = Kernel.UnboxAny<double>(n);
            }
            ulong bits = (ulong)BitConverter.DoubleToInt64Bits(dbl);
            big = (bits & ((1UL << 52) - 1)) + (1UL << 52);
            int power = ((int)((bits >> 52) & 0x7FF)) - 0x433;
            if (power > 0) big <<= power;
            else big >>= -power;
            if ((bits & (1UL << 63)) != 0) big = -big;
        }
        else if (rk == NR_FATRAT) {
            FatRat r = Kernel.UnboxAny<FatRat>(n);
            big = r.num / r.den;
        }
        else if (rk == NR_FIXRAT) {
            Rat r = Kernel.UnboxAny<Rat>(n);
            big = r.num / r.den;
        }
        else if (rk == NR_BIGINT) {
            big = Kernel.UnboxAny<BigInteger>(n);
        }
        else {
            big = BigInteger.Zero; small = Kernel.UnboxAny<int>(n); return false;
        }
        return true;
    }

    public static void SimplifyFrac(ref BigInteger num, ref BigInteger den) {
        if (den.Sign < 0) {
            den = -den;
            num = -num;
        }
        if (num.Sign == 0) {
            den = BigInteger.One;
        }
        if (num.Sign != 0 && den.Sign != 0) {
            BigInteger g = BigInteger.GreatestCommonDivisor(num, den);
            if (g != BigInteger.One) {
                num /= g;
                den /= g;
            }
        }
    }

    public static double RatToFloat(BigInteger num, BigInteger den) {
        // TODO: avoid overflow
        return (double) num / (double) den;
    }

    public static Variable MakeFixRat(BigInteger num, BigInteger den) {
        ulong sden;
        SimplifyFrac(ref num, ref den);
        if (den.AsUInt64(out sden) && sden != 0)
            return Kernel.BoxAnyMO<Rat>(new Rat(num, sden), Compartment.Top.RatMO);
        return MakeFloat(RatToFloat(num, den));
    }

    public static Variable MakeFatRat(BigInteger num, BigInteger den) {
        SimplifyFrac(ref num, ref den);
        if (den.Sign != 0)
            return Kernel.BoxAnyMO<FatRat>(new FatRat(num, den), Compartment.Top.FatRatMO);
        return MakeFloat(den.Sign * double.PositiveInfinity);
    }

    public static Variable MakeFloat(double val) {
        return Kernel.BoxAnyMO<double>(val, Compartment.Top.NumMO);
    }

    public static Variable MakeComplex(double re, double im) {
        return Kernel.BoxAnyMO<Complex>(new Complex(re, im), Compartment.Top.ComplexMO);
    }

    public static Variable MakeStr(string str) {
        return Kernel.BoxAnyMO(str, Compartment.Top.StrMO);
    }

    public static Variable MakeComplex(Complex z) {
        return Kernel.BoxAnyMO<Complex>(z, Compartment.Top.ComplexMO);
    }

    public static Variable MakeParcel(params Variable[] bits) {
        return Kernel.NewRWListVar(Kernel.BoxRaw(bits, Compartment.Top.ParcelMO));
    }

    public static Variable InvokeSub(P6any obj, params Variable[] pos) {
        return Kernel.RunInferior(obj.Invoke(Kernel.GetInferiorRoot(), pos,
                    null));
    }

    public static Variable InvokeMethod(string name, params Variable[] pos) {
        return Kernel.RunInferior(pos[0].Fetch().InvokeMethod(
            Kernel.GetInferiorRoot(), name, pos, null));
    }

    public static bool ToBool(Variable v) {
        return v.Fetch().mo.mro_raw_Bool.Get(v);
    }
    public static string ToStr(Variable v) {
        return v.Fetch().mo.mro_raw_Str.Get(v);
    }
    public static double ToNum(Variable v) {
        return v.Fetch().mo.mro_raw_Numeric.Get(v);
    }

    // Most of the following functions get used for inline calls, so they
    // must use HandleSpecialX
    static readonly Func<Constants,Variable,Variable,Variable> numeq_d = numeq;
[ImplicitConsts] public static Variable numeq(Constants c, Variable v1, Variable v2) {
        return numcompare(c, v1, v2, O_IS_EQUAL | O_COMPLEX_OK, numeq_d);
    }

[ImplicitConsts] public static Variable numne(Constants c, Variable v1, Variable v2) {
        // NOTE that junctionalization uses == ! See check in numcompare
        return numcompare(c, v1, v2, O_IS_LESS | O_IS_GREATER | O_IS_UNORD |
                O_COMPLEX_OK, numeq_d);
    }

    static readonly Func<Constants,Variable,Variable,Variable> numlt_d = numlt;
[ImplicitConsts] public static Variable numlt(Constants c, Variable v1, Variable v2) {
        return numcompare(c, v1, v2, O_IS_LESS, numlt_d);
    }

    static readonly Func<Constants,Variable,Variable,Variable> numle_d = numle;
[ImplicitConsts] public static Variable numle(Constants c, Variable v1, Variable v2) {
        return numcompare(c, v1, v2, O_IS_EQUAL | O_IS_LESS, numle_d);
    }

    static readonly Func<Constants,Variable,Variable,Variable> numgt_d = numgt;
[ImplicitConsts] public static Variable numgt(Constants c, Variable v1, Variable v2) {
        return numcompare(c, v1, v2, O_IS_GREATER, numgt_d);
    }

    static readonly Func<Constants,Variable,Variable,Variable> numge_d = numge;
[ImplicitConsts] public static Variable numge(Constants c, Variable v1, Variable v2) {
        return numcompare(c, v1, v2, O_IS_GREATER | O_IS_EQUAL, numge_d);
    }

    internal static Variable strcompare(Constants c, Variable v1, Variable v2,
            int mask, Func<Constants,Variable,Variable,Variable> d) {
        P6any o1 = v1.Fetch(); P6any o2 = v2.Fetch();
        var s = c.setting;
        if (!(o1.mo.is_any && o2.mo.is_any)) {
            Variable jr = HandleSpecial2(c, v1, v2, o1, o2, d);
            // treat $x != $y as !($x == $y)
            if (mask == (O_IS_GREATER | O_IS_LESS | O_IS_UNORD))
                return jr.Fetch().mo.mro_raw_Bool.Get(jr) ? s.FalseV : s.TrueV;
            return jr;
        }
        int diff = string.CompareOrdinal(o1.mo.mro_raw_Str.Get(v1),
                o2.mo.mro_raw_Str.Get(v2));
        int mcom = (diff < 0) ? O_IS_LESS : (diff > 0) ? O_IS_GREATER :
            O_IS_EQUAL;
        return ((mask & mcom) != 0) ? s.TrueV : s.FalseV;
    }

    static readonly Func<Constants,Variable,Variable,Variable> streq_d = streq;
[ImplicitConsts] public static Variable streq(Constants c, Variable v1, Variable v2) {
        return strcompare(c, v1, v2, O_IS_EQUAL, streq_d);
    }

[ImplicitConsts] public static Variable strne(Constants c, Variable v1, Variable v2) {
        return strcompare(c, v1, v2, O_IS_LESS | O_IS_GREATER | O_IS_UNORD, streq_d);
    }

    static readonly Func<Constants,Variable,Variable,Variable> strlt_d = strlt;
[ImplicitConsts] public static Variable strlt(Constants c, Variable v1, Variable v2) {
        return strcompare(c, v1, v2, O_IS_LESS, strlt_d);
    }

    static readonly Func<Constants,Variable,Variable,Variable> strle_d = strle;
[ImplicitConsts] public static Variable strle(Constants c, Variable v1, Variable v2) {
        return strcompare(c, v1, v2, O_IS_EQUAL | O_IS_LESS, strle_d);
    }

    static readonly Func<Constants,Variable,Variable,Variable> strgt_d = strgt;
[ImplicitConsts] public static Variable strgt(Constants c, Variable v1, Variable v2) {
        return strcompare(c, v1, v2, O_IS_GREATER, strgt_d);
    }

    static readonly Func<Constants,Variable,Variable,Variable> strge_d = strge;
[ImplicitConsts] public static Variable strge(Constants c, Variable v1, Variable v2) {
        return strcompare(c, v1, v2, O_IS_GREATER | O_IS_EQUAL, strge_d);
    }

    private static int substr_pos(Compartment s, Variable v1, Variable v2) {
        P6any o1 = v1.Fetch(), o2 = v2.Fetch();
        int r2;
        if (o2.Does(s.CodeMO)) {
            string s1 = o1.mo.mro_raw_Str.Get(v1);
            Variable no2 = Kernel.RunInferior(o2.Invoke(
                Kernel.GetInferiorRoot(), new Variable[] {
                    MakeInt(s1.Length) }, null));
            r2 = (int)no2.Fetch().mo.mro_raw_Numeric.Get(no2);
        } else {
            r2 = (int)o2.mo.mro_raw_Numeric.Get(v2);
        }
        return r2;
    }

    private static int substr_len(Compartment s, Variable v1, int pos, Variable v3) {
        P6any o1 = v1.Fetch(), o3 = v3.Fetch();
        int r3;
        if (o3.Does(s.CodeMO)) {
            string s1 = o1.mo.mro_raw_Str.Get(v1);
            Variable no3 = Kernel.RunInferior(o3.Invoke(
                Kernel.GetInferiorRoot(), new Variable[] {
                    MakeInt(s1.Length) }, null));
            r3 = (int)no3.Fetch().mo.mro_raw_Numeric.Get(no3) - pos;
        } else {
            r3 = (int)o3.mo.mro_raw_Numeric.Get(v3);
        }
        return r3;
    }

    static readonly Func<Constants,Variable,Variable,Variable,Variable> substr3_d = substr3;
[ImplicitConsts] public static Variable substr3(Constants c, Variable v1, Variable v2, Variable v3) {
        P6any o1 = v1.Fetch(), o2 = v2.Fetch(), o3 = v3.Fetch();
        if (!(o1.mo.is_any && o2.mo.is_any && o3.mo.is_any))
            return HandleSpecial3(c, v1,v2,v3, o1,o2,o3, substr3_d);

        int pos = substr_pos(c.setting, v1, v2);
        int len = substr_len(c.setting, v1, pos, v3);
        return new SubstrLValue(v1, pos, len);
    }

    static readonly Func<Constants,Variable,Variable,Variable,Variable> substr_ro3_d = substr_ro3;
[ImplicitConsts] public static Variable substr_ro3(Constants c, Variable v1, Variable v2, Variable v3) {
        P6any o1 = v1.Fetch(), o2 = v2.Fetch(), o3 = v3.Fetch();
        if (!(o1.mo.is_any && o2.mo.is_any && o3.mo.is_any))
            return HandleSpecial3(c, v1,v2,v3, o1,o2,o3, substr_ro3_d);

        int pos = substr_pos(c.setting, v1, v2);
        int len = substr_len(c.setting, v1, pos, v3);
        string str = v1.Fetch().mo.mro_raw_Str.Get(v1);
        string sub = Builtins.LaxSubstring2(str, pos, len);
        return sub == null ? c.setting.StrMO.typeObj : MakeStr(sub);
    }

    static readonly Func<Constants,Variable,Variable,Variable> plus_d = plus;
[ImplicitConsts] public static Variable plus(Constants c, Variable a1, Variable a2) {
        int r1, r2;
        P6any o1 = a1.Fetch(), o2 = a2.Fetch();
        if (!(o1.mo.is_any && o2.mo.is_any))
            return HandleSpecial2(c, a1, a2, o1, o2, plus_d);
        P6any n1 = GetNumber(a1, o1, out r1);
        P6any n2 = GetNumber(a2, o2, out r2);

        if (r1 == NR_COMPLEX || r2 == NR_COMPLEX) {
            Complex v1 = PromoteToComplex(r1, n1);
            Complex v2 = PromoteToComplex(r2, n2);
            return MakeComplex(v1.re + v2.re, v1.im + v2.im);
        }
        if (r1 == NR_FLOAT || r2 == NR_FLOAT) {
            return MakeFloat(PromoteToFloat(r1, n1) + PromoteToFloat(r2, n2));
        }
        if (r1 == NR_FATRAT || r2 == NR_FATRAT) {
            FatRat v1 = PromoteToFatRat(r1, n1);
            FatRat v2 = PromoteToFatRat(r2, n2);

            return MakeFatRat(v1.num*v2.den + v2.num*v1.den, v1.den*v2.den);
        }
        if (r1 == NR_FIXRAT || r2 == NR_FIXRAT) {
            Rat v1 = PromoteToFixRat(r1, n1);
            Rat v2 = PromoteToFixRat(r2, n2);

            return MakeFixRat(v1.num*v2.den + v2.num*v1.den, ((BigInteger)v1.den)*v2.den);
        }
        if (r1 == NR_BIGINT || r2 == NR_BIGINT) {
            return MakeInt(PromoteToBigInt(r1, n1) + PromoteToBigInt(r2, n2));
        }
        return MakeInt((long)PromoteToFixInt(r1, n1) +
                (long)PromoteToFixInt(r2, n2));
    }

    static readonly Func<Constants,Variable,Variable,Variable> minus_d = minus;
[ImplicitConsts] public static Variable minus(Constants c, Variable a1, Variable a2) {
        int r1, r2;
        P6any o1 = a1.Fetch(), o2 = a2.Fetch();
        if (!(o1.mo.is_any && o2.mo.is_any))
            return HandleSpecial2(c, a1,a2, o1,o2, minus_d);
        P6any n1 = GetNumber(a1, o1, out r1);
        P6any n2 = GetNumber(a2, o2, out r2);

        if (r1 == NR_COMPLEX || r2 == NR_COMPLEX) {
            Complex v1 = PromoteToComplex(r1, n1);
            Complex v2 = PromoteToComplex(r2, n2);
            return MakeComplex(v1.re - v2.re, v1.im - v2.im);
        }
        if (r1 == NR_FLOAT || r2 == NR_FLOAT) {
            return MakeFloat(PromoteToFloat(r1, n1) - PromoteToFloat(r2, n2));
        }
        if (r1 == NR_FATRAT || r2 == NR_FATRAT) {
            FatRat v1 = PromoteToFatRat(r1, n1);
            FatRat v2 = PromoteToFatRat(r2, n2);

            return MakeFatRat(v1.num*v2.den - v2.num*v1.den, v1.den*v2.den);
        }
        if (r1 == NR_FIXRAT || r2 == NR_FIXRAT) {
            Rat v1 = PromoteToFixRat(r1, n1);
            Rat v2 = PromoteToFixRat(r2, n2);

            return MakeFixRat(v1.num*v2.den - v2.num*v1.den, ((BigInteger)v1.den)*v2.den);
        }
        if (r1 == NR_BIGINT || r2 == NR_BIGINT) {
            return MakeInt(PromoteToBigInt(r1, n1) - PromoteToBigInt(r2, n2));
        }
        return MakeInt((long)PromoteToFixInt(r1, n1) -
                (long)PromoteToFixInt(r2, n2));
    }

    // Untested and probably unusable in the near term
    public static BigInteger big_pow(BigInteger v1, BigInteger v2) {
        int CHUNK = 2000000000;
        int margin = (int) (v2 % (BigInteger) CHUNK);
        BigInteger number_chunks = (v2 - margin) / CHUNK;
        BigInteger margin_pow = BigInteger.Pow(v1, margin);
        BigInteger result = margin_pow;
        if (number_chunks > 0) {
            BigInteger chunk_pow = margin_pow * BigInteger.Pow(v1, CHUNK - margin);
            for (BigInteger i = 0; i < number_chunks; i++) {
                result *= chunk_pow;
            }
        }
        return result;
    }

    // Unifies the MakeFixRat logic and tries to avoid a huge computation
    // that will just be rounded away.
    // Invariant: pow >= 0
    static Variable RatPow(BigInteger num, BigInteger den, BigInteger pow) {
        if (den == -BigInteger.One) { den = BigInteger.One; num = -num; }

        if (den == BigInteger.One) {
            // den won't be getting any bigger
            return MakeFixRat(big_pow(num, pow), 1);
        }
        // den >= 2
        if (pow >= 64) {
            // Overflow is inevitable.
            return MakeFloat(Math.Pow(RatToFloat(num, den), (double)pow));
        }
        // we might consider detecting smaller overflows, but the penalty
        // of $int ** 63 is not _that_ huge.

        return MakeFixRat(big_pow(num, pow), big_pow(den, pow));
    }

    static readonly Func<Constants,Variable,Variable,Variable> pow_d = pow;
[ImplicitConsts] public static Variable pow(Constants c, Variable a1, Variable a2) {
        int r1, r2;
        P6any o1 = a1.Fetch(), o2 = a2.Fetch();
        if (!(o1.mo.is_any && o2.mo.is_any))
            return HandleSpecial2(c, a1, a2, o1, o2, pow_d);
        P6any n1 = GetNumber(a1, o1, out r1);
        P6any n2 = GetNumber(a2, o2, out r2);

        if (r1 == NR_COMPLEX || r2 == NR_COMPLEX) {
            Complex c1 = PromoteToComplex(r1, n1);
            Complex c2 = PromoteToComplex(r2, n2);
            double r = Math.Sqrt(c1.re * c1.re + c1.im * c1.im);
            if (r == 0.0) {
                return MakeComplex(0.0, 0.0);
            }
            double theta = Math.Atan2(c1.im, c1.re);
            // Log z = ln r + iθ
            // ($a.log * $b).exp;
            double lp_re = Math.Log(r)*c2.re - theta*c2.im;
            double lp_im = theta*c2.re + Math.Log(r)*c2.im;
            return MakeComplex(Math.Exp(lp_re) * Math.Cos(lp_im),
                               Math.Exp(lp_re) * Math.Sin(lp_im));
        }

        if (r1 == NR_FLOAT || (r2 != NR_BIGINT && r2 != NR_FIXINT)) {
            return MakeFloat(Math.Pow(PromoteToFloat(r1, n1), PromoteToFloat(r2, n2)));
        }

        BigInteger v2 = PromoteToBigInt(r2, n2);
        if (v2 >= 0) {
            if (r1 == NR_FIXINT || r1 == NR_BIGINT) {
                return MakeInt(big_pow(PromoteToBigInt(r1, n1), v2));
            }
            if (r1 == NR_FATRAT) {
                FatRat v1 = PromoteToFatRat(r1, n1);
                return MakeFatRat(big_pow(v1.num, v2), big_pow(v1.den, v2));
            }
            if (r1 == NR_FIXRAT) {
                Rat v1 = PromoteToFixRat(r1, n1);
                return RatPow(v1.num, v1.den, v2);
            }
        } else {
            if (r1 == NR_FIXINT || r1 == NR_BIGINT) {
                return RatPow(1, PromoteToBigInt(r1, n1), -v2);
            }
            if (r1 == NR_FATRAT) {
                FatRat v1 = PromoteToFatRat(r1, n1);
                return MakeFatRat(big_pow(v1.den, -v2), big_pow(v1.num, -v2));
            }
            if (r1 == NR_FIXRAT) {
                Rat v1 = PromoteToFixRat(r1, n1);
                return RatPow(v1.den, v1.num, -v2);
            }
        }

        return MakeFloat(Math.Pow(PromoteToFloat(r1, n1), PromoteToFloat(r2, n2)));
    }

    static readonly Func<Constants,Variable,Variable> negate_d = negate;
[ImplicitConsts] public static Variable negate(Constants c, Variable a1) {
        P6any o1 = a1.Fetch();
        int r1;
        if (!o1.mo.is_any)
            return HandleSpecial1(c, a1,o1, negate_d);
        P6any n1 = GetNumber(a1, o1, out r1);

        if (r1 == NR_COMPLEX) {
            Complex v1 = PromoteToComplex(r1, n1);
            return MakeComplex(-v1.re, -v1.im);
        }
        if (r1 == NR_FLOAT) {
            return MakeFloat(-PromoteToFloat(r1, n1));
        }
        if (r1 == NR_FATRAT) {
            FatRat v1 = PromoteToFatRat(r1, n1);
            return MakeFatRat(-v1.num, v1.den);
        }
        if (r1 == NR_FIXRAT) {
            Rat v1 = PromoteToFixRat(r1, n1);
            return MakeFixRat(-v1.num, v1.den);
        }
        if (r1 == NR_BIGINT) {
            return MakeInt(-PromoteToBigInt(r1, n1));
        }
        return MakeInt(-(long)PromoteToFixInt(r1, n1));
    }

    static readonly Func<Constants,Variable,Variable> abs_d = abs;
[ImplicitConsts] public static Variable abs(Constants c, Variable a1) {
        P6any o1 = a1.Fetch();
        int r1;
        if (!o1.mo.is_any)
            return HandleSpecial1(c, a1,o1, abs_d);
        P6any n1 = GetNumber(a1, o1, out r1);

        if (r1 == NR_COMPLEX) {
            Complex v1 = PromoteToComplex(r1, n1);
            return MakeFloat(Math.Sqrt(v1.re * v1.re + v1.im * v1.im));
        }
        if (r1 == NR_FLOAT) {
            double v1 = PromoteToFloat(r1, n1);
            return MakeFloat(v1 < 0 ? -v1 : v1);
        }
        if (r1 == NR_FATRAT) {
            FatRat v1 = PromoteToFatRat(r1, n1);
            return v1.num < 0 ? MakeFatRat(-v1.num, v1.den) : MakeFatRat(v1.num, v1.den);
        }
        if (r1 == NR_FIXRAT) {
            Rat v1 = PromoteToFixRat(r1, n1);
            return v1.num < 0 ? MakeFixRat(-v1.num, v1.den) : MakeFixRat(v1.num, v1.den);
        }
        if (r1 == NR_BIGINT) {
            BigInteger v1 = PromoteToBigInt(r1, n1);
            return MakeInt(v1 < 0 ? -v1 : v1);
        }
        {
            long v1 = PromoteToFixInt(r1, n1);
            return MakeInt(v1 < 0 ? -v1 : v1);
        }
    }

    static readonly Func<Constants,Variable,Variable> ln_d = ln;
[ImplicitConsts] public static Variable ln(Constants c, Variable a1) {
        P6any o1 = a1.Fetch();
        int r1;
        if (!o1.mo.is_any)
            return HandleSpecial1(c, a1,o1, ln_d);
        P6any n1 = GetNumber(a1, o1, out r1);

        if (r1 == NR_COMPLEX) {
            // Log z = ln r + iθ
            Complex v1 = PromoteToComplex(r1, n1);
            return MakeComplex(Math.Log(Math.Sqrt(v1.re * v1.re + v1.im * v1.im)),
                               Math.Atan2(v1.im, v1.re));
        }
        if (r1 == NR_BIGINT) {
            BigInteger v1 = PromoteToBigInt(r1, n1);
            return MakeFloat(BigInteger.Log(v1));
        }
        {
            double v1 = PromoteToFloat(r1, n1);
            return MakeFloat(Math.Log(v1));
        }
    }

    static readonly Func<Constants,Variable,Variable> exp_d = exp;
[ImplicitConsts] public static Variable exp(Constants c, Variable a1) {
        P6any o1 = a1.Fetch();
        int r1;
        if (!o1.mo.is_any)
            return HandleSpecial1(c, a1,o1, exp_d);
        P6any n1 = GetNumber(a1, o1, out r1);

        if (r1 == NR_COMPLEX) {
            Complex v1 = PromoteToComplex(r1, n1);
            return MakeComplex(Math.Exp(v1.re) * Math.Cos(v1.im),
                               Math.Exp(v1.re) * Math.Sin(v1.im));
        }
        {
            double v1 = PromoteToFloat(r1, n1);
            return MakeFloat(Math.Exp(v1));
        }
    }

    static readonly Func<Constants,Variable,Variable,Variable> atan2_d = atan2;
[ImplicitConsts] public static Variable atan2(Constants c, Variable a1, Variable a2) {
        P6any o1 = a1.Fetch();
        P6any o2 = a2.Fetch();
        if (!o1.mo.is_any || !o2.mo.is_any)
            return HandleSpecial2(c, a1,a2,o1,o2, atan2_d);
        int r1;
        P6any n1 = GetNumber(a1, o1, out r1);
        int r2;
        P6any n2 = GetNumber(a2, o2, out r2);

        {
            double v1 = PromoteToFloat(r1, n1);
            double v2 = PromoteToFloat(r2, n2);
            return MakeFloat(Math.Atan2(v1, v2));
        }
    }

    static readonly Func<Constants,Variable,Variable> floor_d = floor;
[ImplicitConsts] public static Variable floor(Constants c, Variable a1) {
        P6any o1 = a1.Fetch();
        int r1;
        if (!o1.mo.is_any)
            return HandleSpecial1(c, a1,o1, floor_d);
        P6any n1 = GetNumber(a1, o1, out r1);

        if (r1 == NR_COMPLEX) {
            throw new NieczaException("floor is only defined for Reals, you have a Complex()");
        }
        if (r1 == NR_FLOAT) {
            double v1 = PromoteToFloat(r1, n1);
            if (Double.IsNaN(v1) || Double.IsNegativeInfinity(v1) || Double.IsPositiveInfinity(v1)) {
                return MakeFloat(v1);
            }
            ulong bits = (ulong)BitConverter.DoubleToInt64Bits(v1);
            BigInteger big = (bits & ((1UL << 52) - 1)) + (1UL << 52);
            int power = ((int)((bits >> 52) & 0x7FF)) - 0x433;
            // note: >>= has flooring semantics for signed values
            if ((bits & (1UL << 63)) != 0) big = -big;
            if (power > 0) big <<= power;
            else big >>= -power;
            return MakeInt(big);
        }
        if (r1 == NR_FATRAT) {
            FatRat v1 = PromoteToFatRat(r1, n1);
            BigInteger rem;
            BigInteger red = BigInteger.DivRem(v1.num, v1.den, out rem);
            if (rem.Sign != 0 && v1.num.Sign < 0)
                return MakeInt(red - 1);
            else
                return MakeInt(red);
        }
        if (r1 == NR_FIXRAT) {
            Rat v1 = PromoteToFixRat(r1, n1);
            BigInteger rem;
            BigInteger red = BigInteger.DivRem(v1.num, v1.den, out rem);
            if (rem.Sign != 0 && v1.num.Sign < 0)
                return MakeInt(red - 1);
            else
                return MakeInt(red);
        }
        return n1;
    }

    static readonly Func<Constants,Variable,Variable,Variable> gcd_d = gcd;
[ImplicitConsts] public static Variable gcd(Constants c, Variable a1, Variable a2) {
        int r1, r2;
        P6any o1 = a1.Fetch(), o2 = a2.Fetch();
        if (!(o1.mo.is_any && o2.mo.is_any))
            return HandleSpecial2(c, a1,a2, o1,o2, gcd_d);
        P6any n1 = GetNumber(a1, o1, out r1);
        P6any n2 = GetNumber(a2, o2, out r2);

        // SHOULD: optimize for the case of two small sized Ints
        return MakeInt(BigInteger.GreatestCommonDivisor(PromoteToBigInt(r1, n1), PromoteToBigInt(r2, n2)));
    }

    static readonly Func<Constants,Variable,Variable,Variable,Variable> expmod_d = expmod;
[ImplicitConsts] public static Variable expmod(Constants c, Variable a1, Variable a2, Variable a3) {
        P6any o1 = a1.Fetch();
        P6any o2 = a2.Fetch();
        P6any o3 = a3.Fetch();
        if (!o1.mo.is_any || !o2.mo.is_any || !o3.mo.is_any)
            return HandleSpecial3(c, a1,a2,a3,o1,o2,o3, expmod_d);
        int r1, r2, r3;
        P6any n1 = GetNumber(a1, o1, out r1);
        P6any n2 = GetNumber(a2, o2, out r2);
        P6any n3 = GetNumber(a3, o3, out r3);

        return MakeInt(BigInteger.ModPow(PromoteToBigInt(r1, n1),
                                         PromoteToBigInt(r2, n2),
                                         PromoteToBigInt(r3, n3)));
    }

    static readonly Func<Constants,Variable,Variable> bigrand_d = bigrand;
[ImplicitConsts] public static Variable bigrand(Constants c, Variable a1) {
        // Assumes a1 is positive!
        int r1;
        P6any o1 = a1.Fetch();
        if (!o1.mo.is_any)
            return HandleSpecial1(c, a1, o1, bigrand_d);
        P6any n1 = GetNumber(a1, o1, out r1);

        BigInteger top = PromoteToBigInt(r1, n1);
        int bits = (int) Math.Ceiling(BigInteger.Log(top, 2));
        int bytes = bits / 8 + 1;
        byte mask = (byte) ((1 << (bits % 8)) - 1);

        byte[] b = new byte[bytes + 1];
        while (true) {
            lock (rng_lock) { rng.NextBytes(b); }
            b[bytes] = 0;
            b[bytes - 1] &= mask;
            BigInteger candidate = new BigInteger (b);
            if (candidate < top)
                return MakeInt(candidate);
        }
    }

[TrueGlobal] static IForeignInterpreter p5_interpreter;
    public static Variable eval_perl5(Variable v) {
        P6any o1 = v.Fetch();
        string r = o1.mo.mro_raw_Str.Get(v);

        if (p5_interpreter == null) {
            System.Reflection.Assembly a = System.Reflection.Assembly.Load("Perl5Interpreter");
            p5_interpreter = (IForeignInterpreter) a.CreateInstance("Perl5Interpreter");
        }
        return p5_interpreter.Eval(r);
    }

    // we don't need to do nominal checking stuff here because this
    // is in a method, never inlined, and as such the binder had to
    // already have been called.
    public static Variable complex_new(Variable a1, Variable a2) {
        double d1 = a1.Fetch().mo.mro_raw_Numeric.Get(a1);
        double d2 = a2.Fetch().mo.mro_raw_Numeric.Get(a2);
        return MakeComplex(d1,d2);
    }
    public static Variable complex_re(Variable a1) {
        return MakeFloat(Kernel.UnboxAny<Complex>(a1.Fetch()).re);
    }
    public static Variable complex_im(Variable a1) {
        return MakeFloat(Kernel.UnboxAny<Complex>(a1.Fetch()).im);
    }
    public static Variable rat_nu(Variable a1) {
        return MakeInt(Kernel.UnboxAny<Rat>(a1.Fetch()).num);
    }
    public static Variable rat_de(Variable a1) {
        return MakeInt(Kernel.UnboxAny<Rat>(a1.Fetch()).den);
    }
    public static Variable fatrat_nu(Variable a1) {
        return MakeInt(Kernel.UnboxAny<FatRat>(a1.Fetch()).num);
    }
    public static Variable fatrat_de(Variable a1) {
        return MakeInt(Kernel.UnboxAny<FatRat>(a1.Fetch()).den);
    }

    const int O_IS_GREATER = 1;
    const int O_IS_LESS = 2;
    const int O_IS_EQUAL = 4;
    const int O_IS_UNORD = 8;
    const int O_COMPLEX_OK = 16;
    public static Variable numcompare(Constants c, Variable a1, Variable a2, int mask,
            Func<Constants,Variable,Variable,Variable> dl) {
        int r1, r2, res=0;
        var s = c.setting;
        P6any o1 = a1.Fetch(), o2 = a2.Fetch();
        if (!(o1.mo.is_any && o2.mo.is_any)) {
            Variable jr = HandleSpecial2(c, a1, a2, o1, o2, dl);
            // treat $x != $y as !($x == $y)
            if (mask == (O_IS_GREATER | O_IS_LESS | O_IS_UNORD | O_COMPLEX_OK))
                return jr.Fetch().mo.mro_raw_Bool.Get(jr) ? s.FalseV : s.TrueV;
            return jr;
        }
        P6any n1 = GetNumber(a1, o1, out r1);
        P6any n2 = GetNumber(a2, o2, out r2);

        if (r1 == NR_COMPLEX || r2 == NR_COMPLEX) {
            if ((mask & O_COMPLEX_OK) == 0)
                throw new NieczaException("Complex numbers are not arithmetically ordered; use cmp if you want an arbitrary order");
            Complex v1 = PromoteToComplex(r1, n1);
            Complex v2 = PromoteToComplex(r2, n2);
            if (double.IsNaN(v1.re) || double.IsNaN(v1.im) ||
                    double.IsNaN(v2.re) || double.IsNaN(v2.im))
                res = O_IS_UNORD;
            else if (v1.re != v2.re)
                res = v1.re > v2.re ? O_IS_GREATER : O_IS_LESS;
            else
                res = v1.im > v2.im ? O_IS_GREATER : v1.im < v2.im ? O_IS_LESS : O_IS_EQUAL;
        }
        else if (r1 == NR_FLOAT || r2 == NR_FLOAT) {
            double d1 = PromoteToFloat(r1, n1);
            double d2 = PromoteToFloat(r2, n2);
            if (double.IsNaN(d1) || double.IsNaN(d2)) res = O_IS_UNORD;
            else res =d1 > d2 ? O_IS_GREATER : d1 < d2 ? O_IS_LESS : O_IS_EQUAL;
        }
        else if (r1 == NR_FATRAT || r2 == NR_FATRAT) {
            FatRat v1 = PromoteToFatRat(r1, n1);
            FatRat v2 = PromoteToFatRat(r2, n2);

            r1 = BigInteger.Compare(v1.num*v2.den, v2.num*v1.den);
        }
        else if (r1 == NR_FIXRAT || r2 == NR_FIXRAT) {
            Rat v1 = PromoteToFixRat(r1, n1);
            Rat v2 = PromoteToFixRat(r2, n2);

            r1 = BigInteger.Compare(v1.num*v2.den, v2.num*v1.den);
        }
        else if (r1 == NR_BIGINT || r2 == NR_BIGINT) {
            r1 = BigInteger.Compare(PromoteToBigInt(r1, n1),
                    PromoteToBigInt(r2, n2));
        }
        else
            r1 = PromoteToFixInt(r1, n1).CompareTo(PromoteToFixInt(r2, n2));

        if (res == 0)
            res = (r1 > 0) ? O_IS_GREATER : (r1 < 0) ? O_IS_LESS : O_IS_EQUAL;

        return ((mask & res) != 0) ? s.TrueV : s.FalseV;
    }

    static readonly Func<Constants,Variable,Variable,Variable> mul_d = mul;
[ImplicitConsts] public static Variable mul(Constants c, Variable a1, Variable a2) {
        int r1, r2;
        P6any o1 = a1.Fetch(), o2 = a2.Fetch();
        if (!(o1.mo.is_any && o2.mo.is_any))
            return HandleSpecial2(c, a1,a2, o1,o2, mul_d);
        P6any n1 = GetNumber(a1, o1, out r1);
        P6any n2 = GetNumber(a2, o2, out r2);

        if (r1 == NR_COMPLEX || r2 == NR_COMPLEX) {
            Complex v1 = PromoteToComplex(r1, n1);
            Complex v2 = PromoteToComplex(r2, n2);
            return MakeComplex(v1.re*v2.re - v1.im*v2.im, v1.im*v2.re + v1.re*v2.im);
        }
        if (r1 == NR_FLOAT || r2 == NR_FLOAT) {
            return MakeFloat(PromoteToFloat(r1, n1) * PromoteToFloat(r2, n2));
        }
        if (r1 == NR_FATRAT || r2 == NR_FATRAT) {
            FatRat v1 = PromoteToFatRat(r1, n1);
            FatRat v2 = PromoteToFatRat(r2, n2);

            return MakeFatRat(v1.num*v2.num, v1.den*v2.den);
        }
        if (r1 == NR_FIXRAT || r2 == NR_FIXRAT) {
            Rat v1 = PromoteToFixRat(r1, n1);
            Rat v2 = PromoteToFixRat(r2, n2);

            return MakeFixRat(v1.num*v2.num, ((BigInteger)v1.den)*v2.den);
        }
        if (r1 == NR_BIGINT || r2 == NR_BIGINT) {
            return MakeInt(PromoteToBigInt(r1, n1) * PromoteToBigInt(r2, n2));
        }
        return MakeInt((long)PromoteToFixInt(r1, n1) *
                (long)PromoteToFixInt(r2, n2));
    }

    static readonly Func<Constants,Variable,Variable,Variable> divide_d = divide;
[ImplicitConsts] public static Variable divide(Constants c, Variable a1, Variable a2) {
        int r1, r2;
        P6any o1 = a1.Fetch(), o2 = a2.Fetch();
        if (!(o1.mo.is_any && o2.mo.is_any))
            return HandleSpecial2(c, a1,a2, o1,o2, divide_d);
        P6any n1 = GetNumber(a1, o1, out r1);
        P6any n2 = GetNumber(a2, o2, out r2);

        if (r1 == NR_COMPLEX || r2 == NR_COMPLEX) {
            Complex v1 = PromoteToComplex(r1, n1);
            Complex v2 = PromoteToComplex(r2, n2);
            double sn2 = v2.re*v2.re + v2.im*v2.im;
            return MakeComplex((v1.re*v2.re + v1.im*v2.im)/sn2,
                    (v2.re*v1.im - v2.im*v1.re)/sn2);
        }
        if (r1 == NR_FLOAT || r2 == NR_FLOAT) {
            return MakeFloat(PromoteToFloat(r1, n1) / PromoteToFloat(r2, n2));
        }
        if (r1 == NR_FATRAT || r2 == NR_FATRAT) {
            FatRat v1 = PromoteToFatRat(r1, n1);
            FatRat v2 = PromoteToFatRat(r2, n2);

            return MakeFatRat(v1.num*v2.den, v1.den*v2.num);
        }
        if (r1 == NR_FIXRAT || r2 == NR_FIXRAT) {
            Rat v1 = PromoteToFixRat(r1, n1);
            Rat v2 = PromoteToFixRat(r2, n2);

            return MakeFixRat(v1.num*v2.den, v2.num*v1.den);
        }
        if (r1 == NR_BIGINT || r2 == NR_BIGINT) {
            return MakeFixRat(PromoteToBigInt(r1, n1), PromoteToBigInt(r2, n2));
        }
        return MakeFixRat(PromoteToFixInt(r1, n1), PromoteToFixInt(r2, n2));
    }

    static readonly Func<Constants,Variable,Variable,Variable> mod_d = mod;
[ImplicitConsts] public static Variable mod(Constants c, Variable a1, Variable a2) {
        int r1, r2;
        P6any o1 = a1.Fetch(), o2 = a2.Fetch();
        if (!(o1.mo.is_any && o2.mo.is_any))
            return HandleSpecial2(c, a1,a2, o1,o2, mod_d);
        P6any n1 = GetNumber(a1, o1, out r1);
        P6any n2 = GetNumber(a2, o2, out r2);

        if (r1 == NR_COMPLEX || r2 == NR_COMPLEX) {
            throw new NieczaException("Modulus operation not defined with complex arguments");
        }
        if (r1 == NR_FLOAT || r2 == NR_FLOAT) {
            double v1 = PromoteToFloat(r1, n1);
            double v2 = PromoteToFloat(r2, n2);
            return MakeFloat(v1 - v2 * Math.Floor(v1 / v2));
        }
        if (r1 == NR_FATRAT || r2 == NR_FATRAT) {
            FatRat v1 = PromoteToFatRat(r1, n1);
            FatRat v2 = PromoteToFatRat(r2, n2);

            BigInteger c1 = v1.num*v2.den;
            BigInteger c2 = v2.num*v1.den;
            BigInteger cd = v1.den*v2.den;

            BigInteger rem;
            BigInteger red = BigInteger.DivRem(c1, c2, out rem);
            if (c2.Sign > 0 && rem.Sign < 0) red--;
            if (c2.Sign < 0 && rem.Sign > 0) red--;

            return MakeFatRat(c1 - red*cd, cd);
        }
        if (r1 == NR_FIXRAT || r2 == NR_FIXRAT) {
            Rat v1 = PromoteToFixRat(r1, n1);
            Rat v2 = PromoteToFixRat(r2, n2);

            BigInteger c1 = v1.num*v2.den;
            BigInteger c2 = v2.num*v1.den;
            BigInteger cd = ((BigInteger)v1.den)*v2.den;

            BigInteger rem;
            BigInteger red = BigInteger.DivRem(c1, c2, out rem);
            if (c2.Sign > 0 && rem.Sign < 0) red--;
            if (c2.Sign < 0 && rem.Sign > 0) red--;

            return MakeFixRat(c1 - red*c2, cd);
        }
        if (r1 == NR_BIGINT || r2 == NR_BIGINT) {
            BigInteger v1 = PromoteToBigInt(r1, n1);
            BigInteger v2 = PromoteToBigInt(r2, n2);
            BigInteger rem;
            BigInteger red = BigInteger.DivRem(v1, v2, out rem);
            if (v2.Sign > 0 && rem.Sign < 0) red--;
            if (v2.Sign < 0 && rem.Sign > 0) red--;
            return MakeInt(v1 - v2*red);
        }
        {
            long v1 = PromoteToFixInt(r1, n1);
            long v2 = PromoteToFixInt(r2, n2);
            long rem;
            long red = Math.DivRem(v1, v2, out rem);
            if (v2 > 0 && rem < 0) red--;
            if (v2 < 0 && rem > 0) red--;
            return MakeInt(v1 - v2*red);
        }
    }

    // this is only called from .Int
    public static Variable coerce_to_int(Variable a1) {
        int r1;
        P6any o1 = a1.Fetch();
        P6any n1 = GetNumber(a1, o1, out r1);

        if (r1 == NR_FLOAT) {
            double v1 = PromoteToFloat(r1, n1);
            if (Double.IsNaN(v1) || Double.IsNegativeInfinity(v1) || Double.IsPositiveInfinity(v1)) {
                return MakeFloat(v1);
            }
        }

        int small; BigInteger big;
        return GetAsInteger(a1, out small, out big) ?
            MakeInt(big) : MakeInt(small);
    }

    // only called from infix for now
    // when it's not, it'll need to be split anyway, I think
    // I fumbled spec reading - only 4 and 5 are actually needed
    public static Variable divop(int opc, Variable a1, Variable a2) {
        int small1, small2; BigInteger big1, big2;
        bool b1 = GetAsInteger(a1, out small1, out big1);
        bool b2 = GetAsInteger(a2, out small2, out big2);

        if (b1 || b2 || small1 == int.MinValue || small2 == int.MinValue) {
            if (!b1) big1 = small1;
            if (!b2) big2 = small2;
            BigInteger rem;
            BigInteger red = BigInteger.DivRem(big1, big2, out rem);
            if (opc >= 4 && big2.Sign > 0 && rem.Sign < 0) {
                red--;
                rem += big2;
            }
            if (opc >= 4 && big2.Sign < 0 && rem.Sign > 0) {
                red--;
                rem += big2;
            }
            switch (opc & 3) {
                case 0: return MakeInt(red);
                case 1: return MakeInt(rem);
                default: return MakeParcel(MakeInt(red), MakeInt(rem));
            }
        } else {
            int rem = small1 % small2;
            int red = small1 / small2;
            if (opc >= 4 && small2 > 0 && rem < 0) {
                red--;
                rem += small2;
            }
            if (opc >= 4 && small2 < 0 && rem > 0) {
                red--;
                rem += small2;
            }
            switch (opc & 3) {
                case 0: return MakeInt(red);
                case 1: return MakeInt(rem);
                default: return MakeParcel(MakeInt(red), MakeInt(rem));
            }
        }
    }

    // called from .Num
    public static Variable coerce_to_num(Variable a1) {
        int r1;
        P6any n1 = GetNumber(a1, a1.Fetch(), out r1);

        if (r1 == NR_COMPLEX) {
            Complex v1 = PromoteToComplex(r1, n1);
            if (v1.im != 0)
                throw new NieczaException("Complex cannot be used here");
            return MakeFloat(v1.re);
        } else {
            return MakeFloat(PromoteToFloat(r1, n1));
        }
    }

    static readonly Func<Constants,Variable,Variable> sqrt_d = sqrt;
[ImplicitConsts] public static Variable sqrt(Constants c, Variable a1) {
        P6any o1 = a1.Fetch();
        int r1;
        if (!o1.mo.is_any)
            return HandleSpecial1(c, a1,o1, sqrt_d);
        P6any n1 = GetNumber(a1, o1, out r1);

        if (r1 == NR_COMPLEX) {
            Complex v1 = PromoteToComplex(r1, n1);
            double angle = Math.Atan2(v1.im, v1.re) / 2;
            double mag = Math.Sqrt(Math.Sqrt(v1.im*v1.im + v1.re*v1.re));
            return MakeComplex(mag * Math.Cos(angle), mag * Math.Sin(angle));
        } else {
            double val = PromoteToFloat(r1, n1);
            return MakeFloat(Math.Sqrt(val));
        }
    }

    static readonly Func<Constants,Variable,Variable,Variable> numand_d = numand;
[ImplicitConsts] public static Variable numand(Constants c, Variable v1, Variable v2) {
        P6any o1 = v1.Fetch(); P6any o2 = v2.Fetch();
        if (!(o1.mo.is_any && o2.mo.is_any))
            return HandleSpecial2(c, v1,v2, o1,o2, numand_d);

        int r1 = (int)o1.mo.mro_raw_Numeric.Get(v1);
        int r2 = (int)o2.mo.mro_raw_Numeric.Get(v2);
        return MakeInt(r1 & r2);
    }

    static readonly Func<Constants,Variable,Variable,Variable> numor_d = numor;
[ImplicitConsts] public static Variable numor(Constants c, Variable v1, Variable v2) {
        P6any o1 = v1.Fetch(); P6any o2 = v2.Fetch();
        if (!(o1.mo.is_any && o2.mo.is_any))
            return HandleSpecial2(c, v1,v2, o1,o2, numor_d);

        int r1 = (int)o1.mo.mro_raw_Numeric.Get(v1);
        int r2 = (int)o2.mo.mro_raw_Numeric.Get(v2);
        return MakeInt(r1 | r2);
    }

    static readonly Func<Constants,Variable,Variable,Variable> numxor_d = numxor;
[ImplicitConsts] public static Variable numxor(Constants c, Variable v1, Variable v2) {
        P6any o1 = v1.Fetch(); P6any o2 = v2.Fetch();
        if (!(o1.mo.is_any && o2.mo.is_any))
            return HandleSpecial2(c, v1,v2, o1,o2, numxor_d);

        int r1 = (int)o1.mo.mro_raw_Numeric.Get(v1);
        int r2 = (int)o2.mo.mro_raw_Numeric.Get(v2);
        return MakeInt(r1 ^ r2);
    }

    static readonly Func<Constants,Variable,Variable,Variable> numlshift_d = numlshift;
[ImplicitConsts] public static Variable numlshift(Constants c, Variable v1, Variable v2) {
        P6any o1 = v1.Fetch(); P6any o2 = v2.Fetch();
        if (!(o1.mo.is_any && o2.mo.is_any))
            return HandleSpecial2(c, v1,v2, o1,o2, numlshift_d);

        int r1 = (int)o1.mo.mro_raw_Numeric.Get(v1);
        int r2 = (int)o2.mo.mro_raw_Numeric.Get(v2);
        return MakeInt(r1 << r2);
    }

    static readonly Func<Constants,Variable,Variable,Variable> numrshift_d = numrshift;
[ImplicitConsts] public static Variable numrshift(Constants c, Variable v1, Variable v2) {
        P6any o1 = v1.Fetch(); P6any o2 = v2.Fetch();
        if (!(o1.mo.is_any && o2.mo.is_any))
            return HandleSpecial2(c, v1,v2, o1,o2, numrshift_d);

        int r1 = (int)o1.mo.mro_raw_Numeric.Get(v1);
        int r2 = (int)o2.mo.mro_raw_Numeric.Get(v2);
        return MakeInt(r1 >> r2);
    }

    static readonly Func<Constants,Variable,Variable> numcompl_d = numcompl;
[ImplicitConsts] public static Variable numcompl(Constants c, Variable v1) {
        P6any o1 = v1.Fetch();
        if (!o1.mo.is_any)
            return HandleSpecial1(c, v1,o1, numcompl_d);

        int r1 = (int)o1.mo.mro_raw_Numeric.Get(v1);
        return MakeInt(~r1);
    }

    // only called from .Rat
[ImplicitConsts] public static Variable rat_approx(Constants c, Variable v1, Variable v2) {
        NominalCheck("$x", c.setting.AnyMO, v1);
        NominalCheck("$y", c.setting.AnyMO, v2);

        BigInteger nc, dc, ne, de, na, da;
        GetAsRational(v1, out nc, out dc);
        GetAsRational(v2, out ne, out de);

        if (ne != 0) {
            RatApproxer.Simplest(nc*de-ne*dc,dc*de,nc*de+ne*dc,dc*de,out na,out da);
        } else {
            na = nc; da = dc;
        }

        SimplifyFrac(ref na, ref da);

        // since the user controls the denominator size here, use FatRat freely
        // XXX: is it appropriate to return FatRat from a method named Rat?
        ulong sda;
        if (da.AsUInt64(out sda)) {
            return MakeFixRat(na,da);
        } else {
            return MakeFatRat(na,da);
        }
    }

[ImplicitConsts] public static Variable postinc(Constants c, Variable v) {
        P6any o1 = v.Fetch();
        v.AssignO(o1.mo.mro_succ.Get(v), false);

        if (!o1.IsDefined()) {
            if (o1.Isa(c.setting.BoolMO))
                o1 = c.setting.FalseV;
            else
                o1 = Kernel.BoxRaw<int>(0, c.setting.IntMO);
        }

        return o1;
    }

    public static Variable preinc(Variable v) {
        v.AssignO(v.Fetch().mo.mro_succ.Get(v), false);
        return v;
    }

[ImplicitConsts] public static Variable postdec(Constants c, Variable v) {
        P6any o1 = v.Fetch();
        v.AssignO(o1.mo.mro_pred.Get(v), false);

        if (!o1.IsDefined()) {
            if (o1.Isa(c.setting.BoolMO))
                o1 = c.setting.FalseV;
            else
                o1 = Kernel.BoxRaw<int>(0, c.setting.IntMO);
        }

        return o1;
    }

    public static Variable predec(Variable v) {
        v.AssignO(v.Fetch().mo.mro_pred.Get(v), false);
        return v;
    }

[ImplicitConsts] public static Variable not(Constants c, Variable v) {
        P6any o1 = v.Fetch();
        bool r = o1.mo.mro_raw_Bool.Get(v);
        return r ? c.setting.FalseV : c.setting.TrueV;
    }

    static readonly Func<Constants,Variable,Variable> chars_d = chars;
[ImplicitConsts] public static Variable chars(Constants c, Variable v) {
        P6any o1 = v.Fetch();
        if (!o1.mo.is_any)
            return HandleSpecial1(c, v,o1, chars_d);

        string r = o1.mo.mro_raw_Str.Get(v);
        return MakeInt(r.Length);
    }

    static readonly Func<Constants,Variable,Variable> codes_d = codes;
[ImplicitConsts] public static Variable codes(Constants c, Variable v) {
        P6any o1 = v.Fetch();
        if (!o1.mo.is_any)
            return HandleSpecial1(c, v,o1, codes_d);

        string r = o1.mo.mro_raw_Str.Get(v);

        int i = 0;
        foreach (char ch in r)
            if (((uint)(ch - 0xDC00)) >= 0x400)
                i++;

        return MakeInt(i);
    }

    static readonly Func<Constants,Variable,Variable> ord_d = ord;
[ImplicitConsts] public static Variable ord(Constants c, Variable v) {
        P6any o1 = v.Fetch();
        if (!o1.mo.is_any)
            return HandleSpecial1(c, v,o1, ord_d);

        string r = o1.mo.mro_raw_Str.Get(v);
        // XXX Failure
        if (r.Length == 0) return c.setting.AnyP;
        else if (r.Length >= 2 &&
                r[0] >= (char)0xD800 && r[0] <= (char)0xDBFF &&
                r[1] >= (char)0xDC00 && r[1] <= (char)0xDFFF)
            return MakeInt((0x10000 - 0xDC00) +
                    ((int)r[0] - 0xD800) * 0x400 + (int)r[1]);
        return MakeInt((int)r[0]);
    }

    static readonly Func<Constants,Variable,Variable> chr_d = chr;
[ImplicitConsts] public static Variable chr(Constants c, Variable v) {
        P6any o1 = v.Fetch();
        if (!o1.mo.is_any)
            return HandleSpecial1(c, v,o1, chr_d);

        int r = (int)o1.mo.mro_raw_Numeric.Get(v);
        if (r >= 0x110000)
            return c.setting.AnyP; // XXX failure
        return Kernel.BoxAnyMO(Utils.Chr(r), c.setting.StrMO);
    }

[ImplicitConsts] public static Variable UniCat(Constants c, Variable v) {
        P6any o1 = NominalCheck("$x", c.setting.AnyMO, v);
        char ch = (char) o1.mo.mro_raw_Numeric.Get(v);
        int ix = (int) char.GetUnicodeCategory(ch);
        return MakeInt(ix);
    }

    public static Variable MakeJunction(int type, Variable[] elems) {
        if (type >= 8) {
            type -= 8;
            foreach (Variable e in elems)
                if (e.List) goto need_flatten;
            goto flat_enough;
need_flatten:;
            VarDeque iter = new VarDeque(elems);
            VarDeque into = new VarDeque();
            while (Kernel.IterHasFlat(iter, true))
                into.Push(iter.Shift());
            elems = into.CopyAsArray();
flat_enough:;
        }
        P6opaque nj = new P6opaque(Compartment.Top.JunctionMO);
        nj.slots[0] = Kernel.BoxRaw(type, Compartment.Top.IntMO);
        nj.slots[1] = Kernel.BoxRaw(elems, Compartment.Top.ParcelMO);
        return nj;
    }

    public static Variable Make(Frame fr, Variable v) {
        if (fr.info.name == "CORE make")
            fr = fr.caller;
        Cursor c = (Cursor) fr.LexicalFind("$/").Fetch();
        c.Make(v);
        return v;
    }

    public static VarDeque HashIterRaw(int mode, Variable v) {
        P6any o = NominalCheck("$x", Compartment.Top.AnyMO, v);
        VarHash d = Kernel.UnboxAny<VarHash>(o);

        VarDeque lv = new VarDeque();

        foreach (KeyValuePair<string,Variable> kv in d) {
            switch (mode) {
                case 0:
                    lv.Push(Kernel.BoxAnyMO<string>(kv.Key, Compartment.Top.StrMO));
                    break;
                case 1:
                    lv.Push(kv.Value);
                    break;
                case 2:
                    lv.Push(Kernel.BoxAnyMO<string>(kv.Key, Compartment.Top.StrMO));
                    lv.Push(kv.Value);
                    break;
                case 3:
                    P6opaque p = new P6opaque(Compartment.Top.PairMO);
                    p.slots[0] = Kernel.BoxAnyMO<string>(kv.Key, Compartment.Top.StrMO);
                    p.slots[1] = kv.Value;
                    lv.Push(p);
                    break;
            }
        }
        return lv;
    }
    public static Variable HashIter(int mode, Variable v) {
        VarDeque lv = HashIterRaw(mode, v);
        P6opaque l = new P6opaque(Compartment.Top.ListMO);
        l.slots[0] = lv;
        l.slots[1] = new VarDeque();
        return Kernel.NewRWListVar(l);
    }

    public static Variable path_modified(string path) {
        long t = File.GetLastWriteTimeUtc(path).Ticks;
        return MakeFloat(((double)(t - 621355968000000000L)) / 10000000.0);
    }

    public static Variable now() {
        long t = DateTime.UtcNow.Ticks;
        return MakeFloat(((double)(t - 621355968000000000L)) / 10000000.0);
    }

    public static Variable times() {
        Process p = Process.GetCurrentProcess();
        Variable[] ret = new Variable[4];
        ret[0] = ret[2] = MakeFloat(((double)p.UserProcessorTime.Ticks) / 10000000.0);
        ret[1] = ret[3] = MakeFloat(((double)p.PrivilegedProcessorTime.Ticks) / 10000000.0);
        return MakeParcel(ret);
    }

[TrueGlobal]
    private static object rng_lock = new object();
    private static Random rng = new Random();

    public static Variable rand() {
        double i;
        lock (rng_lock) { i = rng.NextDouble(); }
        return MakeFloat(i);
    }

    public static void srand(int seed) {
        lock (rng_lock) { rng = new Random(seed); }
    }

    public static void srand_time() {
        lock (rng_lock) { rng = new Random(); }
    }

    public static bool path_any_exists(string path) {
        return File.Exists(path) || Directory.Exists(path);
    }

    public static void path_unlink(string path) {
        File.Delete(path);
    }

    public static string cwd_path() {
        return Directory.GetCurrentDirectory();
    }

    public static void path_chdir(string path) {
        Directory.SetCurrentDirectory(path);
    }

    public static void path_mkdir(string path) {
        Directory.CreateDirectory(path);
    }

    public static int path_rmdir(string path) {
        return PosixWrapper.rmdir(path);
    }

    public static void path_copy(string from_path, string to_path) {
        System.IO.File.Copy(from_path, to_path, true);
    }

    public static int command_system(string command) {
        return PosixWrapper.system(command);
    }

    public static int command_run(Variable argv, Variable env) {
        Type Process = Type.GetType("GLib.Process,glib-sharp, Version=2.12.0.0, Culture=neutral, PublicKeyToken=35e10195dab3c99f");
        Type SpawnFlags = Type.GetType("GLib.SpawnFlags,glib-sharp, Version=2.12.0.0, Culture=neutral, PublicKeyToken=35e10195dab3c99f");
        MethodInfo spawn_sync = Process.GetMethod("SpawnSync");

        object[] arguments = new object[]{ null, UnboxLoS(argv), UnboxLoS(env), Enum.ToObject(SpawnFlags, 0), null,
                                           null, null, null };
        bool result = (bool) spawn_sync.Invoke(null, arguments);
/* string stdout = (string) arguments[5];
string stderr = (string) arguments[6];
int exit_status = (int) arguments[7];
*/ return result ? 1 : 0;
    }

    public static string command_qx(string command_line) {
        Type Process;
        try {
            Process = Type.GetType("GLib.Process,glib-sharp, Version=2.12.0.0, Culture=neutral, PublicKeyToken=35e10195dab3c99f");
        } catch (Exception) {
            Process = null;
        }
        if (Process != null) {
            MethodInfo spawn_sync = Process.GetMethod("SpawnCommandLineSync");

            object[] arguments = new object[]{ command_line, null, null, null };
            bool result = (bool) spawn_sync.Invoke(null, arguments);
            return result ? (string) arguments[1] : "";
        } else {
            /* Next line should be more robust... */
            string [] args = command_line.Split(new Char[] {' '}, 2);
            Process process = new Process();
            process.StartInfo.UseShellExecute = false;
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.FileName = args[0];
            if (args.Length > 1 && args[1] != "") {
                process.StartInfo.Arguments = args[1];
            }
            process.Start();
            /* Next two lines have to be in this order, not sure why */
            string output = process.StandardOutput.ReadToEnd();
            process.WaitForExit();
            return output;
        }
    }

    public static int path_chmod(string path, double mode) {
        return PosixWrapper.chmod(path, (int) mode);
    }

    public static bool emulate_eaccess(string path, int mode) {
        uint ruid = PosixWrapper.getuid();
        uint rgid = PosixWrapper.getgid();
        uint euid = PosixWrapper.geteuid();
        uint egid = PosixWrapper.getegid();
        // this is not threadsafe, but it's how Perl 5 does it sometimes
        PosixWrapper.setreuid(euid, euid);
        PosixWrapper.setregid(egid, egid);
        int res = PosixWrapper.access(path, mode);
        PosixWrapper.setreuid(ruid, euid);
        PosixWrapper.setregid(rgid, egid);
        return res == 0;
    }

    public static bool path_access_readable(string path) {
        return (File.Exists(path) || Directory.Exists(path))
            && PosixWrapper.access(path, PosixWrapper.R_OK) == 0;
    }

    public static bool path_access_writable(string path) {
        return (File.Exists(path) || Directory.Exists(path))
            && PosixWrapper.access(path, PosixWrapper.W_OK) == 0;
    }

    public static bool path_access_executable(string path) {
        return (File.Exists(path) || Directory.Exists(path))
            && PosixWrapper.access(path, PosixWrapper.X_OK) == 0;
    }
    
    public static bool path_eaccess_readable(string path) {
        return (File.Exists(path) || Directory.Exists(path))
            && emulate_eaccess(path, PosixWrapper.R_OK);
    }

    public static bool path_eaccess_writable(string path) {
        return (File.Exists(path) || Directory.Exists(path))
            && emulate_eaccess(path, PosixWrapper.W_OK);
    }

    public static bool path_eaccess_executable(string path) {
        return (File.Exists(path) || Directory.Exists(path))
            && emulate_eaccess(path, PosixWrapper.X_OK);
    }

    public static bool path_eaccess_owned(string path) {
        if (!File.Exists(path) && !Directory.Exists(path))
            return false;
        long[] stat = PosixWrapper.stat(path);
        return PosixWrapper.geteuid() == (uint)stat[5];
    }

    public static bool path_access_owned(string path) {
        if (!File.Exists(path) && !Directory.Exists(path))
            return false;
        long[] stat = PosixWrapper.stat(path);
        return PosixWrapper.getuid() == (uint)stat[5];
    }

    public static P6any MakeList(VarDeque items, VarDeque rest) {
        P6any l = new P6opaque(Compartment.Top.ListMO);
        l.SetSlot(Compartment.Top.ListMO, "$!rest", rest);
        l.SetSlot(Compartment.Top.ListMO, "$!items", items);
        return l;
    }

    public static P6any MakeArray(VarDeque items, VarDeque rest) {
        P6any l = new P6opaque(Compartment.Top.ArrayMO);
        l.SetSlot(Compartment.Top.ListMO, "$!rest", rest);
        l.SetSlot(Compartment.Top.ListMO, "$!items", items);
        return l;
    }

    public static Variable BoxLoS(string[] los) {
        VarDeque items = new VarDeque();
        foreach (string i in los)
            items.Push(Kernel.BoxAnyMO(i, Compartment.Top.StrMO));
        return Kernel.NewRWListVar(MakeList(items, new VarDeque()));
    }

    public static string[] UnboxLoS(Variable args) {
        List<string> la = new List<string>();
        VarDeque iter = start_iter(args);
        while (Kernel.IterHasFlat(iter, true)) {
            Variable v = iter.Shift();
            la.Add(v.Fetch().mo.mro_raw_Str.Get(v));
        }
        return la.ToArray();
    }

    public static Frame you_are_here(Frame th, string sname) {
        P6any to_call = Kernel.MakeSub(th.info.setting.setting_path[sname], th);
        return to_call.Invoke(th, Variable.None, null);
    }

    public static void RunSubtask(string file, string args) {
        System.Diagnostics.Process.Start(file, args).WaitForExit();
    }

[TrueGlobal] internal static System.Collections.IDictionary upcall_receiver;
    internal static object UpCall(object[] args) {
        return upcall_receiver[args];
    }
    public static Frame simple_eval(Frame th, Variable str) {
        if (upcall_receiver == null)
            return Kernel.Die(th, "Cannot eval; no compiler available");
        SubInfo outer = th.caller.info;
        object r = UpCall(new object[] { "eval",
                str.Fetch().mo.mro_raw_Str.Get(str),
                new Niecza.CLRBackend.Handle(outer),
                new Niecza.CLRBackend.Handle(th.caller)
                });
        if (r is Exception)
            return Kernel.Die(th, ((Exception)r).Message);
        P6any sub = Kernel.MakeSub(((RuntimeUnit)Niecza.CLRBackend.Handle.Unbox(r)).mainline, th.caller);
        return sub.Invoke(th, Variable.None, null);
    }

    internal static P6any compile_bind_regex(Frame th, string code) {
        if (th.info.rx_compile_cache == null)
            th.info.rx_compile_cache = new Dictionary<string, SubInfo>();
        SubInfo main;
        // TODO: it would be better if the compiler could be modified to
        // compile a regex directly as the mainline
        if (!th.info.rx_compile_cache.TryGetValue(code, out main)) {
            if (upcall_receiver == null)
                throw new NieczaException("Cannot eval; no compiler available");
            object r = UpCall(new object[] { "eval",
                    "regex {" + code + "}",
                    new Niecza.CLRBackend.Handle(th.info)
                    });
            if (r is Exception)
                throw new NieczaException(((Exception)r).Message);
            main = ((RuntimeUnit)Niecza.CLRBackend.Handle.Unbox(r)).mainline;
            th.info.rx_compile_cache[code] = main;
        }
        P6any sub = Kernel.MakeSub(main, th);
        return Kernel.RunInferior(sub.Invoke(Kernel.GetInferiorRoot(),
            Variable.None, null)).Fetch();
    }

    public static P6any MakePair(Variable key, Variable value) {
        P6any l = new P6opaque(Compartment.Top.PairMO);
        l.SetSlot(Compartment.Top.EnumMO, "$!key", key);
        l.SetSlot(Compartment.Top.EnumMO, "$!value", value);
        return l;
    }

    public static Variable pair(Variable key, Variable value) {
        return MakePair(key, value);
    }

    public static VarDeque start_iter(Variable thing) {
        if (thing.List)
            return thing.Fetch().mo.mro_raw_iterator.Get(thing);
        else
            return new VarDeque(thing);
    }

    public static Variable array_constructor(Variable bits) {
        VarDeque rest = start_iter(bits);
        VarDeque items = new VarDeque();
        while (Kernel.IterHasFlat(rest, true))
            items.Push(Kernel.NewMuScalar(rest.Shift().Fetch()));
        return MakeArray(items, rest);
    }

    public static string frame_subname(Frame fr) {
        return fr.info.name.Substring(fr.info.name.IndexOf(" ")+1);
    }

[ImplicitConsts] public static Variable count(Constants c, P6any fcni) {
        int i = get_count(fcni);
        return (i == int.MaxValue) ? MakeFloat(double.PositiveInfinity) :
            MakeInt(i);
    }
    public static int get_count(P6any fcni) {
        if (!fcni.Isa(Compartment.Top.CodeMO))
            return 1; // can't introspect fake subs (?)
        return sig_count(Kernel.GetInfo(fcni).sig);
    }
    public static int sig_count(P6any si) {
        if (si == null)
            return 1;
        int arity = 0;
        foreach (Parameter p in ((Signature)si).parms) {
            int fl = p.flags;
            if ((fl & (Parameter.SLURPY_CAP | Parameter.SLURPY_POS |
                    Parameter.SLURPY_PCL)) != 0)
                return int.MaxValue;
            if ((fl & Parameter.SLURPY_NAM) != 0) continue;
            if ((fl & Parameter.POSITIONAL) == 0) continue;
            arity++;
        }
        return arity;
    }

    public static int sig_arity(P6any obj) {
        int arity = 0;
        foreach (Parameter p in ((Signature)obj).parms) {
            int fl = p.flags;
            if ((fl & (Parameter.SLURPY_CAP | Parameter.SLURPY_POS |
                    Parameter.SLURPY_PCL | Parameter.SLURPY_NAM |
                    Parameter.OPTIONAL | Parameter.DEFOUTER |
                    Parameter.HASDEFAULT)) != 0)
                continue;
            if ((fl & Parameter.POSITIONAL) == 0) continue;
            arity++;
        }
        return arity;
    }
[ImplicitConsts] public static Variable arity(Constants c, P6any fcni) {
        if (!fcni.Isa(c.setting.CodeMO))
            return MakeInt(1); // can't introspect fake subs (?)
        SubInfo si = (SubInfo) Kernel.GetInfo(fcni);
        if (si.sig == null)
            return MakeInt(1);
        return MakeInt(sig_arity(si.sig));
    }

    class ItemSource {
        protected ItemSource() {}
[Immutable]
        public static ItemSource Empty = new ItemSource();
        // main access point - return true to block (only if block is true)
        public virtual bool TryGet(out Variable[] r, bool block) {
            r = null;
            return true;
        }
        // utility to get data from a list
        protected static int TryOne(VarDeque items, bool block) {
            if (block) {
                return Kernel.IterHasFlat(items, true) ? +1 : -1;
            } else {
again:
                if (items.Count() == 0) return -1;
                Variable v = items[0];
                P6any i = v.Fetch();
                if (i.mo.HasType(Compartment.Top.IterCursorMO))
                    return 0;
                if (v.List) {
                    items.Shift();
                    items.UnshiftD(i.mo.mro_raw_iterator.Get(v));
                    goto again;
                }
                return +1;
            }
        }
    }

    class BatchSource: ItemSource {
        int arity;
        VarDeque items;

        public BatchSource(int count, VarDeque items) {
            this.arity = count;
            this.items = items;
        }

        public override bool TryGet(out Variable[] r, bool block) {
            r = null;
            List<Variable> pen = new List<Variable>();
            while (pen.Count < arity) {
                switch (TryOne(items, block)) {
                    case -1: goto nomore;
                    case 0:
                        for (int i = pen.Count - 1; i >= 0; i--)
                            items.Unshift(pen[i]);
                        return false;
                    case +1: pen.Add(items.Shift()); break;
                }
            }
nomore:
            if (pen.Count != 0)
                r = pen.ToArray();
            return true;
        }
    }

    class ZipSource : ItemSource {
        VarDeque[] sources;
        public ZipSource(Variable[] pcl) {
            sources = new VarDeque[pcl.Length];
            for (int i = 0; i < pcl.Length; i++)
                sources[i] = start_iter(pcl[i]);
        }

        public override bool TryGet(out Variable[] r, bool block) {
            r = null;
            for (int i = 0; i < sources.Length; i++)
                switch (TryOne(sources[i], block)) {
                    case -1: return true;
                    case 0: return false;
                }
            if (sources.Length == 0)
                return true; // empty zip should return immediately
            r = new Variable[sources.Length];
            for (int i = 0; i < sources.Length; i++)
                r[i] = sources[i].Shift();
            return true;
        }
    }

    class CrossSource: ItemSource {
        VarDeque[] basic;
        VarDeque[] iter;
        Variable[] basic_top;
        Variable[] iter_top;
        // 0=init 1=end i=advance wheel i-2
        int state;

        public CrossSource(Variable[] pcl) {
            basic = new VarDeque[pcl.Length];
            iter = new VarDeque[pcl.Length];
            basic_top = new Variable[pcl.Length];
            iter_top = new Variable[pcl.Length];
            for (int i = 0; i < pcl.Length; i++) {
                iter[i] = start_iter(pcl[i]);
            }
        }

        public override bool TryGet(out Variable[] r, bool block) {
            r = null;
            if (state == 0) {
                // Make sure all the lists are non-empty.
                for (int i = 0; i < iter.Length; i++) {
                    switch (TryOne(iter[i], block)) {
                        case -1: return true;
                        case 0: return false;
                        case 1: break;
                    }
                }
                for (int i = 0; i < iter.Length; i++) {
                    iter_top[i] = iter[i].Shift();
                    if (i != 0) {
                        basic[i] = new VarDeque(iter[i]);
                        basic_top[i] = iter_top[i];
                    }
                }
            }
            else if (state == 1) {
                return true;
            }
            else {
again:
                int wheel = state - 2;
                switch (TryOne(iter[wheel], block)) {
                    case 0: return false;
                    case +1:
                        iter_top[wheel] = iter[wheel].Shift();
                        break;
                    case -1:
                        if (wheel == 0) return true;
                        iter[wheel] = new VarDeque(basic[wheel]);
                        iter_top[wheel] = basic_top[wheel];
                        state--;
                        goto again;
                }
            }
            r = new Variable[iter_top.Length];
            for (int i = 0; i < iter_top.Length; i++)
                r[i] = iter_top[i];
            state = iter_top.Length + 1;
            return true;
        }
    }

    internal static Frame CommonMEMap_C(Frame th) {
        ItemSource src = (ItemSource) th.lex0;
        VarDeque outq = (VarDeque) th.lex1;
        object fnc = th.lex2;
        int tailmode = th.lexi0;
        var setting = th.info.setting;

        switch (th.ip) {
            case 0:
                Variable[] pen;
                if (!src.TryGet(out pen, tailmode != 0)) {
                    P6opaque thunk = new P6opaque(setting.GatherIteratorMO);
                    th.coro_return = th;
                    th.MarkSharedChain();
                    thunk.slots[0] = Kernel.NewMuScalar(th);
                    thunk.slots[1] = Kernel.NewMuScalar(setting.AnyP);
                    P6opaque lst = new P6opaque(setting.ListMO);
                    lst.slots[0] = outq;
                    lst.slots[1] = new VarDeque(thunk);
                    th.caller.resultSlot = Kernel.NewRWListVar(lst);
                    th.lexi0 = 1;
                    return th.Return();
                }
                if (pen == null) {
                    if (tailmode != 0)
                        return Kernel.Take(th, setting.EMPTYP);
                    P6opaque lst = new P6opaque(setting.ListMO);
                    lst.slots[0] = outq;
                    lst.slots[1] = new VarDeque();
                    th.caller.resultSlot = Kernel.NewRWListVar(lst);
                    return th.Return();
                }
                th.lex3 = pen;
                th.ip = 1;
                goto case 1;
            case 1:
                th.ip = 2;
                if (fnc is P6any) {
                    return ((P6any)fnc).Invoke(th, (Variable[])th.lex3, null);
                } else if (fnc == null) {
                    th.resultSlot = MakeParcel((Variable[]) th.lex3);
                    goto case 2;
                } else {
                    th.resultSlot = ((Func<Variable,Variable>)fnc).Invoke(
                        ((Variable[])th.lex3)[0]);
                    goto case 2;
                }
            case 2:
                if (tailmode != 0) {
                    th.ip = 0;
                    return Kernel.Take(th, (Variable)th.resultSlot);
                } else {
                    outq.Push((Variable) th.resultSlot);
                    th.ip = 0;
                    goto case 0;
                }
            case 3:
                th.lex0 = src = ItemSource.Empty;
                th.ip = 0;
                goto case 0;
            default:
                return Kernel.Die(th, "Invalid IP");
        }
    }

    public static Frame MEMap(Frame th, Variable[] lst) {
        VarDeque iter = new VarDeque(lst);
        Variable fcn = iter.Shift();
        P6any fcni = fcn.Fetch();
        int arity = get_count(fcni);
        var setting = th.info.setting;

        Frame fr = th.MakeChild(null, setting.CommonMEMap_I, setting.AnyP);
        fr.lexi0 = 0;
        fr.lex0 = new BatchSource(arity, iter);
        fr.lex1 = new VarDeque();
        fr.lex2 = fcni;
        return fr;
    }

    public static Frame MEMap_for_each(Frame th, P6any lst,
            Func<Variable,Variable> fcn) {
        VarDeque iter = new VarDeque(Kernel.NewRWListVar(lst));
        var setting = th.info.setting;

        Frame fr = th.MakeChild(null, setting.CommonMEMap_I, setting.AnyP);
        fr.lexi0 = 0;
        fr.lex0 = new BatchSource(1, iter);
        fr.lex1 = new VarDeque();
        fr.lex2 = fcn;
        return fr;
    }

    static P6any ExtractWith(bool with, ref Variable[] pcl) {
        if (!with) return null;
        Variable[] opcl = pcl;
        pcl = new Variable[pcl.Length - 1];
        for (int j = 0; j < pcl.Length; j++)
            pcl[j] = opcl[j+1];
        return opcl[0].Fetch();
    }

    public static Frame MEZip(Frame th, bool with, Variable[] pcl) {
        var setting = th.info.setting;
        Frame fr = th.MakeChild(null, setting.CommonMEMap_I, setting.AnyP);
        Kernel.SetTopFrame(fr);
        fr.lexi0 = 0;
        fr.lex2 = ExtractWith(with, ref pcl);
        fr.lex0 = new ZipSource(pcl);
        fr.lex1 = new VarDeque();
        return fr;
    }

    public static Frame MECross(Frame th, bool with, Variable[] pcl) {
        var setting = th.info.setting;
        Frame fr = th.MakeChild(null, setting.CommonMEMap_I, setting.AnyP);
        Kernel.SetTopFrame(fr);
        fr.lexi0 = 0;
        fr.lex2 = ExtractWith(with, ref pcl);
        fr.lex0 = new CrossSource(pcl);
        fr.lex1 = new VarDeque();
        return fr;
    }

    internal static Frame CommonGrep_C(Frame th) {
        VarDeque src = (VarDeque) th.lex0;
        VarDeque outq = (VarDeque) th.lex1;
        Variable flt = (Variable) th.lex2;
        int tailmode = th.lexi0;
        var setting = th.info.setting;

        switch (th.ip) {
            case 0:
                Variable pen = null;
                while (pen == null) {
                    if (tailmode != 0) {
                        if (!Kernel.IterHasFlat(src, false)) break;
                    } else {
                        if (src.Count() == 0) break;
                        if (src[0].Fetch().mo.HasType(setting.IterCursorMO)) {
                            P6opaque thunk = new P6opaque(setting.GatherIteratorMO);
                            th.coro_return = th;
                            th.MarkSharedChain();
                            thunk.slots[0] = Kernel.NewMuScalar(th);
                            thunk.slots[1] = Kernel.NewMuScalar(setting.AnyP);
                            P6opaque lst = new P6opaque(setting.ListMO);
                            lst.slots[0] = outq;
                            lst.slots[1] = new VarDeque(thunk);
                            th.caller.resultSlot = Kernel.NewRWListVar(lst);
                            th.lexi0 = 1;
                            return th.Return();
                        }
                    }
                    pen = src.Shift();
                }
                if (pen == null) {
                    if (tailmode != 0)
                        return Kernel.Take(th, setting.EMPTYP);
                    P6opaque lst = new P6opaque(setting.ListMO);
                    lst.slots[0] = outq;
                    lst.slots[1] = new VarDeque();
                    th.caller.resultSlot = Kernel.NewRWListVar(lst);
                    return th.Return();
                }
                th.lex3 = pen;
                th.ip = 1;
                goto case 1;
            case 1:
                th.ip = 2;
                return flt.Fetch().InvokeMethod(th, "ACCEPTS",
                        new Variable[] { flt, (Variable)th.lex3 }, null);
            case 2:
                Variable r = (Variable) th.resultSlot;
                if (!r.Fetch().mo.mro_raw_Bool.Get(r)) {
                    th.ip = 0;
                    goto case 0;
                }
                if (tailmode != 0) {
                    th.ip = 0;
                    return Kernel.Take(th, (Variable)th.lex3);
                } else {
                    outq.Push((Variable) th.lex3);
                    th.ip = 0;
                    goto case 0;
                }
            case 3:
                th.lex0 = src = new VarDeque();
                th.ip = 0;
                goto case 0;
            default:
                return Kernel.Die(th, "Invalid IP");
        }
    }
    public static Frame MEGrep(Frame th, Variable[] lst) {
        VarDeque iter = new VarDeque(lst);
        Variable fcn = iter.Shift();
        iter = Kernel.IterFlatten(iter);
        var setting = th.info.setting;

        Frame fr = th.MakeChild(null, setting.CommonGrep_I, setting.AnyP);
        fr.lexi0 = 0;
        fr.lex0 = iter;
        fr.lex1 = new VarDeque();
        fr.lex2 = fcn;
        return fr;
    }

    public static Frame CallNext(Frame th, P6any cap) {
        Frame to = th;
        while (to != null && to.curDisp == null)
            to = to.caller;
        if (to == null || to.curDisp.next == null)
            return Kernel.Die(th, "No next function to call!");

        DispatchEnt de = to.curDisp.next;
        P6opaque o = cap as P6opaque;

        Variable[] p = to.pos;
        VarHash n = to.named;
        if (o != null) {
            p = (Variable[]) o.slots[0];
            n = o.slots[1] as VarHash;
        }

        return de.info.SetupCall(th, de.outer, de.ip6, p, n, false, de);
    }

    public static bool obj_can(P6any obj, string mname) {
        return obj.mo.mro_methods.ContainsKey(mname);
    }

    // Used mostly to initialize $*PID et al
[TrueGlobal] public static string programName;
[TrueGlobal] public static string execName;

[ImplicitConsts] public static Variable getenv(Constants c, string str) {
        return Kernel.BoxAnyMO(Environment.GetEnvironmentVariable(str), c.setting.StrMO);
    }

    public static void setenv(string key, string val) {
        Environment.SetEnvironmentVariable(key, val);
    }

[ImplicitConsts] public static Variable sysquery(Constants c, int ix) {
        switch (ix) {
            case 0: return BoxLoS(Kernel.commandArgs);
            case 1: return MakeStr(programName ?? AppDomain.CurrentDomain.FriendlyName);
            case 2: return MakeStr(execName);
            case 3: return MakeStr(AppDomain.CurrentDomain.BaseDirectory);
            case 4: {
                VarHash ret = new VarHash();
                foreach (System.Collections.DictionaryEntry de in Environment.GetEnvironmentVariables()) {
                    ret[(string) de.Key] = Kernel.BoxAnyMO((string)de.Value, c.setting.StrMO);
                }
                return Kernel.BoxAnyMO(ret, c.setting.HashMO);
            }
            case 5: return MakeStr(Environment.OSVersion.Platform.ToString());
            case 6: return MakeStr(Environment.OSVersion.Version.ToString());
            default: return null;
        }
    }

    public static P6any who(P6any obj) { return obj.mo.who; }

[ImplicitConsts] public static Variable stash_exists_key(Constants c, P6any st, string key) {
        string lkey = Kernel.UnboxAny<string>(st);
        lkey = (char)lkey.Length + lkey + key;
        return c.setting.currentGlobals.ContainsKey(lkey) ? c.setting.TrueV : c.setting.FalseV;
    }

    public static Variable stash_at_key(P6any st, string key) {
        return Kernel.GetVar(Kernel.UnboxAny<string>(st), key).v;
    }

    public static Variable stash_bind_key(P6any st, string key, Variable to) {
        Kernel.GetVar(Kernel.UnboxAny<string>(st), key).Bind(to);
        return to;
    }

[ImplicitConsts] public static Variable stash_delete_key(Constants c, P6any st, string key) {
        string lkey = Kernel.UnboxAny<string>(st);
        lkey = (char)lkey.Length + lkey + key;
        StashEnt r;
        if (!c.setting.currentGlobals.TryGetValue(lkey, out r))
            return c.setting.AnyP;
        c.setting.currentGlobals.Remove(key);
        return r.v;
    }

    public static Variable pstash_at_key(P6any st, string key) {
        return Kernel.UnboxAny<StashCursor>(st).Raw(key, null);
    }

    public static Variable pstash_bind_key(P6any st, string key, Variable to) {
        return Kernel.UnboxAny<StashCursor>(st).Raw(key, to);
    }

    internal static Frame TEMP_C(Frame th) {
        ((Variable)th.outer.lex0).Store((P6any)th.outer.lex1);
        return th.Return();
    }

[ImplicitConsts] public static Variable temporize(Constants c, Variable v, Frame fr, int mode) {
        int type = (mode & 1) != 0 ? LeaveHook.UNDO : LeaveHook.UNDO + LeaveHook.KEEP;
        if ((mode & 2) != 0) {
            fr.PushLeave(type, v.Fetch());
        }
        else if (v.List) {
            fr.PushLeave(type, Kernel.RunInferior(v.Fetch().InvokeMethod(
                    Kernel.GetInferiorRoot(), "TEMP",
                    new Variable[] { v }, null)).Fetch());
        }
        else {
            // this is quite dubious really, Frame and LexPad should be separated
            Frame o = new Frame(null, null, c.setting.TEMP_SI, null);
            o.lex0 = v;
            o.lex1 = v.Fetch();
            fr.PushLeave(type, Kernel.MakeSub(c.setting.TEMP_SI, o));
        }

        return v;
    }

    internal static Frame RunCATCH_C(Frame th) {
        // ENTRY lex0 : CATCH lambda (decontainerized)
        // lex1 : exception payload (@! Array)
        // EXIT ret : new @!; will catch if false
        // LEX lex2 : @*unhandled
        // lex3 : $current
        // lex4 : @! iterator
        // note, compiler munges catch/control lambdas to return True
        // if exitted via succeed
        // note2, any exception thrown from under RunCATCH_I will be caught
        // and pushed onto @*unhandled along with $current, and next;

        // -> $handler, @! { #0
        // my @*unhandled;
        // for @! -> $current { #N=1 R=2
        // $handler.($current) || push @*unhandled, $current
        // } #L=4
        // @*unhandled;
        // }

        // $! will be set to munged @! if we return nothing

        Variable t1, t2;
        VarDeque u1;
        P6any v1;
        switch (th.ip) {
            case 0:
                th.lex2 = Kernel.CreateArray();
                t1 = (Variable)th.lex1;
                th.lex4 = t1.Fetch().mo.mro_raw_iterator.Get(t1);
                goto case 1;

            case 1:
                u1 = (VarDeque)th.lex4;
                if (!Kernel.IterHasFlat(u1, true)) goto case 4;
                th.lex3 = u1.Shift();
                goto case 2;

            case 2:
                t1 = (Variable)th.lex3;
                v1 = (P6any)th.lex0;
                th.ip = 3;
                return v1.Invoke(th, new Variable[] { t1 }, null);

            case 3:
                t1 = (Variable)th.resultSlot;
                if (t1.Fetch().mo.mro_raw_Bool.Get(t1))
                    goto case 1; // yay handled
                t1 = (Variable)th.lex3;
                t2 = (Variable)th.lex2;
                t2.Fetch().mo.mro_push.Invoke(t2, new Variable[] { t1 });
                goto case 1;

            case 4:
                th.caller.resultSlot = th.lex2;
                return th.Return();

            default:
                return Kernel.Die(th, "Invalid IP");
        }
    }

    internal static string DumpVar(Variable v) {
        string ret;
        try {
            Variable p = Kernel.RunInferior(v.Fetch().InvokeMethod(
                Kernel.GetInferiorRoot(), "perl", new Variable[] { v }, null));
            ret = p.Fetch().mo.mro_raw_Str.Get(p);
        } catch (Exception ex) {
            ret = "(stringification failed: " + ex.ToString() + ")";
        }
        return ret;
    }

    public static Variable dir(string s) {
        string[] raw = Directory.GetFileSystemEntries(s);
        string[] forperl = new string[raw.Length + 2];
        forperl[0] = "."; forperl[1] = "..";
        for (int i = 0; i < raw.Length; i++) {
            int ix = raw[i].LastIndexOf(Path.DirectorySeparatorChar);
            forperl[i+2] = (ix >= 0) ? raw[i].Substring(ix+1) : raw[i];
        }
        return BoxLoS(forperl);
    }

    public static Thread start_p6_thread(P6any sub) {
        Frame th = Kernel.GetTopFrame();
        th.MarkSharedChain();
        Thread thr = new Thread(delegate () {
                Kernel.SetupThreadParent(th);
                Kernel.RunInferior(sub.Invoke(Kernel.GetInferiorRoot(),
                        Variable.None, null));
            });
        thr.Start();
        return thr;
    }

    public static Variable sleep(double secs) {
        Stopwatch stopwatch = new Stopwatch();

        stopwatch.Start();
        Thread.Sleep((int)(secs * 1000.0));
        stopwatch.Stop();

        return MakeFloat(stopwatch.Elapsed.TotalSeconds);
    }

    public static void pun_helper(Variable pun, Variable vname, Frame fr) {
        string name = vname.Fetch().mo.mro_raw_Str.Get(vname);
        fr.pos[0] = pun;
        fr.curDisp = new DispatchEnt(pun.Fetch().mo.FindMethod(name));
    }

    public static Frame dispatch_fromtype(Frame th) {
        Variable[] npos = new Variable[th.pos.Length - 2];
        STable from = th.pos[1].Fetch().mo;
        string name = th.pos[2].Fetch().mo.mro_raw_Str.Get(th.pos[2]);
        npos[0] = th.pos[0];
        Array.Copy(th.pos, 3, npos, 1, npos.Length - 1);

        if (!npos[0].Fetch().Does(from)) {
            return Kernel.Die(th, "Cannot dispatch to a method on " +
                from.name + " because it is not inherited or done by " +
                npos[0].Fetch().mo.name);
        }

        var de = from.FindMethod(name);
        if (de != null) {
            return de.info.SetupCall(th.Return(), de.outer, de.ip6,
                        npos, th.named, false, de);
        } else {
            return Kernel.Die(th, "Unable to resolve method " + name + " via " +
                    from.name);
        }
    }

    public static void exit(int code) {
        // Hack - at least some versions of Mono don't fire ProcessExit
        // on an explicit Exit() call
        Compartment.BeforeExit(null, null);
        Environment.Exit(code);
    }

    public static P6any repr_clone(P6any obj, VarHash mods) {
        obj = obj.ReprClone();
        if (!mods.IsNonEmpty) return obj;

        Variable arg;
        foreach (STable m in obj.mo.mo.mro) {
            foreach (P6how.AttrInfo ai in m.mo.local_attr) {
                if ((ai.flags & P6how.A_PUBLIC) == 0) continue;
                if (!mods.TryGetValue(ai.name.Substring(2), out arg)) continue;

                EstablishSlot(obj, ai, arg);
            }
        }

        return obj;
    }

[ImplicitConsts] public static Variable mixin(Constants c, P6any obj, Variable role_list, Variable init,
            Variable newtype) {
        VarDeque iter = start_iter(role_list);
        List<STable> roles = new List<STable>();
        while (Kernel.IterHasFlat(iter, true))
            roles.Add(iter.Shift().Fetch().mo);

        STable n = new STable(obj.mo.name + "+" + Kernel.JoinS(",", roles));

        n.how = Kernel.BoxAny<STable>(n, obj.mo.how).Fetch();
        n.typeObj = n.initObj = new P6opaque(n);
        ((P6opaque)n.typeObj).slots = null;

        n.mo.superclasses.Add(obj.mo);
        n.mo.local_roles = roles;
        n.mo.Compose();
        newtype.Store(n.typeObj);

        string aname = null;
        if (init != c.setting.AnyP) {
            if (!obj.IsDefined())
                throw new NieczaException("Cannot initialize a slot when mixing into a type object");
            if (n.mo.local_attr.Count != 1 || (n.mo.local_attr[0].flags & P6how.A_PUBLIC) == 0)
                throw new NieczaException("Role(s) being mixed in do not define precisely one, public attribute");
            aname = n.mo.local_attr[0].name;
        }

        if (obj.IsDefined()) {
            obj.ChangeType(n);

            BuildMostDerived(obj);
            if (aname != null)
                Kernel.Assign((Variable)obj.GetSlot(n, aname), init);
            return obj;
        } else {
            return n.typeObj;
        }
    }

[ImplicitConsts] public static Variable dualvar(Constants c, Variable obj, Variable type, Variable str) {
        P6any nobj = obj.Fetch().ReprClone();
        nobj.ChangeType(type.Fetch().mo);
        nobj.SetSlot(c.setting.PseudoStrMO, "$!value",
                Kernel.UnboxAny<string>(str.Fetch()));
        return nobj;
    }

    public static void EstablishSlot(P6any n, P6how.AttrInfo ai,
            Variable vx) {
        Variable obj;
        if ((ai.flags & P6how.A_TYPE) == P6how.A_SCALAR) {
            if (ai.type == null)
                obj = Kernel.NewMuScalar(
                    vx != null ? vx.Fetch() : Compartment.Top.AnyMO.typeObj);
            else
                obj = Kernel.NewRWScalar(ai.type,
                    vx != null ? vx.Fetch() : ai.type.initObj);
        } else {
            obj = (ai.flags & P6how.A_HASH) != 0 ?
                Kernel.CreateHash() : Kernel.CreateArray();
            if (vx != null) {
                // https://github.com/sorear/niecza/issues/104
                if (!vx.List)
                    vx = Kernel.NewRWListVar(vx.Fetch());
                Kernel.Assign(obj, vx);
            }
        }
        n.SetSlot(ai.owner, ai.name, obj);
    }


    static void BuildMostDerived(P6any obj) {
        P6any build = null;
        foreach (P6how.MethodInfo m in obj.mo.mo.lmethods) {
            if (m.Name() == "BUILD" && m.flags == P6how.V_SUBMETHOD)
                build = m.impl;
        }

        foreach (P6how.AttrInfo ai in obj.mo.mo.local_attr) {
            Variable vx = null;
            if (ai.init != null) {
                vx = Kernel.RunInferior(ai.init.Invoke(Kernel.GetInferiorRoot(),
                    new [] { obj }, null));
            }
            EstablishSlot(obj, ai, vx);
        }

        if (build != null)
            Kernel.RunInferior(build.Invoke(Kernel.GetInferiorRoot(),
                new Variable[] { obj }, null));
    }

    public static Variable enum_mixin_role(string name, P6any meth) {
        STable r = new STable('{' + name + '}');
        r.mo.FillRole(new STable[0], null);
        r.typeObj = r.initObj = new P6opaque(r);
        r.mo.AddMethod(0, name, meth);
        r.mo.Revalidate();
        r.SetupVTables();
        return r.typeObj;
    }

    // TODO: merge
    public static Variable cat_mixin_role(string name, P6any meth) {
        STable r = new STable('{' + name + '}');
        r.mo.FillRole(new STable[0], null);
        r.typeObj = r.initObj = new P6opaque(r);
        r.mo.AddMethod(P6how.M_MULTI, name, meth);
        r.mo.Revalidate();
        r.SetupVTables();
        return r.typeObj;
    }

    public static Variable type_mixin_role(Variable type, Variable meth) {
        STable stype = type.Fetch().mo;
        string name = stype.name;
        STable r = new STable("ANON");

        r.mo.FillRole(new STable[0], null);
        r.typeObj = r.initObj = new P6opaque(r);
        r.mo.AddMethod(0, name, meth.Fetch());
        r.mo.AddMethod(P6how.V_PRIVATE, name, meth.Fetch());
        r.mo.AddAttribute(name, P6how.A_PUBLIC, null, stype);
        r.mo.Revalidate();
        return r.typeObj;
    }

    public static void raise(string sig) { PosixWrapper.raise(sig); }

    public static Variable dyngetattr(Variable obj, Variable ty, Variable name) {
        string sname = Kernel.UnboxAny<string>(name.Fetch());
        return (Variable)obj.Fetch().GetSlot(ty.Fetch().mo, sname);
    }

[ImplicitConsts] public static Variable is_role(Constants c, Variable o) {
        int rty = o.Fetch().mo.mo.type;
        return (rty == P6how.ROLE || rty == P6how.CURRIED_ROLE || rty == P6how.PARAMETRIZED_ROLE) ? c.setting.TrueV : c.setting.FalseV;
    }

    public class Blackhole : Variable {
        P6any value;

        private Blackhole() {}
        public Blackhole(P6any value) { this.value = value; }

        public override P6any Fetch() { return value; }
        public override void Store(P6any v) { }

        public override void Freeze(Niecza.Serialization.FreezeBuffer fb) {
            fb.Byte((byte)Niecza.Serialization.SerializationCode.Blackhole);
            fb.ObjRef(value);
        }
        internal static object Thaw(Niecza.Serialization.ThawBuffer tb) {
            var n = new Blackhole();
            tb.Register(n);
            n.value = (P6any) tb.ObjRef();
            return n;
        }
    }

    public static Variable blackhole(Variable o) {
        return new Blackhole(o.Fetch());
    }

    public static Variable sig_params(P6any sig) {
        VarDeque items = new VarDeque();
        items.PushN(((Signature)sig).parms);
        return Kernel.NewRWListVar(MakeList(items, new VarDeque()));
    }

    public static string code_name(P6any obj) {
        return Kernel.GetInfo(obj).name;
    }

[ImplicitConsts] public static P6any code_signature(Constants c, P6any obj) {
        return Kernel.GetInfo(obj).sig ?? c.setting.AnyMO.typeObj;
    }

    public static Variable code_candidates(P6any sub) {
        // Not foolproof
        SubInfo si = Kernel.GetInfo(sub);
        VarDeque items = new VarDeque();
        if (si.param != null && si.param[0] is P6any[]) {
            foreach (P6any cand in (P6any[])si.param[0])
                if (cand != null)
                    items.Push(cand);
        } else {
            items.Push(sub);
        }
        return Kernel.NewRWListVar(MakeList(items, new VarDeque()));
    }

    public static int param_flags(P6any param) {
        return ((Parameter)param).flags;
    }

    public static Variable param_names(P6any param) {
        return BoxLoS(((Parameter)param).names ?? new string[0]);
    }

[ImplicitConsts] public static Variable param_type(Constants c, P6any param) {
        return (((Parameter)param).type ?? c.setting.AnyMO).typeObj;
    }

[ImplicitConsts] public static P6any param_subsig(Constants c, P6any param) {
        var p = param as Parameter;
        if (p.post_constraints != null) {
            foreach (object o in p.post_constraints) {
                if (o is Signature)
                    return (P6any)o;
            }
        }
        return c.setting.AnyMO.typeObj;
    }

    public static Variable param_value_constraints(P6any param) {
        var p = param as Parameter;
        VarDeque items = new VarDeque();
        if (p.post_constraints != null) {
            foreach (object o in p.post_constraints) {
                if (o is Variable)
                    items.Push((Variable)o);
            }
        }
        return Kernel.NewRWListVar(MakeList(items, new VarDeque()));
    }

    public static string param_name(P6any param) {
        return ((Parameter)param).name;
    }

    public static Frame code_accepts_capture(Frame th, P6any code, P6any cap) {
        var setting = th.info.setting;
        return Kernel.GetInfo(code).SetupCall(th, Kernel.GetOuter(code), code,
            (Variable[])cap.GetSlot(setting.CaptureMO, "$!positionals"),
            (VarHash)cap.GetSlot(setting.CaptureMO, "$!named"),
            true, null);
    }

    public static System.IO.TextReader treader_stdin() {
        return new System.IO.StreamReader(Console.OpenStandardInput(), Console.InputEncoding);
    }

[TrueGlobal] internal static StreamWriter stdout =
        new StreamWriter(Console.OpenStandardOutput(), Console.OutputEncoding);
[TrueGlobal] internal static StreamWriter stderr =
        new StreamWriter(Console.OpenStandardError(), Console.OutputEncoding);
    public static System.IO.TextWriter twriter_stdout() {
        stdout.AutoFlush = true; return stdout;
    }

    public static System.IO.TextWriter twriter_stderr() {
        stderr.AutoFlush = true; return stderr;
    }

    public static int ref_hash(P6any o) { return RuntimeHelpers.GetHashCode(o); }

    public static Frame ind_method_call(Frame th, StashCursor root,
            string nm, P6any cap) {
        int cut = nm.LastIndexOf("::");
        var setting = th.info.setting;
        var pos = (Variable[]) cap.GetSlot(setting.CaptureMO, "$!positionals");
        var nam = (VarHash) cap.GetSlot(setting.CaptureMO, "$!named");

        if (cut < 0) {
            return pos[0].Fetch().InvokeMethod(th, nm, pos, nam);
        } else {
            var from = root.Indirect(nm.Substring(0, cut), false, null)
                .Fetch().mo;
            var name = nm.Substring(cut+2);

            // some code copied from dispatch_fromtype
            if (!pos[0].Fetch().Does(from)) {
                return Kernel.Die(th, "Cannot dispatch to a method on " +
                    from.name + " because it is not inherited or done by " +
                    pos[0].Fetch().mo.name);
            }

            var de = from.FindMethod(name);
            if (de != null) {
                return de.info.SetupCall(th, de.outer, de.ip6,
                            pos, nam, false, de);
            } else {
                return Kernel.Die(th, "Unable to resolve method " + name +
                        " via " + from.name);
            }
        }
    }

    public static byte[] encode(string inp, string enc) {
        return Encoding.GetEncoding(enc).GetBytes(inp);
    }

    public static string decode(byte[] inp, string enc) {
        return Encoding.GetEncoding(enc).GetString(inp);
    }

    public static int blob_len(byte[] inp) {
        return inp.Length;
    }

    public static Socket socket_new(int family, int type, int proto) {
        return new Socket( (AddressFamily)family, (SocketType)type,
                (ProtocolType)proto );
    }

    public static byte[] socket_read(Socket from, int ct) {
        byte[] buf = new byte[ct];
        int rct = from.Receive(buf);
        Array.Resize(ref buf, rct);
        return buf;
    }

    public static void socket_write(Socket sock, byte[] data) {
        sock.Send(data);
    }

    public static void socket_close(Socket sock) {
        sock.Shutdown( SocketShutdown.Both ); // XXX perhaps should be separate
        sock.Close();
    }

    public static void socket_connect(Socket sock, string host, int port) {
        sock.Connect(host, port);
    }

    public static void socket_bind(Socket sock, string host, int port) {
        System.Net.IPAddress addr;
        if (host.Length == 0 || !System.Net.IPAddress.TryParse (host, out addr))
            addr = System.Net.Dns.GetHostEntry (host).AddressList[0];

        sock.Bind(new System.Net.IPEndPoint(addr, port));
    }

    public static void socket_listen(Socket sock, int log) {
        sock.Listen(log);
    }

    public static Socket socket_accept(Socket sock) {
        return sock.Accept();
    }
}
Something went wrong with that request. Please try again.