Skip to content
This repository
tree: 15c5b26206
Fetching contributors…

Cannot retrieve contributors at this time

file 4209 lines (3730 sloc) 144.122 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 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209
# vim: ft=perl6 fdm=marker
my module CORE;
use MONKEY_TYPING;

# The contract for 'is pure' is that, when provided a set of positional and
# named arguments all of which are of immutable types, an immutable object
# is returned which depends only on the arguments, not on any free variables.
# In particular, any function which necessarily takes or returns a List
# is excluded.
# However, slurpy arguments are ok. If an object is claimed to be immutable
# but implements variable methods for Bool,Str,Int,etc, no rules apply.
#
# There are three senses of 'immutability' currently used in Niecza. For an
# expression, being immutable means that the same Variable will always be
# returned (that is, =:=) and there are no side effects, so that expression
# can effectively be constant-folded. const_value will return either a
# Value downvalue or Nil depending on (an approximation to) such immutability.
#
# For values, immutability is measured by the 'immutable' method, and is true
# if none of the object's state, as seen by perl, eqv, or other such accesors,
# can be changed. Variables are immutable if they are read-only and their
# value is immutable. Note that an immutable expression can return a mutable
# variable!
#
# Known suboptimalities of this system: it doesn't make a whole lot of sense
# to be forbidding (3 => 5) but, but allowing (3 => $x) but. Also, we could
# usefully fold some cases like "foo" => &bar, even though &bar is not
# immutable.

# Predeclarations of types {{{
my class Mu { ... }
my grammar Cursor { ... }
my class Regex { ... }
my class Num { ... }
my class Str { ... }
my class Code { ... }
my class Match { ... }
my class List { ... }
my class Array { ... }
my class FatRat { ... }
my class Junction { ... }
my class Enum { ... }
my class Range { ... }
my class Whatever { ... }
my class IO { ... }
my class ObjAt { ... }
my class Proxy { ... }
my class KeySet { ... }
my class Bag { ... }
my class KeyBag { ... }
grammar Niecza::NumSyntax { ... }
# }}}
# Important inlinable definitions {{{
proto infix:<+>($?,$?) is pure is Niecza::builtin('plus',2,2) {*}
multi infix:<+>($l,$r) { $l + $r }

proto infix:<->($?,$?) is pure is Niecza::builtin('minus',2,2) {*}
multi infix:<->($l,$r) { $l - $r }

proto infix:<*> is pure is Niecza::builtin('mul',2,2) is Niecza::absprec<u=> ($?,$?) {*}
multi infix:<*>($l,$r) { $l * $r }
proto infix:</> is pure is Niecza::builtin('divide',2,2) is equiv<*> ($?,$?) {*}
multi infix:</>($l,$r) { $l / $r }
proto infix:<%> is pure is Niecza::builtin('mod',2,2) is equiv<*> ($?,$?) {*}
multi infix:<%>($l,$r) { $l % $r }
proto infix:<**> is pure is Niecza::builtin('pow',2,2) is Niecza::absprec<w= right> ($?,$?) {*}
multi infix:<**>($l,$r) { $l ** $r }

# sub infix:<gcd>($l,$r) is Niecza::builtin('gcd',2,2) { $l gcd $r }
sub infix:<gcd>($l,$r) is pure { Q:CgOp { (gcd {$l.Int} {$r.Int}) } }
sub infix:<lcm>($l,$r) is pure {
    my $l-int = $l.Int.abs;
    my $r-int = $r.Int.abs;
    $l-int div ($l-int gcd $r-int) * $r-int;
}

sub next ($x?) { _lexotic(1, $x, ()) }
sub last ($x?) { _lexotic(2, $x, ()) }
sub redo ($x?) { _lexotic(3, $x, ()) }
sub return(\|@pcl) is return-pass { Q:CgOp {
    (control 4 (null frame) (int -1) (null str) {@pcl.unwrap-single})
} }
sub return-rw(\|@pcl) is return-pass { Q:CgOp {
    (control 4 (null frame) (int -1) (null str) {@pcl.unwrap-single})
} }
sub succeed(\|@pcl) {
    Q:CgOp { (control 6 (null frame) (int -1) (null str) {@pcl.unwrap-single}) }
}
sub proceed() { proceed }
sub term:<proceed>() {
    Q:CgOp { (control 7 (null frame) (int -1) (null str) {()}) }
}

sub take(\|@pcl) { Q:CgOp { (take {@pcl.unwrap-single}) } }
sub take-rw(\|@pcl) { Q:CgOp { (take {@pcl.unwrap-single}) } }

sub infix:<&> is pure is Niecza::absprec<q= list> is iffy
    (\|$p) { Junction.from-parcel(0, $p) }
sub infix:<|> is pure is Niecza::absprec<p= list> is iffy
    (\|$p) { Junction.from-parcel(3, $p) }
sub infix:<^> is pure is equiv<|> (\|$p) { Junction.from-parcel(2, $p) }
sub all (*@p) is pure { all @p }
sub none (*@p) is pure { none @p }
sub one (*@p) is pure { one @p }
sub any (*@p) is pure { any @p }

proto infix:<< == >>($?,$?) is pure is Niecza::builtin('numeq',2,2)
    is Niecza::absprec<m= chain> is diffy is iffy {*}
proto infix:<< != >>($?,$?) is pure is Niecza::builtin('numne',2,2)
    is equiv<==> {*}
proto infix:<< < >>($?,$?) is pure is Niecza::builtin('numlt',2,2)
    is equiv<==> {*}
proto infix:<< > >>($?,$?) is pure is Niecza::builtin('numgt',2,2)
    is equiv<==> {*}
proto infix:<< <= >>($?,$?) is pure is Niecza::builtin('numle',2,2)
    is equiv<==> {*}
proto infix:<< >= >>($?,$?) is pure is Niecza::builtin('numge',2,2)
    is equiv<==> {*}

multi infix:<< == >>($l,$r) { $l == $r }
multi infix:<< != >>(\l,\r) { l != r } # Needs special handling of junctions
multi infix:<< < >>($l,$r) { $l < $r }
multi infix:<< > >>($l,$r) { $l > $r }
multi infix:<< <= >>($l,$r) { $l <= $r }
multi infix:<< >= >>($l,$r) { $l >= $r }

proto infix:<ge>($?,$?) is Niecza::builtin('strge',2,2) is equiv<==> is pure {*}
proto infix:<gt>($?,$?) is Niecza::builtin('strgt',2,2) is equiv<==> is pure {*}
proto infix:<le>($?,$?) is Niecza::builtin('strle',2,2) is equiv<==> is pure {*}
proto infix:<lt>($?,$?) is Niecza::builtin('strlt',2,2) is equiv<==> is pure {*}
proto infix:<eq>($?,$?) is Niecza::builtin('streq',2,2) is equiv<==> is pure {*}
proto infix:<ne>($?,$?) is Niecza::builtin('strne',2,2) is equiv<==> is pure {*}

multi infix:<ge>($s1, $s2) { $s1 ge $s2 }
multi infix:<gt>($s1, $s2) { $s1 gt $s2 }
multi infix:<le>($s1, $s2) { $s1 le $s2 }
multi infix:<lt>($s1, $s2) { $s1 lt $s2 }
multi infix:<eq>($s1, $s2) { $s1 eq $s2 }
multi infix:<ne>(\s1, \s2) { s1 ne s2 } # Needs special handling of junctions

sub infix:<,> is Niecza::builtin('comma',0) is pure is Niecza::absprec<g= list> (\|$t) { Q:CgOp { (newrwlistvar (@ {$t})) }; }
proto infix:<=>($?,$?) is Niecza::absprec<i= right> is Niecza::builtin('assign',2,2) {*}
multi infix:<=>(\a, \b) { a = b }

sub chars($str) is pure is Niecza::builtin('chars',1,1) { chars($str) }
sub codes($str) is pure is Niecza::builtin('codes',1,1) { codes($str) }

sub defined(\x) is pure is Niecza::builtin('defined',1,1) { defined(x) }

sub prefix:<~>(\v) is pure is Niecza::builtin('asstr', 1, 1) { ~v }
sub prefix:<?>(\v) is pure is Niecza::builtin('asbool', 1, 1) { ?v }
sub prefix:<->(\v) is pure is Niecza::builtin('negate', 1, 1) { -v }
sub prefix:<+>(\v) is pure is Niecza::builtin('num', 1, 1) { +v }
sub prefix:<!>(\v) is pure is Niecza::builtin('not', 1, 1) { !v }

sub not(\v) is pure is Niecza::builtin('not', 1, 1) { not(v) }
sub so(\v) is pure is Niecza::builtin('asbool', 1, 1) { so v }

proto infix:<+&> is pure is Niecza::builtin('numand',2,2) is equiv<*> ($?,$?) {*}
proto infix:<+|>($?,$?) is pure is Niecza::builtin('numor',2,2) {*}
proto infix:<+^>($?,$?) is pure is Niecza::builtin('numxor',2,2) {*}
proto infix:<< +< >>($?,$?) is equiv<*> is pure
    is Niecza::builtin('numlshift',2,2) {*}
proto infix:<< +> >>($?,$?) is equiv<*> is pure
    is Niecza::builtin('numrshift',2,2) {*}
proto prefix:<< +^ >>(|) is Niecza::builtin('numcompl',1,1) is pure {*}

multi infix:<+&> ($x, $y) { $x +& $y }
multi infix:<+|>($x, $y) { $x +| $y }
multi infix:<+^>($x, $y) { $x +^ $y }
multi infix:<< +< >>($x, $y) { $x +< $y }
multi infix:<< +> >>($x, $y) { $x +> $y }
multi prefix:<< +^ >>($x) { +^$x }

sub infix:<< => >>($k, Mu $v) is equiv<=> is pure
    is Niecza::builtin('pair', 2, 2) { $k => $v }

sub postcircumfix:<[ ]>(\container, |stuff) {
    container.postcircumfix:<[ ]>(|stuff)
}

sub postcircumfix:<{ }>(\container, |stuff) {
    container.postcircumfix:<{ }>(|stuff)
}

sub push(@array, *@stuff) is Niecza::builtin('push', 1) { @array.push(@stuff) }
sub unshift(@array, *@stuff) is Niecza::builtin('unshift', 1) { @array.unshift(@stuff) }
sub pop(@array) is Niecza::builtin('pop', 1, 1) { @array.pop }
sub shift(@array) is Niecza::builtin('shift', 1, 1) { @array.shift }
multi sub splice(@array is rw) { @array.splice() }
multi sub splice(@array is rw, *@values) { @array.splice(@values) }
multi sub splice(@array is rw, $offset, *@values) { @array.splice($offset,Inf,@values); }
multi sub splice(@array is rw, $offset, $size, *@values) { @array.splice($offset, $size, @values); }

sub grep(Mu $filter, *@items) is Niecza::builtin('grep',1) { grep($filter, @items) }
sub map($callback, *@items) is Niecza::builtin('map',1) { map($callback, @items) }

sub _array_constructor(\parcel) is Niecza::builtin('array_constructor', 1,
    1) { _array_constructor(parcel) }

sub make($x) is Niecza::builtin('make', 1, 1) { make $x }

# these are defined in terms of other operators so they go at the end
sub prefix:<--> is Niecza::absprec<x= unary non> is Niecza::builtin('predec',1,1) ($v is rw) { $v = $v.pred; $v }
sub prefix:<++> is equiv<--> is Niecza::builtin('preinc',1,1) ($v is rw) { $v = $v.succ; $v }
sub postfix:<--> is Niecza::absprec<x= unary non> is Niecza::builtin('postdec',1,1) ($v is rw) { my $old = $v; $v = $v.pred; $old }
sub postfix:<++> is equiv<--> is Niecza::builtin('postinc',1,1) ($v is rw) { my $old = $v; $v = $v.succ; $old }
sub substr(\str, $start, $len?, $repl?) is Niecza::builtin('substr_ro3', 3, 3) is pure {
    $start := $start(chars str) if $start.^does(Code);
    $len := $len.^does(Code) ?? ($len(chars str) - $start) !!
        $len // (chars(str) - $start);
    defined($repl) ??
        substr-rw(str, $start, $len) = $repl !!
        substr(str, $start, $len)
}

# Right now, this compltely duplicates the code of substr. substr needs to be fixed so
# that it isn't an lvalue, and the code below should remain substr-rw.
sub substr-rw(\str, $start, $len?, $repl?) is Niecza::builtin('substr3', 3, 3) is pure {
    $start := $start(chars str) if $start.^does(Code);
    $len := $len.^does(Code) ?? ($len(chars str) - $start) !!
        $len // (chars(str) - $start);
    defined($repl) ??
        substr-rw(str, $start, $len) = $repl !!
        substr-rw(str, $start, $len)
}

# not actually inlined but needed for constant i
sub sqrt($x) is pure { Q:CgOp { (sqrt {$x}) } }

sub Niecza::toggle_mono_trace() { Q:CgOp { (prog (raise (s "SIGUSR2")) {0}) } }

sub infix:<X>(\|$pcl) is Niecza::absprec<f= list> {
    Q:CgOp { (cross (b 0) (unbox fvarlist (@ {$pcl}))) }
}
sub infix:<Z>(\|$pcl) is equiv<X> {
    Q:CgOp { (zip (b 0) (unbox fvarlist (@ {$pcl}))) }
}
sub zipop(\|$pcl) {
    Q:CgOp { (zip (b 1) (unbox fvarlist (@ {$pcl}))) }
}
sub crossop(\|$pcl) {
    Q:CgOp { (cross (b 1) (unbox fvarlist (@ {$pcl}))) }
}
# }}}
# Fundamental types {{{
my constant True = 1.Bool;
my constant False = 0.Bool;
my class Mu {
    method head() { @(self).head }
    method flattens(\:) {
        Q:CgOp { (box Bool (var_islist {self})) }
    }
    method typename() { # should be ^name
        Q:CgOp { (box Str (obj_typename (@ {self}))) }
    }
    method gist() { defined(self) ?? self.perl !! self.typename ~ '()' }
    method say() { self.gist.say }
    method print() { $*OUT.print(self) }
    method Stringy() { self.Str }
    method Str() {
        if defined(self) {
            my $tn := Q:CgOp { (box Str (obj_typename (@ {self}))) };
            $tn ~ "()<instance>"
        } else {
            warn "Use of uninitialized value in string context";
            ""
        }
    }
    method succ() { defined(self) ?? die("cannot increment a value of type {self.typename()}") !! 1 }
    method pred() { defined(self) ?? die("cannot decrement a value of type {self.typename()}") !! -1 }
    method notdef() { !defined(self) }
    method ACCEPTS(\x) { defined(self) ?? self === x !! x.^does(self) }
    method perl() { defined(self) ?? "{self.typename}.new(...)" !! self.typename }
    method so() { ?self }
    method not() { !self }
    method bless($, *%_) { Q:CgOp { (default_new (@ {self}) (unbox varhash (@ {%_}))) } }
    method CREATE() { Q:CgOp { (obj_newblank (obj_llhow (@ {self}))) } }
    multi method new(*%_) { Q:CgOp { (default_new (@ {self}) (unbox varhash (@ {%_}))) } }
    method clone(*%_) { Q:CgOp { (repr_clone (@ {self}) (unbox varhash (@ {%_}))) } }
    method dispatch:<::>(|) { Q:CgOp { (dispatch_fromtype) } }
    method immutable() { !defined(self) }
    method take() { take self }
    multi method WHICH() { ObjAt.new(str => '', ref => self) }
}

my class Any is Mu {
    method isa(\other) { self.^isa(other) }
    method does(\other) { self.^does(other) }
    method can($method) { self.^can($method) }
    method flat() { @(self) }
    method Numeric() {
        die "Cannot use value like $.typename as a number" if defined(self);
        warn "Use of uninitialized value in numeric context";
        0;
    }

    # This needs a way of taking a user-defined comparison
    # specifier, but AFAIK nothing has been spec'd yet.
    # CHEAT: Almost certainly should be hashed on something
    # other than the stringification of the objects.
    method uniq() {
        my %seen;
        gather for @(self) {
             unless %seen{$_} {
                 take $_;
                 %seen{$_} = 1;
             }
        }
    }

    method kv() {
        my $i = 0;
        gather for @(self) -> \value {
            my $key = $i++;
            take $key;
            take value;
        }
    }

    method keys() {
        my $i = 0;
        gather for @(self) -> $value { #OK not used
            my $key = $i++;
            take $key;
        }
    }

    method values() {
        gather for @(self) -> \value {
            take value;
        }
    }

    method pairs() {
        self.kv.map(-> $key, \value { $key => value; });
    }

    # NOTE: These functions are called by the default postcircumfixes, *after*
    # processing slicing and adverbs. So you should probably override these
    # instead. However, for speed, Array, Hash et al override the
    # postcircumfixes instead, and so you can't change their behavior using
    # delete_key and company in subclasses.
    method delete_key($) {
        die "Cannot use hash access on an object of type {self.WHAT.perl}"
    }
    method exists_key($) {
        die "Cannot use hash access on an object of type {self.WHAT.perl}"
    }
    method at_key($) {
        die "Cannot use hash access on an object of type {self.WHAT.perl}"
    }
    method bind_key($, $) {
        die "Cannot use hash access on an object of type {self.WHAT.perl}"
    }

    method at_pos($key) { self.list.at_pos($key) }
    method bind_pos($, $) {
        die "Cannot use hash access on an object of type {self.WHAT.perl}"
    }

    method grep(Mu $sm) { grep $sm, @(self) }
    method map($func) { map $func, @(self) }
    method for (&cb) {
        Q:CgOp {
            (rnull (letn it (unbox vvarlist (@ {self.iterator}))
                  cb (@ {&cb})
              (whileloop 0 0 (iter_hasflat (l it))
                (sink (subcall (l cb) (vvarlist_shift (l it)))))))
        };
    }
    method elems() { self.flat.elems }
    method iterator() { self.flat.iterator }
    method join($sep = "") { self.flat.join($sep) }
    method chrs() { chrs(@(self)) }

    method any() { any @(self) }
    method none() { none @(self) }
    method all() { all @(self) }
    method one() { one @(self) }
    method sort($cmp = &infix:<cmp>) { @(self).sort($cmp) }
    method first(Mu $filter) { for @(self) { return $_ if $_ ~~ $filter } }

    method !butWHENCE($cr) {
        Q:CgOp { (newvsubvar (class_ref mo Any) (@ {$cr}) (@ {self})) }
    }

    method hash() { anon %hash = @(self) }

    multi method roll($num = 1) {
        return { self[floor(self.elems.rand)] } xx * if $num ~~ Whatever;
        return self[floor(self.elems.rand)] if $num == 1;
        return map { self[floor(self.elems.rand)] }, ^$num;
    }

    multi method pick($num is copy = 1) {
        my @l = @(self);

        if ($num ~~ Whatever) {
            $num = @l.elems;
        } elsif ($num == 1) {
            return @l[floor(@l.elems.rand)];
        }

        my $number-elements = @l.elems;
        gather {
            while ($num > 0 and $number-elements > 0) {
                my $idx = floor($number-elements.rand());
                my $old = @l[$idx];
                @l[$idx] = @l[--$number-elements];
                take $old;
                --$num;
            }
        }
    }

    method rotate($n = 1) { @(self).rotate($n) }
    method min($cmp = &infix:<cmp>) { @(self).min($cmp) }
    method max($cmp = &infix:<cmp>) { @(self).max($cmp) }
    method minmax($cmp = &infix:<cmp>) { @(self).minmax($cmp) }

    method reduce($expression) {
        my $result;
        my $first = 1;
        for @(self) -> $cur {
            if $first {
                $result = $cur;
                $first = 0;
                next;
            }
            $result = &$expression($result, $cur);
        }
        $result;
    }
}

sub Niecza::autopun($pun, $name) {
    -> | { Q:CgOp { (rnull (pun_helper {$pun} {$name} (callframe))) }; nextsame }
}

sub IMMUTABLE(\x) { Q:CgOp { (ternary (var_is_rw {x}) {False} {x.immutable}) } }

my class Cool {
    method FatRat () { Niecza::NumSyntax.str2num(~self, :fatrat) }
    method Rat($eps = 1e-6) { Q:CgOp { (rat_approx {self} {$eps}) } }
    method Int() { Q:CgOp { (coerce_to_int {self}) } }
    method Num() { Q:CgOp { (coerce_to_num {self}) } }
    method IO() { self.Str.IO }
    method abs() { abs self }
    method floor() { floor self }
    method ceiling() { ceiling self }
    method round($scale = 1) { round self, $scale }
    method truncate() { truncate self }
    method sqrt() { sqrt self }
    method sign() { sign self }
    method conj() { self }
    multi method exp() { Q:CgOp { (exp {self}) } }
    multi method exp($base) { $base ** self }
    method ln() { Q:CgOp { (ln {self}) } }
    multi method log() { self.ln }
    multi method log($base) { self.ln / $base.ln }
    method log10() { self.ln / 10.ln }
    method sin() { Q:CgOp { (sin {self}) } }
    method asin() { Q:CgOp { (asin {self}) } }
    method cos() { Q:CgOp { (cos {self}) } }
    method acos() { Q:CgOp { (acos {self}) } }
    method tan() { Q:CgOp { (tan {self}) } }
    method atan() { Q:CgOp { (atan {self}) } }
    method sec() { Q:CgOp { (sec {self}) } }
    method asec() { Q:CgOp { (asec {self}) } }
    method cosec() { Q:CgOp { (cosec {self}) } }
    method acosec() { Q:CgOp { (acosec {self}) } }
    method cotan() { Q:CgOp { (cotan {self}) } }
    method acotan() { Q:CgOp { (acotan {self}) } }
    method sinh() { Q:CgOp { (sinh {self}) } }
    method asinh() { Q:CgOp { (asinh {self}) } }
    method cosh() { Q:CgOp { (cosh {self}) } }
    method acosh() { Q:CgOp { (acosh {self}) } }
    method tanh() { Q:CgOp { (tanh {self}) } }
    method atanh() { Q:CgOp { (atanh {self}) } }
    method sech() { Q:CgOp { (sech {self}) } }
    method asech() { Q:CgOp { (asech {self}) } }
    method cosech() { Q:CgOp { (cosech {self}) } }
    method acosech() { Q:CgOp { (acosech {self}) } }
    method cotanh() { Q:CgOp { (cotanh {self}) } }
    method acotanh() { Q:CgOp { (acotanh {self}) } }
    method atan2($x = 1) { Q:CgOp { (atan2 {self} {$x}) } }
    method polar() { self.abs, atan2(0, self); }
    method unpolar($angle) { unpolar(self, $angle); }
    method cis() { cis(self); }
    method rand() { self * rand; }
    method roots($n) { roots(self, $n); }

    method gamma() { Q:CgOp { (gamma {self}) } }
    method lgamma() { Q:CgOp { (lgamma {self}) } }
    method expm1() { Q:CgOp { (expm1 {self}) } }
    method log1p() { Q:CgOp { (log1p {self}) } }

    method split($matcher, $limit?, :$all?) {
        my $matchrx = (($matcher ~~ Regex) ?? $matcher !! /$matcher/);
        my $str = ~self;
        my $C = Cursor.cursor_start($str);
        my @out;
        my $i = 0;
        my $last = 0;
        my $limctr = $limit ~~ Whatever ?? Inf !! $limit // Inf;
        my $M;
        while ($i <= chars $str) && ($limctr > 1) {
            $M = head($matchrx($C.cursor($i++)));
            if $M {
                push @out, substr($str, $last, ($M.from - $last));
                push @out, $M if $all;
                $i = $i max ($last = $M.to);
                $limctr = ($limctr - 1);
            }
        }
        push @out, substr($str, $last, (chars($str) - $last));
        @out;
    }
    sub _match_nth($ix, @nth) {
        shift @nth while @nth && @nth[0] < $ix;
        @nth && @nth[0] == $ix;
    }
    method match($pat, :st(:rd(:nd(:th(:$nth)))), :c(:$continue), :p(:$pos)) {
        my $ix = $continue // $pos // 0;
        my $str = ~self;
        if $ix && ($ix === ?1) {
            $ix = CALLER::CALLER::<$/> ?? CALLER::CALLER::<$/>.to !! 0;
        }
        my $max = chars $str;
        my $incr = Cursor.cursor_start($str);
        my $indx = 0;
        $nth := [ @$nth ] if defined($nth);

        while $ix <= $max {
            my $mat = head($pat.($incr.cursor($ix++)));
            if $mat && (!defined($nth) || _match_nth(++$indx, $nth)) {
                Q:CgOp { (rnull (set_status (s $/) {$mat})) };
                return unitem($mat);
            }
            $ix = $ix max $mat.to if defined $mat;
            $ix = $max + 1 if defined($pos);
        }
        Q:CgOp { (rnull (set_status (s $/) {Match})) };
        Match;
    }
    method subst(\: $matcher_, $replacement, :g(:$global), :$x,
            :c(:$continue), :th(:st(:nd(:rd(:$nth)))), :p(:$pos), :$inplace) {
        die ":pos may not be used with :continue" if
            defined($pos) && defined($continue);
        die ":x may not be used with :global" if defined($x) && $global;

        my $old := CALLER::<$/>;
        LEAVE CALLER::<$/> := $old unless $inplace;

        my $str = ~self;
        my $C = Cursor.cursor_start($str);
        my $matcher = $matcher_ ~~ Regex ?? $matcher_ !! /$matcher_/;
        my $i = $pos // $continue // 0;
        if ($i === ?1) {
            $i = $old ?? $old.to !! 0;
        }
        $nth := [ @$nth ] if defined $nth;
        my $to = 0;
        my $changes = 0;
        my $limctr = ($global || defined($x) && $x ~~ Whatever) ?? Inf
                     !! defined($x) ?? $x.niecza_quantifier_max !! 1;
        my @out;
        my $index = 0;
        while $i < chars($str) && $limctr {
            my $M = head($matcher($C.cursor($i++)));
            if $M && $M.chars {
                Q:CgOp { (rnull (set_status (s '$/') {$M})) };
                $i = $M.to max $i;
                unless defined($nth) && !_match_nth(++$index, $nth) {
                    $changes++;
                    push @out, substr($str,$to,$M.from-$to);
                    push @out, ($replacement ~~ Str ?? $replacement
                                                    !! $replacement.count == 1 ?? $replacement($M) !! $replacement());
                    $to = $i = $M.to;
                    $limctr = $limctr - 1;
                }
            } else {
                last if defined($pos);
            }
        }
        my $res = join "", @out, substr($str,$to,chars($str)-$to);
        if defined($x) && $changes !~~ $x {
            $res = $str;
        }
        if $inplace {
            self = $res;
            ?$changes;
        } else {
            $res;
        }
    }
    method capitalize() { self.lc.subst(:g, /\w+/, { ucfirst $/ }) }

    method index($substring, $pos?) {
        my $str = ~self;
        my $fromc = defined($pos) ?? ($pos min chars $str) !! 0;
        my $len = chars $substring;
        my $maxi = chars($str) - $len;
        while $fromc <= $maxi {
            if substr($str,$fromc,$len) eq $substring {
                return $fromc;
            }
            $fromc++;
        }
        Num; # XXX StrPos
    }

    method rindex($substring, $from?) {
        my $str = ~self;
        my $len = chars $substring;
        my $fromc = (($from // 1_000_000_000) min (chars($str) - $len));
        while $fromc >= 0 {
            if substr($str,$fromc,$len) eq $substring {
                return $fromc;
            }
            $fromc = $fromc - 1;
        }
        Num; # XXX StrPos
    }

    method comb($matcher = /./, $limit?, :$match) {
        my $str = ~self;
        my $C = Cursor.cursor_start($str);
        my $i = 0;
        my $limctr = $limit ~~ Whatever ?? Inf !! $limit // Inf;
        my @out;
        while ($i < chars $str) && $limctr > 0 {
            my $M = head($matcher($C.cursor($i++)));
            if $M {
                $i max= $M.to;
                push @out, ($match ?? $M !! (~$M));
                $limctr = $limctr - 1;
            }
        }
        @out
    }

    method lines($limit = *) {
        self.comb(/ ^^ \N* /, $limit);
    }

    method words($limit = 1_000_000_000) {
        self.comb(/ \S+ /, $limit);
    }
    method words-val() { map &val, self.words }
    method chars() { chars(self) }
    method codes() { codes(self) }
    method chomp() {
        my $s = ~self;
        my $l = chars($s);
        --$l if $l && substr($s, $l-1, 1) eq "\x0A";
        --$l if $l && substr($s, $l-1, 1) eq "\x0D";
        substr($s,0,$l);
    }
    method p5chomp($self is rw:) {
        my $s = ~$self;
        my $l = chars($s);
        my $ol = $l;
        --$l if $l && substr($s, $l-1, 1) eq "\x0A";
        --$l if $l && substr($s, $l-1, 1) eq "\x0D";
        $self = substr($s,0,$l);
        $ol - $l;
    }
    method chop() {
        my $s = ~self;
        substr($s, 0, chars($s) - 1)
    }
    method p5chop($self is rw:) {
        my $str = ~$self;
        return '' if $str eq '';
        my $end = substr($str, chars($str)-1, 1);
        $self = substr($str, 0, chars($str)-1);
        $end;
    }
    method substr(\: $start, $len?, $repl?) {
        $start := $start(chars self) if $start.^does(Code);
        $len := $len.^does(Code) ?? ($len(chars self) - $start) !!
            $len // (chars(self) - $start);
        defined($repl) ??
            substr(self, $start, $len) = $repl !!
            substr(self, $start, $len)
    }
    method lc() { Q:CgOp { (box Str (str_tolower (obj_getstr {self}))) }}
    method uc() { Q:CgOp { (box Str (str_toupper (obj_getstr {self}))) }}
    method tc() {
        self ~~ /^(.)(.*)$/ ?? Q:CgOp { (box Str (ucd_titlecase { $0.ord })) } ~ $1 !! "";
    }
    method tclc() {
        self ~~ /^(.)(.*)$/ ?? Q:CgOp { (box Str (ucd_titlecase { $0.ord })) } ~ $1.lc !! "";
    }
    method tcuc() {
        self ~~ /^(.)(.*)$/ ?? Q:CgOp { (box Str (ucd_titlecase { $0.ord })) } ~ $1.uc !! "";
    }
    method flip() { Q:CgOp { (box Str (str_flip (obj_getstr {self}))) }}
    method ucfirst() { ucfirst(self) }
    method lcfirst() { lcfirst(self) }
    method ord() { ord(self) }
    method chr() { chr(self) }
    method ords() { ords(self) }
    method trim-leading () { self.subst(/^ \s+/, "") }
    method trim-trailing() { self.subst(/\s+ $/, "") }
    method trim () { self.trim-leading.trim-trailing }
    method eval() { eval(~self) }

    method fmt(Str $format = '%s') {
        sprintf($format, self);
    }

    method trans(*@changes) {
        Niecza-trans(self, @changes);
    }
}

my role Positional { Any }
my role Associative { Any }

my class Nil is Cool {
    method new() { Nil }
    method iterator() { ().iterator }
    method gist() { 'Nil' }
    # XXX the default won't work because of Nil's exotic binding behavior
    multi method WHICH() { ObjAt.new(str => 'Nil', ref => Any) }
    method Str() { '' }
    method flat() { self.iterator.flat }
    method list() { self.iterator.list }
    method at_pos($key) { @(self).[$key] }
    method Capture () { ().Capture }
    method elems () { 0 }
    method Numeric() { 0 }
    method Bool () { ?0 }
}

my class Capture does Positional does Associative {
    has $!positionals;
    has $!named;

    method Parcel() {
        Q:CgOp { (box Parcel (getslot Capture $!positionals fvarlist (@ {self}))) }
    }
    method perl() {
        self // return self.typename;
        my $pos = self.Parcel.perl;
        $pos = substr($pos, 2, chars($pos) - 3);
        $pos = substr($pos, 0, chars($pos) - 2) if substr($pos, chars($pos) - 2, 2) eq ', ';
        my $h := self.hash;
        if $h {
            $pos ~= ", " if $pos ne "";
            $pos ~= "|" ~ $h.perl;
        }
        '\(' ~ $pos ~ ')';
    }
    method immutable() {
        self // return True;
        self.Parcel.immutable &&
            (!self.hash || self.hash.values.Capture.Parcel.immutable);
    }

    method Capture () { self }
    method item () {
        if self.hash || self.Parcel.raw_elems != 1 {
            die "Can only use .item on captures representing a single value"
        }
        self.Parcel.raw_at(0)
    }
    method list () { @(self.Parcel) }
    method hash () { unitem( Q:CgOp {
        (letn h (getslot Capture $!named varhash (@ {self}))
          (ternary (== (l h) (null varhash)) {{}} (box Hash (l h))))
    }) }
}
# }}}
# Scalar types {{{
my role Numeric is Cool {
    method ACCEPTS(\t) {
        defined(self) ?? (self == self ?? self == t !! t != t)
            !! t.^does(self)
    }
}
my role Real does Numeric {
    method Bridge() {
        self.Num;
    }
    method Complex() {
        Q:CgOp { (complex_new {self.Bridge} {0}) };
    }
    method Str() {
        self.Bridge.Str;
    }
    method Bool() {
        self != 0;
    }
    method succ() {
        self.Bridge + 1;
    }
    method pred() {
        self.Bridge - 1;
    }
}
my role Integral does Real { Any }
my class Num does Real {
    method new() { 0e0 }
    method immutable() { True }
    multi method WHICH(Num:D:) { ObjAt.new(str => ~self, ref => self.WHAT) }
    our constant pi = 3.14159_26535_89793_238e0;
    our constant e = 2.71828_18284_59045_235e0;
    our constant i = Q:CgOp { (complex_new {0} {1}) };
    method Num() { self }
    method FatRat() { self.Rat(0).FatRat }
    method gist() { self.Str }
    method perl() {
        if defined(self) {
            my $num = self.Str;
            $num ~= 'e0' unless $num ~~ m:i/e/ || $num ~~ /Inf/ || $num ~~ /NaN/;
            $num;
        } else {
            self.typename;
        }
    }
}
our constant pi = 3.14159_26535_89793_238e0;
our constant e = 2.71828_18284_59045_235e0;
our constant i = Num::i;
my class Int does Integral {
    method new() { 0 }
    method immutable() { True }
    multi method WHICH(Int:D:) { ObjAt.new(str => ~self, ref => self.WHAT) }
    method niecza_quantifier_max() { self }
    method niecza_quantifier_min() { self }
    method Bridge() { self.Num }
    method Int() { self }
    method perl() { defined(self) ?? ~self !! self.typename }
    method FatRat() { FatRat.new(self, 1) }
    method base(Cool $base) {
        my $intBase = $base;
        die("base must be between 2 and 36, got $base")
            unless 2 <= $intBase <= 36;
        my @conversion = 0..9, 'A' .. 'Z';
        my @res;
        my $n = self.abs;
        repeat {
            push @res, @conversion[$n % $intBase];
            $n div= $intBase;
        } while $n > 0;
        push @res, '-' if self < 0;
        join '', @res.reverse;
    }
    method expmod($power, $mod) { expmod(self, $power, $mod) }
    method is-prime($tries = 100) { is-prime(self, $tries) }
}
my class Rat does Real {
    method new($n,$d) { $n / $d }
    method immutable() { True }
    multi method WHICH(Rat:D:) { ObjAt.new(str => self.perl, ref => self.WHAT) }
    method perl() { defined(self) ?? "<" ~ self.numerator ~ "/" ~ self.denominator ~ ">" !! self.typename }
    method gist() { self // nextsame; self.Str }
    method numerator() { Q:CgOp { (rat_nu {self}) } }
    method denominator() { Q:CgOp { (rat_de {self}) } }
    method Rat($eps = 1e-6) { self } #OK
    method FatRat() { FatRat.new(self.numerator, self.denominator) }
    method nude() { [ self.numerator, self.denominator ] }
    method norm() { self }
}
my class Complex does Numeric {
    method new($re,$im) { Q:CgOp { (complex_new {$re} {$im}) } }
    method immutable() { True }
    multi method WHICH(Complex:D:) { ObjAt.new(str => self.perl, ref => self.WHAT) }
    method perl() { defined(self) ?? "<" ~ self ~ ">" !! self.typename }
    method gist() { self // nextsame; self.Str }
    method Complex() { self }
    method re() { Q:CgOp { (complex_re {self}) } }
    method im() { Q:CgOp { (complex_im {self}) } }
    method conj() { self.re - (self.im)i }
    method polar() { self.abs, atan2(self.im, self.re); }
}
my class FatRat does Real {
    method new($n,$d) { FatRat.succ * $n / $d }
    method immutable() { True }
    multi method WHICH(FatRat:D:) { ObjAt.new(str => self.perl, ref => self.WHAT) }
    method perl() { defined(self) ?? "FatRat.new({self.numerator}, {self.denominator})" !! self.typename }
    method FatRat() { self }
    method gist() { self // nextsame; self.Str }
    method numerator() { Q:CgOp { (fatrat_nu {self}) } }
    method denominator() { Q:CgOp { (fatrat_de {self}) } }
    method nude() { [ self.numerator, self.denominator ] }
}

my class Buf { ... }
my class Str is Cool {
    method new() { "" }
    method immutable() { True }
    method ACCEPTS(\t) { defined(self) ?? self eq t !! t.^does(self) }
    method chars() { chars(self) }
    method IO() { IO.new(path => self) }
    method say() { $*OUT.say(self) }
    multi method WHICH(Str:D:) {
        ObjAt.new(str => ("str|" ~ self), ref => self.WHAT)
    }

    # TODO: Switch to a multi once where is working.
    method indent($steps) {
        my $TABSTOP = CALLER::<$?TABSTOP> // 8;

        if $steps~~Int && $steps == 0 {
            # Zero indent does nothing
            return self;
        } elsif $steps~~Int && $steps > 0 {
            # Positive indent does indent

            # We want to keep trailing \n so we have to .comb explicitly instead of .lines
            return self.comb(/:r ^^ \N* \n?/).map({
                given $_ {
                    # Use the existing space character if they're all the same
                    # (but tabs are done slightly differently)
                    when /^(\t+) ([ \S .* | $ ])/ {
                        $0 ~ "\t" x ($steps div $TABSTOP) ~
                             ' ' x ($steps mod $TABSTOP) ~ $1
                    }
                    when /^(\h) $0* [ \S | $ ]/ {
                        $0 x $steps ~ $_
                    }
    
                    # Otherwise we just insert spaces after the existing leading space
                    default {
                        ($_ ~~ /^(\h*) (.*)$/).join(' ' x $steps)
                    }
                }
            }).join;
        } else {
            # Negative values and Whatever-* do outdent
            # Loop through all lines to get as much info out of them as possible
            my @lines = self.comb(/:r ^^ \N* \n?/).map({
                # Split the line into indent and content
                my ($indent, $rest) = @($_ ~~ /^(\h*) (.*)$/);
    
                # Split the indent into characters and annotate them
                # with their visual size
                my $indent-size = 0;
                my @indent-chars = $indent.comb.map(-> $char {
                    my $width = $char eq "\t"
                        ?? $TABSTOP - ($indent-size mod $TABSTOP)
                        !! 1;
                    $indent-size += $width;
                    $char => $width;
                });
    
                { :$indent-size, :@indent-chars, :$rest };
            });
    
            # Figure out the amount * should outdent by, we also use this for warnings
            my $common-prefix = [min] @lines.map({ $_<indent-size> });

            # Set the actual outdent amount here
            my Int $outdent = $steps ~~ Whatever ?? $common-prefix
                                                 !! -$steps;
            warn sprintf('Asked to remove %d spaces, ' ~
                         'but the shortest indent is %d spaces',
                         $outdent, $common-prefix) if $outdent > $common-prefix;
    
            # Work backwards from the right end of the indent whitespace, removing
            # array elements up to # (or over, in the case of tab-explosion)
            # the specified outdent amount.
            @lines.map({
                my $pos = 0;
                while $_<indent-chars> and $pos < $outdent {
                    $pos += $_<indent-chars>.pop.value;
                }
                $_<indent-chars>».key.join ~ ' ' x ($pos - $outdent) ~ $_<rest>;
            }).join;
        }
    }

    method gist() { defined(self) ?? self !! nextsame }
    method Numeric () { Niecza::NumSyntax.str2num(~self) }
    CHECK my $esc = {
        '$' => '\$', '@' => '\@', '%' => '\%', '&' => '\&', '{' => '\{',
        "\b" => '\b', "\n" => '\n', "\r" => '\r', "\t" => '\t', '"' => '\"',
        '\\' => '\\\\' };
    method perl() {
        self // nextsame;
        '"' ~ self.subst(/ <[$@%&{\b\cJ\cM\t\"\\]> /, { $esc{$/} }, :g)\
                  .subst(/ <-print> /, { ord($/).fmt('\x[%x]') }, :g) ~ '"'
    }
    method encode(Str $enc) {
        Q:CgOp { (box (@ {Buf}) (encode (unbox str (@ {self})) (obj_getstr {$enc}))) }
    }
}

my class Buf {
    method decode(Str $enc) {
        Q:CgOp { (box Str (decode (unbox blob (@ {self})) (obj_getstr {$enc}))) }
    }
    method elems() {
        Q:CgOp { (box Int (unbox blob (@ {self}))) }
    }
    method bytes() { self.elems }
    method Bool() { ?self.elems }
    method Numeric() { self.elems }
    method Int() { self.elems }
}

# ObjAt in Niecza is the type of return values from WHICH. It is a comparable
# type that allows any two objects to be compared, and attempts to capture a
# notion of 'essential equality'. The most ready way to compare the identities
# of mutable objects is to compare references, so ObjAt keeps a reference;
# ObjAt also keeps a string description of contents, for non-mutable types.
#
# For mutable types, the string should be empty, and the reference should be
# the specific object that WHICH was invoked upon.
#
# For defined values of immuable types, the string should hold a description
# of this object, and the reference points to the WHAT of the invokee.
#
# Note that if this protocol is followed, $x === $y implies
# $x.WHAT === $y.WHAT, and so the string data is completely under the control
# of the type.
#
# Well, not quite - you need to avoid returning anything starting with objat|
my class ObjAt {
    has Str $.str;
    has Mu $.ref;

    multi method WHICH(ObjAt:D:) {
        ObjAt.new(str => 'objat|' ~ $!str, ref => $!ref)
    }

    sub REFHASH($v) { Q:CgOp { (box Int (ref_hash (@ {$v}))) }.fmt('[%X]') }
    method Str() { self // nextsame; $!str ~ REFHASH($!ref) }
    method gist() { self // nextsame; $!str ~ REFHASH($!ref) }
}

my class Scalar {
}

# just a tag
my role Callable { Any }
my class Code does Callable {
    has $!outer;
    has $!info;

    method outer() { Q:CgOp { (getslot Code $!outer frame (@ {self})) } }
    method perl() { defined(self) ?? '{ ... }' !! self.typename }

    method accepts_capture($cap) { Q:CgOp { (code_accepts_capture (@ {self}) (@ {$cap})) } }
    method candidates(Code:D:) { Q:CgOp { (code_candidates (@ {self})) } }
    method signature(Code:D:) { Q:CgOp { (code_signature (@ {self})) } }
    method candidates_matching(|cap) { grep *.accepts_capture(cap), self.candidates }
    method name(Code:D:) { Q:CgOp { (box Str (code_name (@ {self}))) } }
}

my class Block is Code {
    method ACCEPTS(\t) { defined(self) ?? (self)(t) !! t.^does(self) }
    method count() { Q:CgOp { (count (@ {self})) } }
    method arity() { Q:CgOp { (arity (@ {self})) } }
}

my class Routine is Block {
    method assuming(|cap) { sub (|new) { self.(|cap, |new) } }
    # wrap, unwrap, cando NYI
    method perl() {
        self // nextsame;
        my $perl = self.^name.lc();
        if self.name() -> $n {
            $perl ~= " $n";
        }
        $perl ~= self.signature().perl.substr(1);
        $perl ~= ' { ... }';
        $perl
    }
}

my class Sub is Routine { }
my class Method is Routine { }
my class Submethod is Routine { }
my class WhateverCode is Block { }

my class Parameter {
    # Value processing
    our constant HASTYPE = 1;
    our constant MULTI_IGNORED = 16384;
    our constant ANY_DEF = 0x40000;
    our constant UNDEF_ONLY = 0x80000;
    our constant DEF_ONLY = 0xC0000;
    our constant TYPE_ONLY = 0x100000;
    our constant DEF_MASK = 0x1C0000;

    # Value binding
    our constant READWRITE = 2;
    our constant RWTRANS = 8;
    our constant INVOCANT = 8192;
    our constant IS_COPY = 32768;
    our constant IS_LIST = 65536;
    our constant IS_HASH = 131072;
    our constant CALLABLE = 0x20_0000;

    # Value source
    our constant HASDEFAULT = 32;
    our constant OPTIONAL = 64;
    our constant DEFOUTER = 4096;
    our constant POSITIONAL = 128;
    our constant SLURPY_POS = 256;
    our constant SLURPY_NAM = 512;
    our constant SLURPY_CAP = 1024;
    our constant SLURPY_PCL = 2048;

    method flags(Parameter:D:) { Q:CgOp { (box Int (param_flags (@ {self}))) } }

    method named(Parameter:D:) { ? (self.named_names && !self.positional) }
    method named_names(Parameter:D:) { Q:CgOp { (param_names (@ {self})) } }
    method type(Parameter:D:) { Q:CgOp { (param_type (@ {self})) } }
    method sub_signature(Parameter:D:) { Q:CgOp { (param_subsig (@ {self})) } }
    method optional(Parameter:D:) { ?( self.flags +& (HASDEFAULT +| OPTIONAL) ) }
    method positional(Parameter:D:) { ?( self.flags +& POSITIONAL ) }
## method value_constraint_list() { !!! }
    method name() { Q:CgOp { (box Str (param_name (@ {self}))) } }
    method slurpy() { ?( self.flags +& (SLURPY_CAP + SLURPY_NAM + SLURPY_POS) ) }

    # no constraint_list! niecza's SubInfo constraints don't reflect well :|
    method value_constraint_list(Parameter:D:) { Q:CgOp { (param_value_constraints (@ {self})) } }
    method parcel() { ?( self.flags +& RWTRANS ) }
    method capture() { ?( self.flags +& SLURPY_CAP ) }
    method rw() { ?( self.flags +& READWRITE ) }
    method copy() { ?( self.flags +& IS_COPY ) }
    method readonly() { !( self.flags +& (READWRITE + IS_COPY + RWTRANS) ) }
    method invocant() { ?( self.flags +& INVOCANT ) }
## method default() { }

    # XXX TODO: A few more bits :-)
    multi method perl(Parameter:D:) {
        my $perl = '';
        my $flags = self.flags;
        my $type = self.type.^name;
        if $flags +& IS_LIST {
            # XXX Need inner type
        }
        elsif $flags +& IS_HASH {
            # XXX Need inner type
        }
        else {
            $perl = $type;
            if $flags +& DEF_ONLY {
                $perl ~= ':D';
            } elsif $flags +& UNDEF_ONLY {
                $perl ~= ':U';
            } elsif $flags +& TYPE_ONLY {
                $perl ~= ':T';
            }
            $perl ~= ' ';
        }
        if self.name -> $name is copy {
            if $flags +& SLURPY_CAP {
                $perl ~= '|' ~ $name;
            } elsif $flags +& RWTRANS {
                $perl ~= '\\' ~ $name;
            } else {
                my $default = $flags +& HASDEFAULT;
                if !self.positional && self.named_names -> @names {
                    my $short = $name.substr(1);
                    $name = ':' ~ $name if $short eq any @names;
                    for @names {
                        next if $_ eq $short;
                        $name = ':' ~ $_ ~ '(' ~ $name ~ ')';
                    }
                    $name ~= '!' unless self.optional;
                } elsif self.optional && !$default {
                    $name ~= '?';
                } elsif self.slurpy {
                    $name = '*' ~ $name;
                }
                $perl ~= $name;
                if $flags +& READWRITE {
                    $perl ~= ' is rw';
                } elsif $flags +& IS_COPY {
                    $perl ~= ' is copy';
                }
                $perl ~= ' = { ... }' if $default;
                if self.sub_signature -> $sub {
                    $perl ~= ' ' ~ $sub.perl;
                }
            }
        }
        $perl
    }
}
my class Signature {
    method params(Signature:D:) { Q:CgOp { (sig_params (@ {self})) } }
    method arity(Signature:D:) { Q:CgOp { (box Int (sig_arity (@ {self}))) } }
    method count(Signature:D:) { Q:CgOp { (box Int (sig_count (@ {self}))) } }
    # XXX TODO: Parameter separators.
    method perl() {
        self // nextsame;
        ':(' ~ join(', ', self.params».perl) ~ ')';
    }
}

my class ClassHOW {
    method name($) { Q:CgOp { (box Str (obj_typename (stab_what (unbox stable (@ {self}))))) } }
    method isa(\obj, \type) { Q:CgOp {
        (box Bool (obj_isa (@ {obj}) (obj_llhow (@ {type}))))
    } }
    method does(\obj, \role) { self.isa(obj, role) }
    method can(\obj, $name) { Q:CgOp {
        (box Bool (obj_can (@ {obj}) (obj_getstr {$name})))
    } }
}

my role CommonEnum {
    has $!index;

    method perl() {
        defined(self) ?? (self.typename ~ "::" ~ self.key) !! self.typename
    }
    method gist() { defined(self) ?? self.key !! (self.typename ~ "()") }
    method key() { self.enums._index_to_key($!index) }
    method value() { self.enums._index_to_value($!index) }
    method kv() { self.key, self.value }
    method pair() { self.key => self.value }

    method succ() {
        my $index = defined(self) ?? $!index !! 0;
        return self if $index == self.enums - 1;
        self.from-index($index + 1)
    }

    method pred() {
        my $index = defined(self) ?? $!index !! 0;
        $index ?? self.from-index($index - 1) !! self;
    }

    method from-index($ix) { self._create($ix,self.enums._index_to_value($ix)) }

    method postcircumfix:<( )> ($key) {
        self.from-index(self.enums._lookup($key));
    }

    method pick($count = 1) { self.enums.map({ self.($_.key) }).pick($count) }
    method roll($count = 1) { self.enums.map({ self.($_.key) }).roll($count) }
}

my role IntBasedEnum does CommonEnum {
    method Numeric() { Q:CgOp { (box Int (unbox int (@ {self}))) } }
    method Int() { self.Numeric }
    method Str() { defined(self) ?? self.key !! nextsame }
    method Stringy() { defined(self) ?? self.key !! nextsame }
    method _create($ix,$val) { Q:CgOp {
        (letn obj (box (@ {self}) (unbox int (@ {$val.Int})))
          (setslot (obj_llhow (@ (l obj))) $!index (@ (l obj)) {$ix.Int})
          (l obj))
    } }
}

my role StrBasedEnum does CommonEnum {
    method _create($ix,$val) { Q:CgOp {
        (letn obj (box (@ {self}) (unbox str (@ {$val.Str})))
          (setslot (obj_llhow (@ (l obj))) $!index (@ (l obj)) {$ix.Int})
          (l obj))
    } }
}

# Using the "enum" type declarator would require a compile time reference
# to the EnumMap type, which depends on Bool; ick.
my class Bool is Int does IntBasedEnum {
    our $_enums;
    method enums() { $_enums }
    our constant True = Q:CgOp { (box Bool (bool 1)) };
    our constant False = Q:CgOp { (box Bool (bool 0)) };
    method ACCEPTS(\t) { defined(self) ?? self !! t.^does(self) }
    method succ() { True }
    method pred() { False }
}
# }}}
# Fundamental scalar operators {{{
sub infix:<~> is Niecza::absprec<r= list> is pure (\|$bits) { Q:CgOp {
    (letn buf (strbuf_new)
          i (int 0)
          ar (unbox fvarlist (@ {$bits}))
          max (fvarlist_length (l ar))
      [whileloop 0 0 (< (l i) (l max)) (prog
          [strbuf_append (l buf)
            (obj_getstr (fvarlist_item (l i) (l ar)))]
          [l i (+ (l i) (int 1))])]
      [box Str (strbuf_seal (l buf))])
} }

sub infix:<max>(*@values) is pure is Niecza::absprec<k= list> { @values.max }
sub infix:<min>(*@values) is pure is equiv<max> { @values.min }
sub infix:<minmax>(*@values) is equiv<max> { @values.minmax }

sub warn($str) { Q:CgOp { (control 11 (null frame) (int -1) (obj_getstr {$str}) (null obj)) } }

sub gist(\|@items) { @items.gist }
our sub Niecza::gistcat(\|@items) {
    my @tok;
    loop (my $i = 0; $i < @items.raw_elems; $i++) {
        push @tok, @items.raw_at($i).gist;
    }
    @tok.join;
}
sub say(|c) { $PROCESS::OUTPUT_USED := True; Q:CgOp { (rnull (say (obj_getstr {Niecza::gistcat(|c)}))) }; True }
sub print(*@items) { $PROCESS::OUTPUT_USED := True; Q:CgOp { (rnull (print (obj_getstr {@items.join("")}))) }; True }
sub note(|c) { $PROCESS::OUTPUT_USED := True; Q:CgOp { (rnull (note (obj_getstr {Niecza::gistcat(|c)}))) }; True }

sub sprintf(\|$args) { Q:CgOp { (sprintf (unbox fvarlist (@ {$args}))) } }
sub printf(Cool $format, *@args) { print sprintf $format, |@args };

sub exit($status = 0) { Q:CgOp {
    (rnull [exit (cast int (obj_getnum {$status}))])
} }

sub index($haystack,$needle,$pos?) is pure { $haystack.index($needle,$pos) }
sub rindex($haystack,$needle,$pos?) is pure { $haystack.rindex($needle,$pos) }
sub comb($matcher,$str,$limit?,:$match) { (~$str).comb($matcher,$limit,:$match) }
sub split($matcher,$str,$limit?,:$all) { (~$str).split($matcher,$limit,:$all) }

sub item(Mu $x) { $x }
sub list(*@x) { @x.list }

sub prefix:<not> is pure is Niecza::absprec<h= unary left> (\x) { not(x) }

sub infix:<x> is pure is Niecza::absprec<s=> ($str, $ct) {
    my $i = +$ct;
    my $j = ''; # XXX use strbuf
    while $i >= 1 {
        $i--;
        $j ~= $str;
    }
    $j;
}

sub infix:<leg> is pure is Niecza::absprec<n= non> is diffy ($s1, $s2) {
    (Q:CgOp { (box Num (cast num (strcmp (obj_getstr {$s1}) (obj_getstr {$s2})))) }) <=> 0
}

sub lc($string) is pure { (~$string).lc }
sub uc($string) is pure { (~$string).uc }
sub tc($string) is pure { (~$string).tc }
sub tclc($string) is pure { (~$string).tclc }
sub chop($string) is pure { (~$string).chop }
sub chomp($string) is pure { (~$string).chomp }
sub capitalize($string) is pure { (~$string).capitalize }
sub p5chop(*@strs) { my $r = ''; $r = .p5chop for @strs; $r }
sub p5chomp(*@strs) { my $r = 0; $r += .p5chomp for @strs; $r }
sub flip($string) is pure { (~$string).flip }
sub lcfirst($o) is pure { my $s = ~$o; lc(substr($s,0,1)) ~ substr($s,1) }
sub ucfirst($o) is pure { my $s = ~$o; uc(substr($s,0,1)) ~ substr($s,1) }
sub trim-leading($string) is pure { $string.trim-leading };
sub trim-trailing($string) is pure { $string.trim-trailing };
sub trim($string) is pure { $string.trim };

sub Niecza::ValueIdentity(Mu $l, Mu $r) {
    my $lw = $l.WHICH;
    my $rw = $r.WHICH;
    Q:CgOp { (box Bool (compare == (@ {$lw.ref}) (@ {$rw.ref}))) } &&
        $lw.str eq $rw.str
}
sub infix:<===>($l, $r) is equiv<==> { Niecza::ValueIdentity($l, $r) }

sub infix:<=:=>(\l,\r) is equiv<==> { Q:CgOp {
    (box Bool (compare == {l} {r}))
} }

sub _param_role_inst(\|$t) {
    Q:CgOp { (instrole (unbox fvarlist (@ {$t}))) }
}

sub infix:<does>($obj, \roles, :$clone, :$value) is rw {
    die "Cannot use 'does' operator with a type object"
        if !$clone && !$obj.defined;
    die "Cannot use 'does' operator with an immutable object"
        if !$clone && $obj.immutable;
    $obj := $obj.clone if $clone && defined($obj);

    my Mu $newtype;
    my @roles = roles;
    for @roles <-> $val {
        my $oval = $val;
        if defined($val) {
            $val = Q:CgOp { (enum_mixin_role (obj_getstr {$val.typename})
                (@ {method () { $oval }})) };
        } elsif !Q:CgOp { (is_role {$val}) } {
            my $tn = $val.typename;
            $val = Q:CgOp { (type_mixin_role {$val}
                {method () { Q:CgOp { (dyngetattr {self} {$newtype} {$tn}) } } }) };
        }
    }

    Q:CgOp { (mixin (@ {$obj}) {@roles} {$value} {$newtype}) }
}

sub infix:<but>($obj, \roles, :$value) is rw {
    infix:<does>($obj, roles, :clone, :$value)
}

sub infix:<~~>($t,$m) is equiv<==> { $m.ACCEPTS($t) }

sub ord($x) is pure { Q:CgOp { (ord {$x}) } }
sub chr($x) is pure { Q:CgOp { (chr {$x}) } }
sub ords($x) { $x.comb.map({ ord($_) }) }
sub chrs(*@x) { @x.map({ chr($_ )}).join }

# }}}
# Flow inspection and control {{{
my class CallFrame {
    method caller() { Q:CgOp {
        (letn c (frame_caller (cast frame (@ {self})))
          (ternary
            (!= (l c) (null frame))
            (l c)
            {Any}))
    } }
    method dynamic-caller() { Q:CgOp {
        (letn c (frame_dyn_caller (cast frame (@ {self})))
          (ternary
            (!= (l c) (null frame))
            (l c)
            {Any}))
    } }

    method file() { Q:CgOp { (box Str (frame_file
        (cast frame (@ {self})))) } }
    method line() { Q:CgOp { (box Num (cast num (frame_line
        (cast frame (@ {self}))))) } }
    method subname() { Q:CgOp { (box Str (frame_subname
        (cast frame (@ {self})))) } }
    method args() { Q:CgOp { (frame_args (cast frame (@ {self}))) } }

    method hints($var) { Q:CgOp { (frame_hint (cast frame (@ {self}))
        (obj_getstr {$var})) } }
}
sub caller() { Q:CgOp { (frame_caller (frame_caller (callframe))) } }
sub callframe(Int $level is copy = 0) {
    my $frame := Q:CgOp { (frame_caller (callframe)) };
    $frame := $frame.caller while $level--;
    $frame;
}

sub die($msg = "Died") { Q:CgOp { (die (@ {$msg})) } }

my class Label {
    has $!target;
    has $!name;
    method immutable() { True }

    method goto() { _lexotic(8, self, ()) }
    method next() { _lexotic(1, self, ()) }
    method last() { _lexotic(2, self, ()) }
    method redo() { _lexotic(3, self, ()) }
}

# XXX multi dispatch
sub _lexotic ($id, $x, \val) {
    Q:CgOp {
        (letn fr (null frame)
              nm (null str)
              id (@ {$x})
          (ternary (obj_isa (l id) (class_ref mo Label))
            (prog (l fr (getslot Label $!target frame (l id)))
                  (l nm (getslot Label $!name str (l id))))
            (ternary (obj_isa (l id) (class_ref mo Str))
              (l nm (obj_getstr {$x}))
              (prog)))
          (control (cast int (obj_getnum {$id})) (l fr) (int -1) (l nm) {val}))
    }
}
sub goto ($x) { _lexotic(8, $x, ()) }

sub nextsame() {
    Q:CgOp { (control 9 (null frame) (int -1) (null str) (null obj)) }
}
sub nextwith(|cap) {
    Q:CgOp { (control 9 (null frame) (int -1) (null str) (@ {cap})) }
}

sub callsame () { Q:CgOp { (callnext (null obj)) } }
sub callwith (|cap) { Q:CgOp { (callnext (@ {cap})) } }

sub assignop($fn) {
    anon sub _assign(\lhs, \rhs) {
        lhs = $fn(lhs, rhs)
    }
}

sub notop(&fn) { -> \x, \y { !(fn(x,y)) } }

# }}}
# Aggregate types {{{
# Parcel: immutable list of boxes which have no context - may flatten, may
# autovivify, don't rebind or push/shift/etc
# List: mutable list of boxes without much context. accessing off end returns
# undefined. lazy.
# coercion makes the elements of a List read-only and maybe fetches them too.
# Array: mutable list of read-write scalar boxes

sub unitem(\a) { Q:CgOp { (newrwlistvar (@ {a})) } }
sub head(\x) { for x -> \elt { return elt }; Any }

my class Iterator {
    method list () {
        Q:CgOp {
            (letn n (obj_newblank (class_ref mo List))
              (iter_to_list (l n) (unbox vvarlist (@ {self})))
              (newrwlistvar (l n)))
        }
    }

    method flat () {
        Q:CgOp {
            (letn n (obj_newblank (class_ref mo List))
              (iter_to_list (l n) (iter_flatten (unbox vvarlist (@ {self}))))
              (newrwlistvar (l n)))
        }
    }
}

my class IterCursor {
    # subclasses must provide .reify, return parcel
}

sub flat(*@x) { @x }
sub hash(|cap) {
    (%(cap) || cap.Parcel.raw_elems != 1) ??
        %( @(cap), %(cap) ) !! %( $(cap) )
}

my class EMPTY { }

my class Parcel is Cool does Positional {
    method ACCEPTS(\what) { defined(self) ?? self.flat.ACCEPTS(what) !! nextsame }
    method flat() { self.iterator.flat }
    method at_pos($key) { @(self).[$key] }

    # LoLly usage
    method raw_elems() { Q:CgOp {
        (box Num (cast num (fvarlist_length (unbox fvarlist (@ {self})))))
    } }
    method raw_at($ix) {
        Q:CgOp { (fvarlist_item (cast int (obj_getnum {$ix})) (unbox fvarlist (@ {self}))) }
    }
    method immutable() {
        self // return True;
        my $ix = 0;
        my $max := self.raw_elems;
        while $ix < $max {
            IMMUTABLE(self.raw_at($ix++)) || return False;
        }
        True;
    }

    method unwrap-single(@self:) { Q:CgOp {
        (letn p (unbox fvarlist (@ {@self}))
              l (fvarlist_length (l p))
          (ternary (== (i 0) (l l)) {Nil}
            (ternary (== (i 1) (l l))
              (fvarlist_item (i 0) (l p)) {@self})))
    } }

    method Capture () {
        Q:CgOp {
            (letn n (obj_newblank (obj_llhow (@ {Capture})))
              (setslot Capture $!positionals (l n) (unbox fvarlist (@ {self})))
              (l n))
        }
    }

    method perl(\:) {
        self // return self.typename;
        my @tok;
        push @tok, '$' if !self.flattens;
        push @tok, '(';
        loop (my $i = 0; $i < self.raw_elems; $i++) {
            push @tok, self.raw_at($i).perl;
            push @tok, ', ' unless $i == self.raw_elems - 1 && $i;
        }
        push @tok, ')';
        @tok.join;
    }

    method elems () { + @(self) }
    method Numeric() { + @(self) }
    method Bool () { ? @(self) }
    method gist () {
        self // nextsame;
        my @tok;
        loop (my $i = 0; $i < self.raw_elems; $i++) {
            push @tok, self.raw_at($i).gist;
        }
        @tok.join(" ");
    }

    method fmt($format = '%s', $separator = ' ') { # duplicates version in List
        self.map({ .fmt($format) }).join($separator);
    }
}

my class List is Cool does Positional {
    has $!items;
    has $!rest;
    has $!flat;

    method new() {
        Q:CgOp {
            (letn n (obj_newblank (obj_llhow (@ {self})))
              (setslot List $!items (l n) (vvarlist_new_empty))
              (setslot List $!rest (l n) (vvarlist_new_empty))
              (newrwlistvar (l n)))
        };
    }

    method flat() {
        self.iterator.flat
    }

    method Seq () {
        Q:CgOp { (box Iterator (iter_copy_elems (unbox vvarlist (@ {self.eager.iterator})))) }.list
    }

    method clone() { Q:CgOp {
        (letn selfo (@ {self})
              new (obj_newblank (obj_llhow (l selfo)))
          (setslot List $!items (l new) (vvarlist_clone
              (getslot List $!items vvarlist (l selfo))))
          (setslot List $!rest (l new) (vvarlist_clone
              (getslot List $!rest vvarlist (l selfo))))
          (newrwlistvar (l new)))
    } }

    method Capture () {
        Q:CgOp {
            (letn n (obj_newblank (obj_llhow (@ {Capture})))
              (setslot Capture $!positionals (l n) (vvarlist_to_fvarlist
                  (getslot List $!items vvarlist (@ {self.eager}))))
              (l n))
        }
    }

    method perl(\:) {
        self // return self.typename;
        my @tok;
        push @tok, '(';
        push @tok, .perl, ', ' for @(self);
        pop @tok if @tok >= 5;
        push @tok, ').list';
        push @tok, '.item' if !self.flattens;
        @tok.join
    }

    method eager() { +self; self }

    method head() { self ??
        Q:CgOp { (vvarlist_item (i 0) (getslot List $!items vvarlist (@ {self}))) } !!
        Any
    }

    method elems() { +self }

    method join($sep = '') {
        my $t;
        for unitem(self) -> $x {
            $t = (defined($t) ?? ($t ~ $sep ~ $x) !! ~$x);
        }
        $t // '';
    }

    method ACCEPTS(\topic) {
        self // nextsame;
        my @t = topic.list;
        # TODO: Whatever-DWIMmery
        return False unless self.elems == @t.elems;
        for ^self.elems {
            return False unless self.at_pos($_) === @t[$_];
        }
        True;
    }

    method gist() { defined(self) ?? self.map(*.gist).join(" ") !! nextsame }

    method sort($cmp_ = &infix:<cmp>) {
        my $cmp = $cmp_;
        if $cmp_.count == 1 {
            $cmp = sub (\x, \y) { $cmp_(x) cmp $cmp_(y) }
        }
        my $l = @(self).eager;
        Q:CgOp {
            (letn n (obj_newblank (obj_llhow (@ {List})))
              (setslot List $!items (l n) (vvarlist_sort (@ {$cmp})
                  (getslot List $!items vvarlist (@ {$l}))))
              (setslot List $!rest (l n) (vvarlist_new_empty))
              (newrwlistvar (l n)))
        }
    }

    method reverse() { reverse( @(self) ); }
    method end() { self.elems - 1 }

    method classify(&test) {
        my %result;
        for @(self) {
            my $k = test $_;
            %result{$k} //= [];
            %result{$k}.push: $_;
        }
        %result;
    }

    method categorize(&test) {
        my %result;
        for @(self) {
            my @k = test $_;
            for @k -> $k {
                %result{$k} //= [];
                %result{$k}.push: $_;
            }
        }
        %result;
    }

    method min($cmp_ = &infix:<cmp>) {
        my $cmp = $cmp_;
        if $cmp_.count == 1 {
            $cmp = sub (\x, \y) { $cmp_(x) cmp $cmp_(y) }
        }
        my $min = self[0] // return Inf;
        for @(self) {
            $min = $_ if $cmp($_, $min) < 0;
        }
        $min;
    }

    method max($cmp_ = &infix:<cmp>) {
        my $cmp = $cmp_;
        if $cmp_.count == 1 {
            $cmp = sub (\x, \y) { $cmp_(x) cmp $cmp_(y) }
        }
        my $max = self[0] // return -Inf;
        for @(self) {
            $max = $_ if $cmp($_, $max) > 0;
        }
        $max;
    }

    method minmax($cmp_ = &infix:<cmp>) {
        my $cmp = $cmp_;
        if $cmp_.count == 1 {
            $cmp = sub (\x, \y) { $cmp_(x) cmp $cmp_(y) }
        }
        my $min = self[0] // return Inf .. -Inf;
        my $max = self[0];
        for @(self) {
            $min = $_ if $cmp($_, $min) < 0;
            $max = $_ if $cmp($_, $max) > 0;
        }
        $min..$max;
    }

    method plan(*@items) {
        Q:CgOp {
            (rnull
              (vvarlist_append (getslot List $!rest vvarlist (@ {self}))
                (unbox vvarlist (@ {@items.iterator}))))
        }
    }

    method kv() { my $i = 0; self.map({ $i++, $_ }) }

    method at_pos($p) { self[$p] }

    method fmt($format = '%s', $separator = ' ') {
        self.map({ .fmt($format) }).join($separator);
    }

    method rotate($n = 1) {
        my $k = $n % self.elems;
        self[$k .. self.elems-1, 0 .. $k-1];
    }

    method splice( @array is rw: $offset = 0, $size = Inf, *@values ) {
        my $begin = $offset.^does(Code) ?? $offset.(@array.elems) !! $offset;
        my $max;

        if $size.^does(Code) {
            $max = $size.(@array.elems);
        } elsif $size < 0 {
           die '$size must be non-negative.';
        } else {
            $max = $begin + $size;
        }

        if $max > @array.elems {
            $max = @array.elems;
        }

        if ($begin < 0) {
           die '$offset must be non-negative.';
        }

        if ($max < 0) {
           die '$size must be non-negative.';
        }

        my @retval = @array.delete($begin..^$max);

        my @temp = @array[0..^$begin];
        @temp.push(@values);
        @temp.push(@array[$max..^@array.elems]);
        @array = @temp;

        return @retval;
    }
}

my class Array is List {
    method perl(\:) {
        self // return self.typename;
        "[" ~ self.map(*.perl).join(', ') ~ "]" ~ (self.flattens ?? ".list" !! "");
    }

    method delete(*@indices) {
        my @result;
        my @i = @indices.map({
            when Range { $_.iterator.list }
            when Callable { $_(+self) }
            when * < 0 { die "Negative index not allowed, please use WhateverCode" }
            $_;
        });
        for @i -> $i {
            @result.push(self[$i]);
            self[$i] = Any;
        }
        self.pop while ?self && !defined self[*-1];
        return @result;
    }
}

# Not connected to Hash because Stash contains bvalues while Hash
# holds values directly.
my class Stash does Associative {
    method at_key($key) {
        Q:CgOp { (stash_at_key (@ {self}) (obj_getstr {$key})) } }
    method bind_key($key, \to) {
        Q:CgOp { (stash_bind_key (@ {self}) (obj_getstr {$key}) {to}) } }
    method delete_key($key) {
        Q:CgOp { (stash_delete_key (@ {self}) (obj_getstr {$key})) } }
    method exists_key($key) {
        Q:CgOp { (stash_exists_key (@ {self}) (obj_getstr {$key})) } }
}

my class PseudoStash does Associative {
    has $.name;

    method at_key($key) {
        Q:CgOp { (pstash_at_key (@ {self}) (obj_getstr {$key})) } }
    method bind_key($key, \to) {
        Q:CgOp { (pstash_bind_key (@ {self}) (obj_getstr {$key}) {to}) } }
}

my class Hash does Associative {
    method new() { unitem(Q:CgOp { (box Hash (varhash_new)) }) }

    method any() { any self.keys }
    method none() { none self.keys }
    method all() { all self.keys }
    method one() { one self.keys }

    method Capture () {
        Q:CgOp {
            (letn n (obj_newblank (obj_llhow (@ {Capture})))
              (setslot Capture $!positionals (l n) (fvarlist_new))
              (setslot Capture $!named (l n) (varhash_dup
                  (unbox varhash (@ {self}))))
              (l n))
        }
    }

    method keys() { Q:CgOp { (hash_keys {self}) } }
    method values() { Q:CgOp { (hash_values {self}) } }
    method pairs() { Q:CgOp { (hash_pairs {self}) } }
    method list() { Q:CgOp { (hash_pairs {self}) } }
    method kv() { Q:CgOp { (hash_kv {self}) } }

    method Numeric() { +@(self) }
    method Str() { @(self).map(* ~ "\n").join }

    method invert() {
        my @new;
        for self.kv -> $k, $v { push @new, $v => $k }
        @new
    }

    method !array-push(Str $key, Mu $value) {
        if not self{$key}:exists {
            self{$key} = $value;
        } elsif self{$key} ~~ Array {
            self{$key}.push: $value;
        } else {
            self{$key} = [self{$key}, $value];
        }
    }

    method push(*@v) {
        my Mu $previous;
        my $has_previous;
        for @v -> $e {
            if $has_previous {
                self!array-push($previous.Str, $e);
                $has_previous = 0;
            } elsif $e.^isa(Enum) {
                self!array-push($e.key.Str, $e.value);
            } else {
                $previous = $e;
                $has_previous = 1;
            }
        }
        self;
    }

    # Rakudo extensions compatibility - DO NOT USE
    method delete($key) { self.{$key}:delete }
    method exists($key) { self.{$key}:exists }

    method at_key($key) { self.{$key} }
    method exists_key($key) { self.{$key}:exists }
    method delete_key($key) { self.{$key}:delete }

    method perl(\:) {
        self // return self.typename;
        '{' ~ (self{self.keys.sort}:p).map(*.perl).join(', ') ~ '}' ~
            (self.flattens ?? ".hash" !! "")
    }

    method fmt($format = "%s\t%s", $sep = "\n") {
         self.pairs.map({ .fmt($format) }).join($sep)
    }
}

my class Whatever {
    method immutable() { True }
    method ACCEPTS(\x) { defined(self) || x.^isa(Whatever) }
}
# XXX use an unshadowable name
BEGIN my $__Whatever := Q:CgOp { (blackhole {Whatever.new}) };

my class Enum is Cool {
    has $.key;
    has Mu $.value;

    method Capture () {
        Q:CgOp {
            (letn n (obj_newblank (obj_llhow (@ {Capture})))
                  d (varhash_new)
              (setslot Capture $!positionals (l n) (fvarlist_new))
              (setslot Capture $!named (l n) (l d))
              (varhash_setindex (obj_getstr {$!key})
                (l d) {$!value})
              (l n))
        }
    }

    method immutable() {
        self // return True;
        IMMUTABLE($!key) || IMMUTABLE($!value);
    }

    method kv() {
        ($.key, $.value);
    }

    method perl() { defined(self) ?? (self.key.perl ~ ' => ' ~ self.value.perl) !! self.typename }

    method pairs() {
        self.flat;
    }
}

my class Pair is Enum {
    method ACCEPTS(\other) {
        self // nextsame;
        other.^does(Hash) ?? ($.value.ACCEPTS(other{$.key})) !!
            (?$.value) == (?other.?"$.key"())
    }
    method Str() {
        $.key ~ "\t" ~ $.value
    }
    method invert() {
        $.value => $.key
    }
    method fmt(Str $format = "%s\t%s") {
        return sprintf($format, $.key, $.value);
    }
}

# XXX This ought to be more read-only
my class EnumMap does Associative {
    has %!by-key;
    has %!by-value;
    has @!values;
    has @!keys;
    has $.data-type;

    method new(*@pairs) {
        self := self.bless(*);
        my $last = -1;
        my $ixn = 0;
        my $str;
        my $int;
        for @pairs -> $p {
            my ($k, $v);
            if $p ~~ Pair {
                $k ::= ~$p.key;
                $v ::= $p.value;
            } else {
                $k ::= ~$p;
                $v ::= $last.succ;
            }
            if $v ~~ Int { $int = 1; }
            elsif $v ~~ Str { $str = 1; }
            else {
                die "Enum values must be Int or Str, but got $v.typename()";
            }
            $last = $v;
            %!by-key{$k} = $ixn;
            %!by-value{$v} //= $ixn;
            push @!keys, $k;
            push @!values, $v;
            $ixn++;
        }
        die "Enum must have at least one value" unless $int || $str;
        die "Enum must contain integer or string values, not both" if $int && $str;
        $!data-type := $int ?? 'Int' !! 'Str';
        unitem(self);
    }

    method Numeric() { +@!keys }
    method _index_to_key($i) { @!keys[$i] }
    method _index_to_value($i) { @!values[$i] }
    method _lookup($w) {
        %!by-key{$w} // %!by-value{$w} // die "No match"
    }
    method iterator() { self.list.iterator }
    method list() { @!keys Z=> @!values }
    method hash() { %!by-key }
    method keys() { @!keys }
    method values() { @!values }
    method invert() { @!values Z=> @!keys }
    method kv() { @!keys Z @!values }
    method pairs() { self.list }
    method at_key(\k) { (my $ ::= @!values[%!by-key.{k}]) }
    method exists_key($k) { self{$k}:exists }
}
BEGIN { $Bool::_enums ::= EnumMap.new("False" => 0, "True" => 1) }
my enum Order (:Increase(-1), :Same(0), :Decrease(1));

class Set does Associative {
    has Bool %!elems;

    method keys { %!elems.keys }
    method values { %!elems.values }
    method elems returns Int { %!elems.elems }
    method exists($a) returns Bool { %!elems.exists($a) }
    method Bool { %!elems.Bool }
    method Numeric { %!elems.Numeric }
    method hash { %!elems.hash }
    method at_key($k) { ?(%!elems{$k} // False) }
    method exists_key($k) { self.exists($k) }

    # Constructor
    method new(*@args --> Set) {
        my %e;
        sub register-arg($arg) {
            given $arg {
                when Pair { %e{.key} = True; }
                when Set | KeySet { for .keys -> $key { %e{$key} = True; } }
                when Associative { for .pairs -> $p { register-arg($p); } }
                when Positional { for .list -> $p { register-arg($p); } }
                default { %e{$_} = True; }
            }
        }

        for @args {
            register-arg($_);
        }
        self.bless(*, :elems(%e));
    }

    submethod BUILD (%!elems) { }

    # Coercions to and from
    method postcircumfix:<( )> ($s --> Set) { to-set($s) }
    multi to-set (Set $set --> Set) { $set }
    multi to-set (KeySet $set --> Set) { Set.new: $set }
    multi to-set (Bag $bag --> Set) { Set.new: $bag }
    multi to-set (KeyBag $bag --> Set) { Set.new: $bag }
    multi to-set (@elems --> Set) { Set.new: @elems }
    multi to-set ([*@elems] --> Set) { Set.new: @elems }
    multi to-set (%elems --> Set) { Set.new: %elems.keys }
    multi to-set ($elem --> Set) { die "Cannot coerce $elem.perl() to a Set; use set($elem.perl()) to create a one-element set" }

    submethod Str(Any:D $ : --> Str) { %!elems.keys().join(" ") }
    submethod gist(Any:D $ : --> Str) { "set({ %!elems.keys».gist.join(', ') })" }
    submethod perl(Any:D $ : --> Str) { 'set(' ~ join(', ', map { .perl }, %!elems.keys) ~ ')' }

    method iterator() { %!elems.keys.iterator }
    method list() { %!elems.keys }
    method pick($count = 1) { %!elems.keys.pick($count) }
    method roll($count = 1) { %!elems.keys.roll($count) }

    # TODO: WHICH will require the capability for >1 pointer in ObjAt
}

# Set operators

sub set(*@args --> Set) {
    Set.new(@args);
}

constant term:<∅> = set();

proto sub infix:<∈>($, $ --> Bool) is equiv(&infix:<==>) {*}
multi sub infix:<∈>($a, Any $b --> Bool) { $a ∈ Set($b) }
multi sub infix:<∈>($a, Set $b --> Bool) { $b.exists($a) }
only sub infix:<(elem)>($a, $b --> Bool) is iffy { $a ∈ $b }
only sub infix:<∉>($a, $b --> Bool) is equiv(&infix:<==>) { $a !∈ $b }

proto sub infix:<∋>($, $ --> Bool) is equiv(&infix:<==>) {*}
multi sub infix:<∋>(Any $a, $b --> Bool) { Set($a) ∋ $b }
multi sub infix:<∋>(Set $a, $b --> Bool) { $a.exists($b) }
only sub infix:<(cont)>($a, $b --> Bool) is iffy { $a ∋ $b }
only sub infix:<∌>($a, $b --> Bool) is equiv(&infix:<==>) { $a !∋ $b }

proto sub infix:<∪>($, $ --> Set) is equiv(&infix:<X>) {*}
multi sub infix:<∪>(Any $a, Any $b --> Set) { Set($a) ∪ Set($b) }
multi sub infix:<∪>(Set $a, Set $b --> Set) { Set.new: $a.keys, $b.keys }
only sub infix:<(|)>($a, $b) is equiv(&infix:<X>) { $a ∪ $b }

proto sub infix:<∩>($, $ --> Set) is equiv(&infix:<X>) {*}
multi sub infix:<∩>(Any $a, Any $b --> Set) { Set($a) ∩ Set($b) }
multi sub infix:<∩>(Set $a, Set $b --> Set) { Set.new: $a.keys.grep: -> $k { ?$b{$k} } }
only sub infix:<(&)>($a, $b) is equiv(&infix:<X>) { $a ∩ $b }

proto sub infix:<(-)>($, $ --> Set) is equiv(&infix:<X>) {*}
multi sub infix:<(-)>(Any $a, Any $b --> Set) { Set($a) (-) Set($b) }
multi sub infix:<(-)>(Set $a, Set $b --> Set) { Set.new: $a.keys.grep: * ∉ $b }

proto sub infix:<(^)>($, $ --> Set) is equiv(&infix:<X>) {*}
multi sub infix:<(^)>(Any $a, Any $b --> Set) { Set($a) (^) Set($b) }
multi sub infix:<(^)>(Set $a, Set $b --> Set) { ($a (-) $b) ∪ ($b (-) $a) }

# TODO: polymorphic eqv
# multi sub infix:<eqv>(Any $a, Any $b --> Bool) { Set($a) eqv Set($b) }
# multi sub infix:<eqv>(Set $a, Set $b --> Bool) { $a == $b and so $a.keys.all ∈ $b }

proto sub infix:<⊆>($, $ --> Bool) is equiv(&infix:<==>) {*}
multi sub infix:<⊆>(Any $a, Any $b --> Bool) { Set($a) ⊆ Set($b) }
multi sub infix:<⊆>(Set $a, Set $b --> Bool) { $a <= $b and so $a.keys.all ∈ $b }
only sub infix:['(<=)']($a, $b --> Bool) is equiv(&infix:<==>) { $a ⊆ $b }
only sub infix:<⊈>($a, $b --> Bool) is equiv(&infix:<==>) { $a !⊆ $b }

proto sub infix:<⊂>($, $ --> Bool) is equiv(&infix:<==>) {*}
multi sub infix:<⊂>(Any $a, Any $b --> Bool) { Set($a) ⊂ Set($b) }
multi sub infix:<⊂>(Set $a, Set $b --> Bool) { $a < $b and so $a.keys.all ∈ $b }
only sub infix:['(<)']($a, $b --> Bool) is equiv(&infix:<==>) { $a ⊂ $b }
only sub infix:<⊄>($a, $b --> Bool) is equiv(&infix:<==>) { $a !⊂ $b }

proto sub infix:<⊇>($, $ --> Bool) is equiv(&infix:<==>) {*}
multi sub infix:<⊇>(Any $a, Any $b --> Bool) { Set($a) ⊇ Set($b) }
multi sub infix:<⊇>(Set $a, Set $b --> Bool) { $a >= $b and so $b.keys.all ∈ $a }
only sub infix:['(>=)']($a, $b --> Bool) is equiv(&infix:<==>) { $a ⊇ $b }
only sub infix:<⊉>($a, $b --> Bool) is equiv(&infix:<==>) { $a !⊇ $b }

proto sub infix:<⊃>($, $ --> Bool) is equiv(&infix:<==>) {*}
multi sub infix:<⊃>(Any $a, Any $b --> Bool) { Set($a) ⊃ Set($b) }
multi sub infix:<⊃>(Set $a, Set $b --> Bool) { $a > $b and so $b.keys.all ∈ $a }
only sub infix:['(>)']($a, $b --> Bool) is equiv(&infix:<==>) { $a ⊃ $b }
only sub infix:<⊅>($a, $b --> Bool) is equiv(&infix:<==>) { $a !⊃ $b }

class KeySet does Associative {
    has Bool %!elems;

    method keys { %!elems.keys }
    method values { %!elems.values }
    method elems returns Int { %!elems.elems }
    method exists($a) returns Bool { %!elems.exists($a) && %!elems{$a} }
    method Bool { %!elems.Bool }
    method Numeric { %!elems.Numeric }
    method hash { %!elems.hash }
    method at_key($k) {
        Proxy.new(FETCH => { %!elems{$k}:exists ?? True !! False },
                  STORE => -> $, $value { if $value { %!elems{$k} = True } else { %!elems{$k}:delete }});
    }
    method exists_key($k) { self.exists($k) }
    method delete_key($k) { %!elems{$k}:delete }

    # Constructor
    method new(*@args --> KeySet) {
        my %e;
        sub register-arg($arg) {
            given $arg {
                when Pair { %e{.key} = True; }
                when Set | KeySet { for .keys -> $key { %e{$key} = True; } }
                when Associative { for .pairs -> $p { register-arg($p); } }
                when Positional { for .list -> $p { register-arg($p); } }
                default { %e{$_} = True; }
            }
        }

        for @args {
            register-arg($_);
        }
        self.bless(*, :elems(%e));
    }

    submethod BUILD (%!elems) { }

    submethod Str(Any:D $ : --> Str) { %!elems.keys().join(" ") }
    submethod gist(Any:D $ : --> Str) { "keyset({ %!elems.keys».gist.join(', ') })" }
    submethod perl(Any:D $ : --> Str) { 'KeySet.new(' ~ join(', ', map { .perl }, %!elems.keys) ~ ')' }

    method iterator() { %!elems.keys.iterator }
    method list() { %!elems.keys }
    method pick($count = 1) { %!elems.keys.pick($count) }
    method roll($count = 1) { %!elems.keys.roll($count) }
}

role Baggy { Any }

class Bag does Associative does Baggy {
    has Int %!elems; # should be UInt

    method keys { %!elems.keys }
    method values { %!elems.values }
    method elems returns Int { [+] self.values }
    method exists($a) returns Bool { %!elems.exists($a) }
    method Bool { %!elems.Bool }
    method Numeric { self.elems }
    method hash { %!elems.hash }
    method at_key($k) { +(%!elems{$k} // 0) }
    method exists_key($k) { self.exists($k) }

    # Constructor
    method new(*@args --> Bag) {
        my %e;
        sub register-arg($arg) {
            given $arg {
                when Pair { if .value { if %e{.key}:exists { %e{.key} += .value } else { %e{.key} = .value } } }
                when Set | KeySet { for .keys -> $key { %e{$key}++; } }
                when Associative { for .pairs -> $p { register-arg($p) } }
                when Positional { for .list -> $p { register-arg($p) } }
                default { %e{$_}++; }
            }
        }

        for @args {
            register-arg($_);
        }
        self.bless(*, :elems(%e));
    }

    submethod BUILD (%!elems) { }

    submethod Str(Any:D $ : --> Str) { %!elems.pairs.map({ $_.key xx $_.value }).flat.join(" ") }
    submethod gist(Any:D $ : --> Str) { "bag({ self.pairs>>.gist.join(', ') })" }
    submethod perl(Any:D $ : --> Str) { 'Bag.new(' ~ %!elems.perl ~ ')' }

    method iterator() { %!elems.pairs.iterator }
    method list() { %!elems.keys }
    method pairs() { %!elems.pairs }

    method pick($count = 1) { my $kb = KeyBag.new(self); $kb.pick($count); }
    method roll($count = 1) { my $kb = KeyBag.new(self); $kb.roll($count); }
}

sub bag(*@a) {
    Bag.new(|@a);
}

multi sub infix:<∪>(Baggy $a, Any $b --> Bag) { $a ∪ bag($b) }
multi sub infix:<∪>(Any $a, Baggy $b --> Bag) { bag($a) ∪ $b }
multi sub infix:<∪>(Baggy $a, Baggy $b --> Bag) { bag((set($a) ∪ set($b)).map({ ; $_ => $a{$_} max $b{$_} })) }

multi sub infix:<∩>(Baggy $a, Any $b --> Bag) { $a ∩ bag($b) }
multi sub infix:<∩>(Any $a, Baggy $b --> Bag) { bag($a) ∩ $b }
multi sub infix:<∩>(Baggy $a, Baggy $b --> Bag) { bag((set($a) ∪ set($b)).map({ ; $_ => $a{$_} min $b{$_} })) }

proto sub infix:<⊍>($, $ --> Bag) is equiv(&infix:<X>) {*}
multi sub infix:<⊍>(Any $a, Any $b --> Bag) { bag($a) ⊍ bag($b) }
multi sub infix:<⊍>(Bag $a, Bag $b --> Bag) { bag((set($a) ∪ set($b)).map({ ; $_ => $a{$_} * $b{$_} })) }
only sub infix:<(.)>($a, $b --> Bag) is equiv(&infix:<X>) { $a ⊍ $b }

proto sub infix:<⊎>($, $ --> Bag) is equiv(&infix:<X>) {*}
multi sub infix:<⊎>(Any $a, Any $b --> Bag) { bag($a) ⊎ bag($b) }
multi sub infix:<⊎>(Bag $a, Bag $b --> Bag) { bag((set($a) ∪ set($b)).map({ ; $_ => $a{$_} + $b{$_} })) }
only sub infix:<(+)>($a, $b --> Bag) is equiv(&infix:<X>) { $a ⊎ $b }

proto sub infix:<≼>($, $ --> Bool) is equiv(&infix:<==>) {*}
multi sub infix:<≼>(Baggy $a, Baggy $b --> Bool) { so all $a.keys.map({ $a{$_} <= $b{$_} }) }

proto sub infix:<≽>($, $ --> Bool) is equiv(&infix:<==>) {*}
multi sub infix:<≽>(Baggy $a, Baggy $b --> Bool) { so all $b.keys.map({ $b{$_} <= $a{$_} }) }

class KeyBag does Associative does Baggy {
    has Int %!elems; # should be UInt

    method keys { %!elems.keys }
    method values { %!elems.values }
    method elems returns Int { [+] self.values }
    method exists($a) returns Bool { %!elems.exists($a) }
    method Bool { %!elems.Bool }
    method Numeric { self.elems }
    method hash { %!elems.hash }
    method at_key($k) {
        Proxy.new(FETCH => { %!elems{$k}:exists ?? %!elems{$k} !! 0 },
                  STORE => -> $, $value { if $value > 0 { %!elems{$k} = $value } else { %!elems{$k}:delete }});
    }
    method exists_key($k) { self.exists($k) }
    method delete_key($k) { %!elems{$k}:delete }

    # Constructor
    method new(*@args --> KeyBag) {
        my %e;
        sub register-arg($arg) {
            given $arg {
                when Pair { if .value { if %e{.key}:exists { %e{.key} += .value } else { %e{.key} = .value } } }
                when Set | KeySet { for .keys -> $key { %e{$key}++; } }
                when Associative { for .pairs -> $p { register-arg($p) } }
                when Positional { for .list -> $p { register-arg($p) } }
                default { %e{$_}++; }
            }
        }

        for @args {
            register-arg($_);
        }
        self.bless(*, :elems(%e));
    }

    submethod BUILD (%!elems) { }

    submethod Str(Any:D $ : --> Str) { %!elems.pairs.map({ $_.key xx $_.value }).flat.join(" ") }
    submethod gist(Any:D $ : --> Str) { "keybag({ self.pairs>>.gist.join(', ') })" }
    submethod perl(Any:D $ : --> Str) { 'KeyBag.new(' ~ %!elems.perl ~ ')' }

    method iterator() { %!elems.pairs.iterator }
    method list() { %!elems.keys }
    method pairs() { %!elems.pairs }

    method pick($count = 1) {
        return self.roll if $count ~~ Num && $count == 1;

        my $temp-bag = KeyBag.new(self);
        my $lc = $count ~~ Whatever ?? Inf !! $count;
        gather while $temp-bag && $lc-- {
            my $choice = $temp-bag.roll;
            take $choice;
            $temp-bag{$choice}--;
        }
    }
    method roll($count = 1) {
        my @inverse-mapping;
        my $a = 0;
        for %!elems.pairs -> $pair {
            $a += $pair.value;
            @inverse-mapping.push((+$a) => $pair.key);
        }

        sub choose {
            my $choice = $a.rand;
            my $i = 0;
            for @inverse-mapping -> $im {
                if $choice ~~ $i ..^ +$im.key {
                    return $im.value;
                }
                $i = $im.key;
            }
        }

        return choose() xx * if $count ~~ Whatever;
        return choose() if $count == 1;
        return choose() xx $count;
    }
}

my class Junction is Mu {
    has $!kind_;
    has $!eigenstates_;

    method !create($kind, $eigenstates) { Q:CgOp {
        (letn ob (obj_newblank (obj_llhow (@ {self})))
          (setslot Junction $!kind_ (l ob) (@ {$kind}))
          (setslot Junction $!eigenstates_ (l ob) (@ {$eigenstates}))
          (l ob))
    } }
    method !kind() { Q:CgOp { (getslot Junction $!kind_ obj (@ {self})) } }
    method !eigenstates() { Q:CgOp { (getslot Junction $!eigenstates_ obj (@ {self})) } }

    my @kinds = <all none one any>;
    method perl() {
        defined(self) ?? (@kinds[self!kind] ~ (anon @ := self!eigenstates).perl)
            !! "Junction"
    }
    method immutable() { self // return True; self!eigenstates.immutable }

    method Str() { defined(self) ?? self.perl !! "Junction()" }

    method from-parcel(Int $kind, \pcl) {
        self!create($kind, pcl)
    }

    method ACCEPTS(Mu \other) {
        defined(self) ??
            ?(self.FALLBACK("ACCEPTS", other)) !!
            other.^isa(self)
    }
}
# }}}
# List utilities {{{
sub _vivify_array_at_pos(\ary, $ix) {
    Q:CgOp { (newvnewarrayvar (class_ref mo Any) {ary} (cast int (obj_getnum {$ix})) (@ {Any})) };
}

my class GatherIterator is IterCursor {
    has $.frame;
    has $!reify;

    method reify() {
        my $*nextframe;
        $!reify // ($!reify = (
            Q:CgOp {
                (letn getv (cotake (cast frame (@ {$!frame})))
                  (setslot (obj_llhow (@ {self})) $!frame (@ {self}) {Any})
                  (box Parcel (ternary (== (@ {EMPTY}) (@ (l getv)))
                    (fvarlist_new)
                    (fvarlist_new
                      (l getv)
                      {GatherIterator.new(frame => $*nextframe)}))))
            }));
    }
}

sub _gather($fr) {
    &infix:<,>(GatherIterator.new(frame => $fr)).list
}

sub reverse(*@array) {
    my @acc;
    push @acc, pop(@array) while @array;
    @acc;
}

sub classify($mapper, *@values) { @values.classify($mapper) }
sub categorize($mapper, *@values) { @values.categorize($mapper) }
sub min(*@args, :&by = &infix:<cmp>) { @args.min(&by) }
sub max(*@args, :&by = &infix:<cmp>) { @args.max(&by) }
sub minmax(*@args, :&by = &infix:<cmp>) { @args.minmax(&by) }
sub end($a) { $a.end }
sub join($tween = "", *@stuff) { @stuff.join($tween) }

sub invert(%h) { %h.invert }
sub keys($h) { $h.keys }
sub values($h) { $h.values }
sub kv($p) { $p.kv }
sub pairs($p) { $p.pairs }
sub elems($p) { $p.elems }

sub sort(*@values) {
    if @values && @values[0] ~~ Callable {
        my $cmp = @values.shift;
        @values.sort($cmp);
    } else {
        @values.sort;
    }
}

sub first(Mu $test, *@bits) { @bits.first($test) }

sub _hash_constructor(\parcel) { my $r := (anon %hash = parcel); $r }
sub _make_capture(|c) { c }

# strange API for this, no?
my class Proxy {
    method new(:$FETCH, :$STORE, :$BIND) {
        Q:CgOp { (var_new_tied (@ {$BIND}) (@ {$FETCH}) (@ {$STORE})) }
    }
}

# a few notes: Not all of these are protos yet, so the failure candidates
# for x, etc are left out. No candidates for operators that don't exist yet.
# No candidates are needed for chain operators or list operators, reduce can
# handle those fine.
multi infix:<**>() { 1 }
multi infix:<*>() { 1 }
multi infix:</>() { die "No zero-arg meaning for infix:</>" }
multi infix:<%>() { die "No zero-arg meaning for infix:<%>" }
#multi infix:<x>() { die "No zero-arg meaning for infix:<x>" }
#multi infix:<xx>() { die "No zero-arg meaning for infix:<xx>" }
multi infix:<+&>() { -1 }
multi infix:«+<»() { die "No zero-arg meaning for infix:<< +< >>" }
multi infix:«+>»() { die "No zero-arg meaning for infix:<< +> >>" }
#multi infix:«~&»() { die "No zero-arg meaning for infix:<~&>" }
#multi infix:«~<»() { die "No zero-arg meaning for infix:<< ~< >>" }
#multi infix:«~>»() { die "No zero-arg meaning for infix:<< ~> >>" }
multi infix:<+>() { 0 }
multi infix:<->() { 0 }
multi infix:<+|>() { 0 }
multi infix:<+^>() { 0 }
#multi infix:<~|>() { '' }
#multi infix:<~^>() { '' }

#multi infix:<&&>() { True }
#multi infix:<||>() { False }
#multi infix:<^^>() { False }
#multi infix:<//>() { Any }

sub reduceop($triangle, $list, $right, $chain, $func, *@items) {
    if $triangle {
        if $chain {
            gather {
                my $ok = True;
                if @items {
                    take True;
                    my Mu $last = shift @items;
                    while @items {
                        my Mu $next = shift @items;
                        my Mu $val ::= ($ok &&= $func($last, $next));
                        take $val;
                        $last = $next;
                    }
                }
            }
        }
        elsif $list {
            my @pool;
            gather {
                while @items {
                    push @pool, shift @items;
                    take reduceop(False, $list, $right, $chain, $func, @pool);
                }
            }
        }
        elsif $right {
            gather {
                while @items >= 2 {
                    my Mu $right ::= pop @items;
                    take $right;
                    my Mu $left = pop @items;
                    push @items, $func($left,$right);
                }
                if @items {
                    my Mu $last ::= shift @items;
                    take $last;
                }
            }
        }
        else { # left assoc
            gather {
                if @items {
                    my Mu $cumu ::= shift @items;
                    take $cumu;
                    while @items {
                        my Mu $new ::= ($cumu ::= $func($cumu, shift @items));
                        take $new;
                    }
                }
            }
        }
    }
    else {
        if $list {
            $func(|@items);
        }
        elsif $chain {
            my $ok = True;
            while @items >= 2 {
                $ok &&= $func(@items[0], @items[1]);
                shift @items;
            }
            $ok;
        }
        elsif $right {
            while @items >= 2 {
                my Mu $r = pop @items;
                my Mu $l = pop @items;
                push @items, $func($l,$r);
            }
            @items ?? @items[0] !! $func();
        }
        else { # left
            while @items >= 2 {
                my Mu $l = shift @items;
                my Mu $r = shift @items;
                unshift @items, $func($l,$r);
            }
            @items ?? @items[0] !! $func();
        }
    }
}

my class NieczaLSM {
    has Cool $.source;
    has @!substitutions;

    has Int $!index = 0;
    has Int $!next_match;
    has $!next_substitution;
    has $!substitution_length;

    has Str $.unsubstituted_text;
    has Str $.substituted_text;

    method add_substitution($key, $value) {
        push @!substitutions, $key => $value;
    }

    method compare_substitution($substitution, Int $pos, Int $length) {
        if $!next_match > $pos
           || $!next_match == $pos && $!substitution_length < $length {

            $!next_match = $pos;
            $!substitution_length = $length;
            $!next_substitution = $substitution;
        }
    }

    multi method triage_substitution($substitution where { $^s.key ~~ Regex }) {
        my $key = $substitution.key;
        return unless $.source.substr($!index) ~~ $key;
        self.compare_substitution($substitution, $!index + $/.from.Int, $/.to.Int - $/.from.Int);
    }

    multi method triage_substitution($substitution where { $^s.key ~~ Cool }) {
        return unless defined index($.source, $substitution.key, $!index);
        self.compare_substitution($substitution,
                                  index($.source, $substitution.key, $!index),
                                  $substitution.key.chars);
    }

    multi method triage_substitution($substitution) {
        die "Don't know how to handle a {$substitution.WHAT} as a substitution key";
    }

    multi method increment_index(Regex $s) {
        $.source.substr($!index) ~~ $s;
        $!index = $!next_match + $/.chars.Int;
    }

    multi method increment_index(Cool $s) {
        $!index = $!next_match + $s.chars;
    }

    method next_substitution() {
        $!next_match = $.source.chars;

        for @!substitutions {
            self.triage_substitution($_);
        }

        $!unsubstituted_text
            = $.source.substr($!index, $!next_match - $!index);
        if defined $!next_substitution {
            my $result = $!next_substitution.value;
            $!substituted_text
                = $result ~~ Callable ?? ~$result() !! $result;
            self.increment_index($!next_substitution.key);
        }

        return $!next_match < $.source.chars;
    }
}

sub Niecza-trans($str, *@changes) {
    my sub expand($s) {
        return $s.list if $s ~~ Positional;
        gather for $s.comb(/ (\w) '..' (\w) | . /, :match) {
            if .[0] {
                take $_ for ~.[0] .. ~.[1];
            } else {
                take ~$_;
            }
        }
    }

    my $lsm = NieczaLSM.new(:source($str));
    for (@changes) -> $p {
        die "$p.perl() is not a Pair" unless $p ~~ Pair;
        if $p.key ~~ Regex {
            $lsm.add_substitution($p.key, $p.value);
        }
        elsif $p.value ~~ Callable {
            my @from = expand $p.key;
            for @from -> $f {
                $lsm.add_substitution($f, $p.value);
            }
        }
        else {
            my @from = expand $p.key;
            my @to = expand $p.value;
            if @to {
                @to = @to xx ceiling(@from / @to);
            } else {
                @to = '' xx @from;
            }
            for @from Z @to -> $f, $t {
                $lsm.add_substitution($f, $t);
            }
        }
    }

    my $r = "";
    while $lsm.next_substitution {
        $r ~= $lsm.unsubstituted_text ~ $lsm.substituted_text;
    }
    $r ~= $lsm.unsubstituted_text;

    return $r;
}

# }}}
# Regular expression support {{{
my grammar Cursor is Any does Associative does Positional {
    method at_key($k) { self.{$k} }
    method at_pos($k) { self.[$k] }
    method suppose($rx) {
        my $*IN_SUPPOSE = True;
        my $*FATALS = 0;
        my @*WORRIES;
        my %*WORRIES;
        my $*HIGHWATER = -1;
        my $*HIGHEXPECT = {};
        try {
            my $ret = head($rx(self));
            if ($ret) { return $ret }
        };
        return ();
    }
    method O (*%hash) {
        Q:CgOp { (cursor_O (cast cursor (@ {self}))
                           (unbox varhash (@ {%hash}))) }
    }
    method ast () { Q:CgOp { (cursor_ast (cast cursor (@ {self}))) } }
    method list () { @( self.Capture ) }
    method flat () { @( self.Capture ) }
    method iterator () { self.flat.iterator }
    method hash () { %( self.Capture ) }
    method Capture () { Q:CgOp {
        (letn cap (obj_newblank (obj_llhow (@ {Capture})))
          (cursor_unpackcaps (cast cursor (@ {self})) (l cap))
          (l cap))
    } }
    method cursor_start($str, $act?) { Q:CgOp { (cursor_start
        (@ {self}) (obj_getstr {$str}) (@ {$act})) } }
    method pos() { Q:CgOp { (box Num (cast num (cursor_pos
        (cast cursor (@ {self}))))) } }
    method to() { Q:CgOp { (box Num (cast num (cursor_pos
        (cast cursor (@ {self}))))) } }
    method cursor($np) { Q:CgOp { (cursor_butpos
        (cast cursor (@ {self})) (cast int (obj_getnum {$np}))) } }
    method orig() { Q:CgOp {
        (box Str (cursor_backing (cast cursor (@ {self})))) } }
    method ws() { Q:CgOp { (cursor_dows (cast cursor (@ {self}))) } }
    method CURSOR() { self }
    method FAILGOAL ($stop, $name, $startpos) { #OK not used
        my $s = "'$stop'";
        $s = '"\'"' if $s eq "'''";
        die("Unable to parse $name\nCouldn't find final $s; gave up");
    }
    # definitions from UTS18
    token alpha { <:Alphabetic + [_]> } # XXX: STD expects to include _
    token lower { <:Lowercase> }
    token upper { <:Uppercase> }
    token punct { <:Punctuation> }
    token digit { \d }
    token xdigit { <:Nd + :Hex_Digit> }
    token alnum { <:Alphabetic + :Nd + [_]> }
    token space { \s }
    token blank { \h }
    token cntrl { <:Control> }
    token graph { <:ANY - :Whitespace - :Control - :Surrogate - :Unassigned> }
    token print { <+graph + blank - cntrl> }
    token word { \w }
    token ident { <.alpha> \w* }
}

my class Match is Cool does Associative does Positional {
    method at_key($k) { self.{$k} }
    method at_pos($k) { self.[$k] }
    method ACCEPTS($) { self // nextsame }
    method list () { @( self.Capture ) }
    method hash () { %( self.Capture ) }
    method flat () { @( self.Capture ) }
    method iterator () { self.flat.iterator }
    method Numeric() { self // nextsame; +(~self) }

    # yeah these could all be more efficient.
    method kv() { (@(self).kv, %(self).kv).flat }
    method keys() { (@(self).keys, %(self).keys).flat }
    method values() { (@(self), %(self).values).flat }

    method Capture () { Q:CgOp {
        (letn cap (obj_newblank (obj_llhow (@ {Capture})))
          (cursor_unpackcaps (cast cursor (@ {self})) (l cap))
          (l cap))
    } }
    method new($) { die "Match.new NYI" }
    method from() { Q:CgOp { (box Num (cast num (cursor_from
        (cast cursor (@ {self}))))) } }
    method to() { Q:CgOp { (box Num (cast num (cursor_pos
        (cast cursor (@ {self}))))) } }
    method pos() { self.to }
    method orig() { Q:CgOp {
        (box Str (cursor_backing (cast cursor (@ {self})))) } }
    method ast () { Q:CgOp { (cursor_ast (cast cursor (@ {self}))) } }
    method chars() { defined(self) ?? $.to - $.from !! 0 }
    method perl() {
        self // nextsame;
        my @pos = @(self);
        @pos = () if @pos == 1 && @pos[0] === self;

        "#<match from({ self.from }) to({ self.to }) text({ self }) pos({ @pos.perl }) named({ %(self).perl })>"
    }
    method CURSOR() { Q:CgOp { (cursor_unmatch (cast cursor (@ {self}))) } }
    method cursor() { Q:CgOp { (cursor_unmatch (cast cursor (@ {self}))) } }
    method reduced() { Q:CgOp { (box Str (cursor_reduced (cast cursor (@ {self})))) } }
    method synthetic(:$cursor!, :$method = "", :$captures, :$from!, :$to!) {
        my $*match;
        Q:CgOp {
            (prog
              (cursor_synthetic
                (cast cursor (@ {$cursor})) (obj_getstr {$method})
                (cast int (obj_getnum {$from}))
                (cast int (obj_getnum {$to}))
                {@$captures})
              {$*match})
        };
    }

    method caps() {
        my @caps = Q:CgOp { (cursor_allcaps {self}) }.sort({ .value.from });

        my $lpos = self.from;
        my $lnam = "beginning of match";
        for @caps {
            if .value.from < $lpos {
                warn "Capture {.key} starts at {.value.from} overlaps $lnam at $lpos";
            }
            $lpos = .value.to;
            $lnam = .key;
        }

        if self.to < $lpos {
            warn "End of match at {self.to} overlaps $lnam at $lpos";
        }

        @caps
    }

    method chunks() {
        my $lpos = self.from;
        my @chunks;
        for self.caps {
            if .value.from > $lpos {
                push @chunks, '~' => Match.synthetic(:cursor(self), :captures[],
                    :from($lpos), :to(.value.from));
            }
            push @chunks, $_;
            $lpos = .value.to;
        }
        if self.to > $lpos {
            push @chunks, '~' => Match.synthetic(:cursor(self), :captures[],
                :from($lpos), :to(self.to));
        }

        @chunks
    }

    method postmatch() { substr(self.orig, self.to) }
    method prematch() { substr(self.orig, 0, self.from) }
}

my class Regex is Method {
    method Bool() {
        return False unless defined self;
        my $fr = caller;
        # Hack - skip ExitRunloop frame
        $fr = $fr.caller unless $fr.line;
        Q:CgOp {
            (letn res {self.ACCEPTS($fr.hints('$_'))}
              (set_status (s $/) {$/})
              (asbool (l res)))
        };
    }
    method ACCEPTS($st) {
        self // nextsame;
        Q:CgOp {
            (letn ix (i 0)
                  str (obj_getstr {$st})
                  max (str_length (l str))
                  incr (cursor_start (@ {Cursor}) (l str) (@ {Any}))
                  csr (null cursor)
                  iter (null vvarlist)
              (whileloop 0 0 (<= (l ix) (l max)) (prog
                (l csr (cursor_butpos (l incr) (l ix)))
                (l ix (+ (l ix) (i 1)))
                (l iter (vvarlist_new_singleton
                    (subcall (@ {self}) (l csr))))
                (ternary (iter_hasflat (l iter))
                  (letn val (vvarlist_shift (l iter))
                    (set_status (s $/) (l val))
                    (return (newrwlistvar (@ (l val))) (l val)))
                  (prog))))
              (set_status (s $/) {Match})
              {Match})
        };
    }
}


my class Grammar is Cursor {
    method parse($text, :$rule = "TOP", :$actions) {
        my $match = (head grep { $_.to == chars $text },
            self.cursor_start($text, $actions)."$rule"()) // Match;
        Q:CgOp { (rnull (set_status (s '$/') {$match})) };
        $match;
    }
}
# }}}
# Other operators {{{
# TODO: these should be macros
sub WHAT(\x) { x.WHAT }
sub HOW(\x) { x.HOW }
constant Inf = 1 / 0;
my class RangeIter is IterCursor {
    has $.current;
    has $.limit;
    has $.exclusive;

    method reify() {
        my $c = $!current;
        my $cmp = $c cmp $!limit;
        ($cmp < 0) ?? ($c, RangeIter.new(current => $c.succ,
                    limit => $!limit, exclusive => $!exclusive)) !!
        ($cmp > 0 || $!exclusive) ?? () !!
            ($c,);
    }
}

my class Range is Cool does Positional {
    has $.min;
    has $.max;
    has $.excludes_min = False;
    has $.excludes_max = False;

    method new($min is copy, $max is copy, :$excludes_min = False, :$excludes_max = False) {
        $max = Inf if $max.^isa(Whatever);
        if $min ~~ Numeric && $max !~~ Numeric {
            $max = +$max;
        }
        $min = -Inf if $min.^isa(Whatever);
        unitem(self.bless(*, :$min, :$max, :$excludes_min, :$excludes_max));
    }

    method immutable() { self // return True; $!min.immutable && $!max.immutable }

    method list() { self.iterator.list }
    method flat() { self.iterator.flat }
    method at_pos(\key) { @(self).at_pos(key) }

    method bounds() { $.min, $.max }
    method from() { $.min }
    method to() { $.max }

    method minmax($cmp = &infix:<cmp>) { self.iterator.list.minmax($cmp) }

    method iterator() {
        &infix:<,>(RangeIter.new(:current($!excludes_min ?? $!min.succ !! $!min),
                      :limit($!max), :exclusive($!excludes_max))).iterator
    }

    method Str() { self.list.Str }
    method Numeric() { +self.list }
    method perl() {
        ( $.min.perl,
          ('^' if $.excludes_min),
          '..',
          ('^' if $.excludes_max),
          $.max.perl
        ).join('');
    }

    method ACCEPTS($topic) {
        !defined(self) ?? ($topic.^isa(Range)) !!
        ($topic.^isa(Range) ??
            (($.min == $topic.min)
                && ($.max == $topic.max)
                && ($.excludes_min == $topic.excludes_min)
                && ($.excludes_max == $topic.excludes_min)) !!
            (self!min_test($topic) && self!max_test($topic)))
    }

    method niecza_quantifier_min() {
        ($!min == -Inf ?? 0 !! $!min + $!excludes_min)
    }

    method niecza_quantifier_max() {
        ($!max == Inf ?? 2_147_483_647 !! $!max - $!excludes_max)
    }

    method !max_test($topic) {
        $topic before $.max || (!$.excludes_max && !($topic after $.max));
    }

    method !min_test($topic) {
        $.min before $topic || (!$.excludes_min && !($.min after $topic));
    }

    method fmt($format = '%s', $separator = ' ') {
        self.list.fmt($format, $separator);
    }

    method roll($count = 1) {
        return self.list.roll($count) unless $!min.^isa(Int) && $!max.^isa(Int);

        my $least = $!excludes_min ?? $!min + 1 !! $!min;
        my $elems = 1 + ($!excludes_max ?? $!max - 1 !! $!max) - $least;

        sub choose {
            $elems ?? ($least + Q:CgOp { (bigrand {$elems}) }) !! Any;
        }

        return choose() xx * if $count ~~ Whatever;
        return choose() if $count == 1;
        return choose() xx $count;
    }

    method pick($count = 1) {
        return self.list.pick($count) unless $!min.^isa(Int) && $!max.^isa(Int);
        return self.list.pick(*) if $count ~~ Whatever;
        return self.roll if $count == 1;
        return self.list.pick($count) unless $!max - $!min > 3 * $count;

        my %seen;
        my $i = 0;
        gather while $i < $count {
            my $x = self.roll;
            unless %seen{$x} {
                %seen{$x} = 1;
                $i++;
                take $x;
            }
        }
    }
}

sub infix:<..> is equiv<leg> ($a, $b) is pure { Range.new($a, $b) }
sub infix:<..^> is equiv<leg> ($a, $b) is pure { Range.new($a, $b, :excludes_max) }
sub infix:<^..> is equiv<leg> ($a, $b) is pure { Range.new($a, $b, :excludes_min) }
sub infix:<^..^> is equiv<leg> ($a, $b) is pure { Range.new($a, $b, :excludes_min, :excludes_max) }

sub _hyper_type($val) {
    #FIXME rewrite using roles
    given $val {
        when Hash { return 1 }
        when List { return 2 }
        when Parcel { return 2 }
        when Range { return 2 }
        default { return 0 }
    }
}

sub hyperunary(&fun, \obj) {
    given _hyper_type(obj) {
        when 1 {
            my %out;
            for obj.kv -> $k, \v {
                %out{$k} = hyperunary(&fun, v);
            }
            return %out;
        }
        when 2 {
            my @out;
            push @out, $( hyperunary(&fun, $_) ) for @(obj);
            return @out;
        }
        when 3 {
            my @out;
            push @out, $( hyperunary(&fun, $_) ) for @(obj);
            return obj.new(@out);
        }
        when 0 {
            return fun(obj);
        }
    }
}

sub _hyper_hash($dwiml, $dwimr, $fun, $left, $right) {
    my %keys;
    for $left.keys {
        %keys{$_} = True if !$dwiml || ($right{$_}:exists);
    }
    for $right.keys {
        %keys{$_} = True if !$dwimr || ($left{$_}:exists);
    }
    for %keys.keys {
        %keys{$_} = hyper($dwiml, $dwimr, $fun, $left{$_}, $right{$_});
    }
    %keys
}

sub _hyper_posi($dwiml, $dwimr, $fun, $left, $right) {
    my $lex = $left[*-1] ~~ Whatever;
    my $rex = $right[*-1] ~~ Whatever;
    my @out;
    my $ix = 0;
    loop {
        my $lend; my $lv; my $rend; my $rv;
        if $ix >= ($lex ?? $left - 1 !! $left) {
            $lend = True;
            $lv := $left[$lex ?? $left - 2 !! $left ?? $ix % $left !! 0];
        } else {
            $lv := $left[$ix];
        }
        if $ix >= ($rex ?? $right - 1 !! $right) {
            $rend = True;
            $rv := $right[$rex ?? $right - 2 !! $right ?? $ix % $right !! 0];
        } else {
            $rv := $right[$ix];
        }
        last if $lend && $rend;
        die "Ran off end of non-dwimmy left" if $lend && !$dwiml && !$dwimr;
        die "Ran off end of non-dwimmy right" if $rend && !$dwiml && !$dwimr;
        last if $lend && !$dwiml;
        last if $rend && !$dwimr;
        push @out, $( hyper($dwiml, $dwimr, $fun, $lv, $rv) );
        $ix++;
    }
    @out;
}

sub hyper($dwiml, $dwimr, $fun, \left, \right) {
    constant @htnames = 'scalar', 'Associative', 'Positional', #OK
        'non-Positional Iterable';
    my $h1 = _hyper_type(left);
    my $h2 = _hyper_type(right);

    if $h1 && $h2 && $h1 != $h2 {
        die "Cannot mix @htnames[$h1] and @htnames[$h2] in hyperop";
    }

    if $h2 == 0 || $h1 == 0 {
        if $h1 == 0 && $h2 == 0 { return $fun(left, right) }
        if $h2 {
            if $dwiml {
                return hyperunary(sub (\x) { $fun(left,x) }, right);
            }
        } else {
            if $dwimr {
                return hyperunary(sub (\x) { $fun(x,right) }, left);
            }
        }
        die "Non-dwimmy scalar used with complex item";
    }

    given $h1 {
        when 1 { return _hyper_hash($dwiml, $dwimr, $fun, left, right) }
        when 2 { return _hyper_posi($dwiml, $dwimr, $fun, @(left), @(right)) }
        when 3 { die "Cannot hyper two unordered collections" }
    }
}

# tweaked from Rakudo
our sub Niecza::generate-series(@lhs, $rhs, :$exclude-limit) {
    my sub get-next-closure (@lhs, $limit? ) {
        die "Need something on the LHS" unless @lhs.elems;
        die "Need more items on the LHS" if @lhs[*-1] ~~ Code && @lhs[*-1].count != Inf && @lhs.elems - 1 < @lhs[*-1].arity;

        #BEWARE: Here be ugliness
        if @lhs[* - 1] ~~ Code { # case: (a,b,c,{code}) ... *
            return @lhs[*-1];
        }
        return { .succ } if @lhs.elems == 1 && $limit ~~ Code;
        return { $_ } if @lhs.elems > 1 && @lhs[*-1] cmp @lhs[*-2] == 0 ; # case: (a , a) ... *

        if @lhs[*-1] ~~ Str || $limit ~~ Str {
            if @lhs[*-1].codes == 1 && $limit.defined && $limit.codes == 1 {
                return { .ord.succ.chr } if @lhs[*-1] lt $limit;# case (... , non-number) ... limit
                return { .ord.pred.chr } if @lhs[*-1] gt $limit;# case (... , non-number) ... limit
            }
            return { .succ } if $limit.defined && @lhs[*-1] lt $limit;# case (... , non-number) ... limit
            return { .pred } if $limit.defined && @lhs[*-1] gt $limit;# case (... , non-number) ... limit
            return { .pred } if @lhs.elems > 1 && @lhs[*-2] gt @lhs[*-1];# case (non-number , another-smaller-non-number) ... *
            return { .succ } ;# case (non-number , another-non-number) ... *
        }
        return { .pred } if @lhs.elems == 1 && $limit.defined && $limit before @lhs[* - 1]; # case: (a) ... b where b before a
        return { .succ } if @lhs.elems == 1 ; # case: (a) ... *

        my $diff = @lhs[*-1] - @lhs[*-2];
        return { $_ + $diff } if @lhs.elems == 2 || @lhs[*-2] - @lhs[*-3] == $diff ; #Case Arithmetic series

        if @lhs[*-2] / @lhs[*-3] == @lhs[*-1] / @lhs[*-2] { #Case geometric series
            my $factor = @lhs[*-2] / @lhs[*-3];
            if $factor ~~ Rat && $factor.denominator == 1 {
                $factor = $factor.Int;
            }
            return { $_ * $factor } ;
        }
        die "Unable to figure out pattern of series";
    }

    my sub infinite-series (@lhs, $limit ) {
        gather {
            my $i = 0;
            # Take all items from the LHS except for terminal Codes
            # (ordered this way to avoid overeager evaluation)
            while (@lhs[$i].defined && @lhs[$i] !~~ Code) || @lhs[$i+1].defined {
                take @lhs[$i]; $i++;
            }

            my $next = get-next-closure(@lhs , $limit );
            my $arity = $next.count;
            my @args=@lhs[$i-($arity ~~ Inf ?? $i !! $arity) .. $i-1]; #We make sure there are $arity elems in args

            loop { #Then we extrapolate using $next and the $args
                my \current = $next.(|@args) // last;
                take current ;
                if $arity {
                    @args.push(current) ;
                    @args.shift while @args.elems > $arity
                }
            }
        }
    }

    my $limit = ($rhs ~~ Whatever ?? Any !! $rhs);
    return infinite-series(@lhs , $limit) if $rhs ~~ Whatever; #shortcut infinite series so we avoid the comparisions

    my $series = infinite-series(@lhs , $limit);

    gather {
        if $limit ~~ Code && $limit.count > 1 {
            my @limit-args;
            while $series {
                @limit-args.shift if @limit-args == $limit.count;
                my $val = $series.shift;
                @limit-args.push($val);
                my $done = @limit-args >= $limit.arity && $limit(|@limit-args);
                take $val unless $done && $exclude-limit;
                last if $done;
            }
        }
        else {
            while $series {
                my $val = $series.shift();
                if $val ~~ $limit {
                    take $val unless $exclude-limit ;
                    last ;
                };
                take $val;
            }
        }
    }
}

our sub Niecza::series-listop(Parcel $lists, $exclude-limit) {
    if $lists.raw_elems <= 1 { return unitem($lists) }
    my @l := ( $lists.raw_at($lists.raw_elems - 1), ).flat;
    loop (my $i = $lists.raw_elems - 2; $i >= 0; $i = $i - 1) {
        @l || die "Need something on the RHS";
        my @mo := &Niecza::generate-series(($lists.raw_at($i),).flat, @l.shift,
            :$exclude-limit);
        @l := ( @mo, @l ).flat;
    }
    @l
}

sub undefine(Mu \x) { x = Any }
sub infix:<%%> is equiv<*> is iffy is pure ($x,$y) { $x % $y == 0 }
sub infix:<?&> is equiv<*> is iffy is pure ($a, $b) { ?($a && $b) }
sub infix:<?|> ($a, $b) is pure is iffy { ?($a || $b) }
sub infix:<?^> ($a, $b) is pure { ?( +$a +^ $b ) }
sub prefix:<?^> ($a) is pure { !$a }
sub prefix:<|> (\item) { item.Capture } # marking this pure breaks syntax
sub prefix:<^> ($limit) is pure { 0 ..^ +$limit }
sub prefix:<so> is equiv<not> is pure (\item) { ?item }
sub infix:<xx> is equiv<x> (\list, $ct) { map { list }, ($ct ~~ Whatever) ?? ^Inf !! ^$ct }
sub _doreplicate($func, $ct) { map { $func() }, ($ct ~~ Whatever) ?? ^Inf !! ^$ct }
sub prefix:<abs> ($x) is pure { Q:CgOp { (abs {$x}) } }
sub abs($x) is pure { Q:CgOp { (abs {$x}) } }
sub floor($x) is pure { Q:CgOp { (floor {$x}) } }
sub ceiling($x) is pure { -floor(-$x) }
sub conj($x) is pure { $x.conj }
sub round($x, $scale=1) is pure { floor($x / $scale + 0.5) * $scale }
sub truncate($x) is pure { $x.Int }
sub sign($x) is pure { $x < 0 ?? -1 !! $x > 0 ?? 1 !! 0 }
multi sub exp($x) { $x.exp }
multi sub exp($x, $base) { $base ** $x }

sub infix:« <=> » is equiv<leg> ($a, $b) is pure {
    $a < $b ?? Order::Increase !! $a > $b ?? Order::Decrease !! Order::Same
}
# XXX polymorphic equality
sub infix:<cmp> is equiv<leg> (Mu $a, Mu $b) {
    return $a <=> $b if $a ~~ Real && $b ~~ Real;
    if $a ~~ Real {
        return Order::Increase if $a == -Inf;
        return Order::Decrease if $a == Inf;
    }
    if $b ~~ Real {
        return Order::Increase if $b == Inf;
        return Order::Decrease if $b == -Inf;
    }
    return ($a ~~ Real ?? "Real" !! $a.WHAT.gist) leg
           ($b ~~ Real ?? "Real" !! $b.WHAT.gist)
                unless Niecza::ValueIdentity($a.WHAT, $b.WHAT);
    return 0 if !$a.defined && !$b.defined;
    return $a leg $b if $a ~~ Str;
    return $a.key cmp $b.key || $a.value cmp $b.value if $a ~~ Pair;
    if $a ~~ List {
        for @$a Z @$b -> $i1, $i2 {
            (my $r = $i1 cmp $i2) && return $r
        }
        return $a <=> $b;
    }
    if $a ~~ Hash {
        my $keys = set $a.keys, $b.keys;
        my @keys = $keys.keys.sort;
        for @keys -> $k {
            return Order::Decrease unless $a{$k} :exists;
            return Order::Increase unless $b{$k} :exists;
            (my $r = $a{$k} cmp $b{$k}) && return $r;
        }
        return Order::Same;
    }
    return $a <=> $b;
}
sub infix:<eqv> is equiv<==> (Any $a, Any $b) { ($a.WHAT.gist cmp $b.WHAT.gist) == 0 && ($a cmp $b) == 0 }
sub infix:<before> ($a, $b) is equiv<==> { ($a cmp $b) < 0 }
sub infix:<after> ($a, $b) is equiv<==> { ($a cmp $b) > 0 }
sub seqop($op, \x, \y) { $op(x,y) } # TODO: Special case with hyper
sub reverseop($op, \x, \y) { $op(y, x) }

sub infix:<div> is equiv<*> ($x,$y) is pure { Q:CgOp { (divop (i 4) {$x} {$y}) } }
sub infix:<mod> is equiv<*> ($x,$y) is pure { Q:CgOp { (divop (i 5) {$x} {$y}) } }
sub infix:<~&> ($x, $y) { die "Buffer bitops NYI"; } #OK
sub infix:<~|> ($x, $y) { die "Buffer bitops NYI"; } #OK
sub infix:<~^> ($x, $y) { die "Buffer bitops NYI"; } #OK
sub infix:«~<» ($x, $y) { die "Buffer bitops NYI"; } #OK
sub infix:«~>» ($x, $y) { die "Buffer bitops NYI"; } #OK
sub prefix:<~^> ($x) { die "Buffer bitops NYI"; } #OK
sub prefix:<||> (\|$args) { die "Slicels NYI" } #OK
sub postfix:<i> ($item) is pure is fiddly is uassoc<left> { $item ~~ Complex ?? $item * i !! Complex.new(0, $item) }
sub prefix:<sleep> ($x) { Q:CgOp { (sleep (obj_getnum {$x})) } }
sub infix:<...> is equiv<X> (\|$lists) { &Niecza::series-listop($lists, False) }
sub infix:<...^> is equiv<X> (\|$lists) { &Niecza::series-listop($lists, True) }
sub infix:« ==> »(\|$args) { die "Feed ops NYI" } #OK
sub infix:« ==>> »(\|$args) { die "Feed ops NYI" } #OK
sub infix:« <== »(\|$args) { die "Feed ops NYI" } #OK
sub infix:« <<== »(\|$args) { die "Feed ops NYI" } #OK

sub eval($str,:$lang="perl6") is return-pass {
    if $lang eq "perl6" {
        Q:CgOp { (simple_eval {$str}) }
    } else {
        Q:CgOp { (eval_perl5 {$str}) }
    }
}

sub rungather($command_line) { Q:CgOp { (box Str (command_qx (obj_getstr {$command_line}))) } }

# tiny stub for Dancer
my class DateTime {
    has $!now;
    method new($now) {
        self := self.bless(*);
        $!now = $now;
        self;
    }
    method Str() { $!now }
}

# a rather strange grammar. All of its rules are tokens, and some of them
# will die().
grammar Niecza::NumSyntax {
    # this is a high candidate to be rewritten in C#
    sub from_base(Str $str, Int $base) {
        my $acc = 0;
        my $places = 0;
        my $ch;
        my $digit;
        loop (my $ix = 0; $ix < chars($str); ++$ix) {
            $ch = ord(substr($str,$ix,1));
            $ch == 0x5F and next;
            ++$places;
            0x30 <= $ch <= 0x39 and $digit = $ch - 0x30;
            0x61 <= $ch <= 0x7A and $digit = $ch - 0x57;
            0x41 <= $ch <= 0x5A and $digit = $ch - 0x37;
            die "Digit <{substr($str,$ix,1)}> too large for radix $base"
                if $digit >= $base;
            $acc = $acc * $base + $digit;
        }
        ($acc, $places);
    }

    token binint {
        $0=[ <[ 0..1 ]>+ [ _ <[ 0..1 ]>+ ]* ]
        { make from_base(~$0, 2)[0] }
    }

    token octint {
        $0=[ <[ 0..7 ]>+ [ _ <[ 0..7 ]>+ ]* ]
        { make from_base(~$0, 8)[0] }
    }

    token hexint {
        $0=[ <[ 0..9 a..f A..F ]>+ [ _ <[ 0..9 a..f A..F ]>+ ]* ]
        { make from_base(~$0, 16)[0] }
    }

    token decint {
        $0=[ \d+ [ _ \d+ ]* ]
        <?{ make from_base(~$0, 10); True }>
    }

    token integer {
        [
        | 0 [ b '_'? <binint> { make $<binint>.ast }
            | o '_'? <octint> { make $<octint>.ast }
            | x '_'? <hexint> { make $<hexint>.ast }
            | d '_'? <decint> { make $<decint>.ast[0] }
            | <decint> { make $<decint>.ast[0] }
            ]
        | <decint> { make $<decint>.ast[0] }
        ]
    }

    token radint {
        [
        | <integer> { make $<integer>.ast }
        | <?before ':'\d> <rad_number> { make $<rad_number>.ast }
              <?{ $() ~~ Int }>
        ]
    }

    token escale {
        <[Ee]> $0=[<[+\-]>?] <decint>
        { make $0 eq '-' ?? -$<decint>.ast[0] !! $<decint>.ast[0] }
    }

    token dec_number {
        :dba('decimal number')
        [
        | $<coeff> = [ '.' <frac=.decint> ] <escale>?
        | $<coeff> = [<int=.decint> '.' <frac=.decint> ] <escale>?
        | $<coeff> = [<int=.decint> ] <escale>
        ]
        {
            my $acc = $<int> ?? $<int>.ast[0] !! 0;
            if $<frac> -> $f {
                my $subn = 10 ** $f.ast[1];
                $acc = FatRat.new($acc * $subn + $f.ast[0], $subn);
            }
            if $<escale> -> $e {
                # forces to Num; XXX not exactly rounded!
                $acc = $acc * 10e0 ** $e.ast;
            }
            make $acc;
        }
    }

    token alnumint {
        [ <[ 0..9 a..z A..Z ]>+ [ _ <[ 0..9 a..z A..Z ]>+ ]* ]
    }

    # XXX: accepts _ in radix (STD does not)
    token rad_number {
        ':' <radix=.decint> [ '\\' \s* ]? # XXX optional dot here? **
        {} # don't recurse in lexer
        :s '<' <radixguts($<radix>.ast[0])> '>'
        { make $<radixguts>.ast }
    }
    rule radixguts ($r) {
        :dba('number in radix notation')
        [
        | $<coeff> = [ '.' <frac=.alnumint> ]
        | $<coeff> = [<int=.alnumint> '.' <frac=.alnumint> ]
        | $<coeff> = [<int=.alnumint> ]
        ]
        [
            '*' <base=.radint>
               [ '**' <exp=.radint> || { die "Base is missing ** exponent part" } ]
        ]?
        # I don't think we need to parse <circumfix> for the runtime case :)
        {
            my $acc = $<int> ?? from_base(~$<int>, $r)[0] !! 0;
            if $<frac> -> $f {
                my ($fn, $fp) = from_base(~$f, $r);
                my $subn = $r ** $fp;
                $acc = FatRat.new($acc * $subn + $fn, $subn);
            }
            if $<base> -> $b {
                # *not* forcing to Num here
                $acc = $acc * $b.ast ** $<exp>.ast;
            }
            make $acc;
        }
    }

    token number {
        [
        | 'NaN' » { make NaN }
        | <integer> { make $<integer>.ast }
        | <dec_number> { make $<dec_number>.ast }
        | <rad_number> { make $<rad_number>.ast }
        | 'Inf' » { make Inf }
        ]
    }

    token snumber {
        $<sn>=[<[+\-]>?] <.ws> <number>
        { make $<sn> eq '-' ?? -$<number>.ast !! $<number>.ast }
    }

    # <numeric> is used by Str.Numeric conversions such as those done by val()
    # NOTE: allows whitespace for round-tripping
    # XXX: allows radix rationals, which strictly speaking it probably shouldn't
    token numeric {
        [ || $ { make 0 }
          || <re=.snumber>? <.ws>
             [ | <?[+\-]> {}:s <im=.snumber>'\\'?'i'
                 { make Complex.new($<re> ?? $<re>.ast !! 0, $<im>.ast) }
               | '/' {} <.ws> <den=.integer>
                 { die "Parsing $/.orig(), rational parts must be integers"
                       unless $<re>.ast ~~ Int;
                   make FatRat.new($<re>.ast, $<den>.ast) }
               | $ { make $<re>.ast } ] ]
    }

    method str2num ($str, :$fatrat) {
        my ($M) = (token {
            <.ws> [ :lang(Niecza::NumSyntax)
                <numeric> || { die "Cannot parse number: $str" } ] <.ws>
            [ $ || { die "Trailing characters after number at $¢.pos()" } ]
        })(Cursor.cursor_start($str, Any));

        if $fatrat {
            $M<numeric>.ast.FatRat
        } else {
            my $a = $M<numeric>.ast;
            $a ~~ FatRat ?? $a.numerator / $a.denominator !! $a
        }
    }

    method base2num ($str, $base) {
        my ($M) = (token {
            <.ws> [ :lang(Niecza::NumSyntax)
                <radixguts($base)> || {die "Cannot parse :$base: $str" } ] <.ws>
            [ $ || { die "Trailing characters after number at $¢.pos()" } ]
        })(Cursor.cursor_start($str, Any));

        my $a = $M<radixguts>.ast;
        $a ~~ FatRat ?? $a.numerator / $a.denominator !! $a
    }
}

class Niecza::PseudoStr is Str { has $!value }

role Niecza::Dualvar is Niecza::PseudoStr {
    method new($val, Str $str) { Q:CgOp { (dualvar {$val} {self} {$str}) } }
    method Str() { self // nextsame; Q:CgOp { (box Str (unbox str (@ {self}))) } }
    method gist() { self // nextsame; Q:CgOp { (box Str (unbox str (@ {self}))) } }
    method Numeric() { 0 + self }
    method perl() { "val({(~self).perl})" }
}
class IntStr is Int does Niecza::Dualvar { }
class RatStr is Rat does Niecza::Dualvar { }
class NumStr is Num does Niecza::Dualvar { }
class ComplexStr is Complex does Niecza::Dualvar { }

sub val($str) is pure {
    $_ = Niecza::NumSyntax.str2num($str);
    when Num { return NumStr.new($_, $str) }
    when Rat { return RatStr.new($_, $str) }
    when Int { return IntStr.new($_, $str) }
    when Complex { return ComplexStr.new($_, $str) }
fail:
    return $str;
    CATCH { goto fail; }
}
sub val_nospace($str) is pure {
    return Niecza::NumSyntax.str2num($str);
fail:
    return $str;
    CATCH { goto fail; }
}

# the opposite of Real.base, used for :16($hex_str)
sub unbase(Int:D $base, Cool:D $str) is pure {
    if $str ~~ Array {
        die ":16[...] syntax NYI";
    }
    if $str ~~ Numeric {
        die 'Numbers may not be passed :base(); if you wanted to render the number in the given base, use $number.base($radix); if you want to treat the number as a string, explicitly coerce it first';
    }
    $str := ~$str;
    if $str ~~ m:pos(0) /\s* [ ':' || '0' (<[bdox]>) <?{ ord($0)-97+10 >= $base }> ] / {
        $str.Numeric;
    } else {
        ":{$base}<$str>".Numeric;
    }
}
# }}}
# I/O stuff {{{
sub slurp($path) is unsafe { Q:CgOp { (box Str (slurp (unbox str (@ {$path})))) } }

sub spurt($path,$text) is unsafe { Q:CgOp { (rnull (spurt (unbox str (@ {$path.Str})) (unbox str (@ {$text.Str})))) } }

sub dir($directory = '.', Mu :$test = none('.','..')) is unsafe {
    grep $test, Q:CgOp { (dir (obj_getstr {$directory})) };
}

my class Instant {
    has $.val;
    method immutable() { True }
    method to-posix() { ($!val, False) }
}
sub term:« now »() {
    Instant.new( val => Q:CgOp { (now) } );
}
sub times() { Q:CgOp { (times) } }
sub term:« time »() { Q:CgOp { (now) } }
sub term:« rand »() { Q:CgOp { (rand) } }
sub srand($seed?) {
    if $seed.defined {
        Q:CgOp { (rnull (srand (cast int (obj_getnum {$seed})))) }
    } else {
        Q:CgOp { (rnull (srand_time)) }
    }
}

my class IO {
    has $.path; # Str

    method Str() { $.path }
    method IO() { self }

    method slurp() { slurp $.path }
    method spurt($text) { spurt $.path, $text }

    method combine(*@paths) {
        die "Sorry, paths do not form a monoid." unless @paths;
        my $acc = shift(@paths).IO;
        for @paths { $acc = $acc.append($_) }
        $acc
    }

    method perl() { $.path.perl ~ ".IO" }

    method f() is unsafe { Q:CgOp { (box Bool (path_file_exists (obj_getstr {$!path}))) } }
    method d() is unsafe { Q:CgOp { (box Bool (path_dir_exists (obj_getstr {$!path}))) } }
    method e() is unsafe { Q:CgOp { (box Bool (path_any_exists (obj_getstr {$!path}))) } }
    method r() is unsafe { Q:CgOp { (box Bool (path_eaccess_readable (obj_getstr {$!path}))) } }
    method R() is unsafe { Q:CgOp { (box Bool (path_access_readable (obj_getstr {$!path}))) } }
    method w() is unsafe { Q:CgOp { (box Bool (path_eaccess_writable (obj_getstr {$!path}))) } }
    method W() is unsafe { Q:CgOp { (box Bool (path_access_writable (obj_getstr {$!path}))) } }
    method x() is unsafe { Q:CgOp { (box Bool (path_eaccess_executable (obj_getstr {$!path}))) } }
    method X() is unsafe { Q:CgOp { (box Bool (path_access_executable (obj_getstr {$!path}))) } }
    method o() is unsafe { Q:CgOp { (box Bool (path_eaccess_owned (obj_getstr {$!path}))) } }
    method O() is unsafe { Q:CgOp { (box Bool (path_access_owned (obj_getstr {$!path}))) } }
    method relative($base) { $base.IO.append(self) }
    method append($sub) { Q:CgOp { (box Str (path_combine (obj_getstr {self}) (obj_getstr {$sub}))) }.IO }
    method but-extension($ext) { Q:CgOp { (box Str (path_change_ext (obj_getstr {self}) (obj_getstr {$ext}))) }.IO }
    method realpath() is unsafe { Q:CgOp { (box Str (path_realpath (obj_getstr {self}))) }.IO }
    method modified() is unsafe { Instant.new(val => Q:CgOp { (path_modified (obj_getstr {self})) }) }
    method copy($dest) is unsafe { Q:CgOp { (rnull (path_copy (obj_getstr {self}) (obj_getstr {$dest})))}}
    method chmod($mode) is unsafe { Q:CgOp { (box Int (path_chmod (obj_getstr {self}) (obj_getnum {$mode}))) } }
}

my class TextReader {
    method get() {
        Q:CgOp {
            (letn line (treader_getline (unbox treader (@ {self})))
              (ternary (== (l line) (null str)) {Str} (box Str (l line))))
        };
    }

    method slurp() {
        Q:CgOp { (box Str (treader_slurp (unbox treader (@ {self})))) }
    }

    method getc() {
        Q:CgOp {
            (letn chi (treader_getc (unbox treader (@ {self})))
              (ternary (>= (l chi) (int 0))
                (box Str (str_chr (l chi)))
                {Str}))
        };
    }

    method lines($given-limit = *) {
        my $limit = $given-limit ~~ Whatever ?? Inf !! $given-limit;
        gather take my $l while $limit-- > 0 && ($l = self.get).defined;
    }

    method close() {
        Q:CgOp { (rnull (treader_close (unbox treader (@ {self})))) }; True
    }
}

my class TextWriter {
    method say(*@c) {
        # $PROCESS::OUTPUT_USED := True;
        Q:CgOp { (rnull (twriter_puts (unbox twriter (@ {self})) (obj_getstr {Niecza::gistcat(|@c) ~ "\n"}))) };
        True;
    }

    method print(*@c) {
        # $PROCESS::OUTPUT_USED := True;
        Q:CgOp { (rnull (twriter_puts (unbox twriter (@ {self})) (obj_getstr {@c.join("")}))) };
        True;
    }

    method close() {
        Q:CgOp { (rnull (twriter_close (unbox twriter (@ {self})))) }; True
    }
}

# the following class stolen from Rakudo, but butchered
class IO::ArgFiles {
    has $!args;
    has $!reader;

    method lines() {
        gather take my $l while ($l = self.get).defined;
    }

    method get() {
        unless defined $!args {
            $!args = [ @*ARGS ];
            $!reader = $*IN unless $!args;
        }
      again:
        $!reader //= open(shift($!args) // return Str);
        if defined my $line = $!reader.get {
            return $line;
        } else {
            $!reader = Any;
            goto again;
        }
    }
}

sub unlink(*@filenames) is unsafe {
    for @filenames -> $filename {
        if $filename.IO ~~ :d {
            Q:CgOp { (box Int (path_rmdir (obj_getstr {$filename}))) };
        } else {
            Q:CgOp { (rnull (path_unlink (obj_getstr {$filename}))) };
        }
    }
    True; # is there a way to actually detect problems with File.Delete?
}

sub cwd() is unsafe {
    Q:CgOp { (box Str (cwd_path)) };
}

sub chdir($filename) is unsafe {
    my $ok_code = True;
    {
        Q:CgOp { (rnull (path_chdir (obj_getstr {$filename}))) };
        $PROCESS::CWD ::= Q:CgOp { (box Str (cwd_path)) };
        CATCH { default { $ok_code = False; } }
    }
    $ok_code;
}

sub mkdir($filename) is unsafe {
    Q:CgOp { (rnull (path_mkdir (obj_getstr {$filename}))) };
    True; # is there a way to actually detect problems with path_mkdir?
}

sub rmdir($filename) is unsafe {
    Q:CgOp { (box Int (path_rmdir (obj_getstr {$filename}))) } == 0;
}

sub shell($command) is unsafe {
    Q:CgOp { (box Int (command_system (obj_getstr {$command}))) };
}

sub run(*@argv, :%env = %*ENV) is unsafe {
    my @env = %env.map({ .key ~ "=" ~ .value });
    Q:CgOp { (box Int (command_run {@argv} {@env})) };
}

multi sub open($filename, :$w?, :$a?, :$r?, :$rw?) is unsafe {
    die "Not yet able to open both :r and :w" if ($r && $w) || $rw;
    if $a {
        Q:CgOp { (box TextWriter (twriter_append (obj_getstr {$filename}) (obj_getbool {True}))) }
    } elsif $w {
        Q:CgOp { (box TextWriter (twriter_open (obj_getstr {$filename}))) }
    } else {
        Q:CgOp { (box TextReader (treader_open (obj_getstr {$filename}))) }
    }
}

sub close($file) {
    $file.close;
}

# TODO $*ARGFILES, multi
sub get($handle = $*IN) { $handle.get }
sub lines($filehandle = $*IN, $limit = *) { $filehandle.lines($limit) }
sub prompt($msg) { print $msg; $*IN.get }
sub getc($handle) { $handle.getc }

multi sub log($x) { $x.log }
multi sub log($x, $base) { $x.log($base) }
sub log10($x) is pure { $x.log(10) }

sub unpolar($mag, $angle) is pure { Complex.new($mag * $angle.cos, $mag * $angle.sin); }
sub cis($angle) is pure { Complex.new($angle.cos, $angle.sin); }
sub roots($x, $an) {
    my $n = $an.Int;
    return NaN if $n < 1;
    return $x if $n == 1;
    # for $!re, $!im {
    # return $NaN if $_ eq 'Inf' || $_ eq '-Inf' || $_ eq 'NaN';
    # }

    my ($mag, $angle) = $x.polar;
    $mag **= 1e0 / $n;
    (^$n).map: { $mag.unpolar( ($angle + $_ * 2e0 * pi) / $n) };
}

sub sin($x) is pure { $x.sin }
sub asin($x) is pure { $x.asin }
sub cos($x) is pure { $x.cos }
sub acos($x) is pure { $x.acos }
sub tan($x) is pure { $x.tan }
sub atan($x) is pure { $x.atan }
sub sec($x) is pure { $x.sec }
sub asec($x) is pure { $x.asec }
sub cosec($x) is pure { $x.cosec }
sub acosec($x) is pure { $x.acosec }
sub cotan($x) is pure { $x.cotan }
sub acotan($x) is pure { $x.acotan }
sub sinh($x) is pure { $x.sinh }
sub asinh($x) is pure { $x.asinh }
sub cosh($x) is pure { $x.cosh }
sub acosh($x) is pure { $x.acosh }
sub tanh($x) is pure { $x.tanh }
sub atanh($x) is pure { $x.atanh }
sub sech($x) is pure { $x.sech }
sub asech($x) is pure { $x.asech }
sub cosech($x) is pure { $x.cosech }
sub acosech($x) is pure { $x.acosech }
sub cotanh($x) is pure { $x.cotanh }
sub acotanh($x) is pure { $x.acotanh }
sub atan2($y, $x = 1) is pure { $y.atan2($x) }

sub hypot($a, $b) is pure {
    my $max = $a.abs max $b.abs;
    my $min = $a.abs min $b.abs;
    my $r = $min / $max;
    $max * sqrt(1 + $r * $r);
}
sub gamma($x) is pure { $x.gamma }
sub lgamma($x) is pure { $x.lgamma }
sub expm1($x) is pure { $x.expm1 }
sub log1p($x) is pure { $x.log1p }

sub expmod($exp, $power, $mod) is pure { Q:CgOp { (expmod {$exp.Int} {$power.Int} {$mod.Int}) } }
sub is-prime($candidate, $tries = 100) {
    # Miller-Rabin via TimToady
    my Int $n = $candidate.Int;
    my Int $k = $tries.Int;
    my @a;
    given $n {
        when 2 | 3 | 5 | 7 | 11 { return True; }
        when * < 2 { return False; }
        when * %% 2 { return False; }
        when * < 1_373_653 { @a = 2, 3; }
        when * < 9_080_191 { @a = 31, 73; }
        when * < 4_759_123_141 { @a = 2, 7, 61; }
        when * < 2_152_302_898_747 { @a = 2, 3, 5, 7, 11; }
        when * < 3_474_749_660_383 { @a = 2, 3, 5, 7, 11, 13; }
        when * < 341_550_071_728_321 { @a = 2, 3, 5, 7, 11, 13, 17; }
        default { @a = (2 ..^ $n).pick($k); }
    }

    my Int $d = $n - 1;
    my Int $s = 0;

    while $d %% 2 {
        $d div= 2;
        $s++;
    }

    for @a -> $a {
        my $x = expmod($a, $d, $n);
        next if $x == 1 | $n - 1;

        for 1 ..^ $s {
            $x = $x ** 2 mod $n;
            return False if $x == 1;
            last if $x == $n - 1;
        }
        return False if $x !== $n - 1;
    }

    return True;
}


sub pick($num, *@values) { @values.pick($num) }
sub roll($num, *@values) { @values.roll($num) }
sub rotate(@array, $n = 1) { @array.rotate($n) }
sub reduce($expression, *@values) { @values.reduce($expression) }

my sub MAIN_HELPER() {
    # Do we have a MAIN at all?
    my $m = CALLER::<&MAIN>;
    return unless $m;

    # Convert raw command line args into positional and named args for MAIN
    my sub process-cmd-args (@args is copy) {
        my (@positional-arguments, %named-arguments);
        while (@args) {
            my $passed-value = @args.shift;
            if $passed-value ~~ /^ ( '--' | '-' | ':' ) ('/'?) (<-[0..9\.]> .*) $/ {
                my ($switch, $negate, $arg) = (~$0, ?((~$1).chars), ~$2); #OK not used

                if $arg.index('=').defined {
                    my ($name, $value) = $arg.split('=', 2);
                    $value = val($value);
                    $value = $value but False if $negate;
                    %named-arguments.push: $name => $value;
                } else {
                    %named-arguments.push: $arg => !$negate;
                }
            } else {
                @args.unshift($passed-value) unless $passed-value eq '--';
                @positional-arguments.push: @args.map: &val;
                last;
            }
        }

        return \(|@positional-arguments, |%named-arguments);
    }

    # Generate $?USAGE string (default usage info for MAIN)
    my sub gen-usage () {
        my @help-msgs;
        my $prog-name = $*PROGRAM_NAME eq '-e' ?? "-e '...'" !! $*PROGRAM_NAME;
        for $m.candidates -> $sub {
            my (@required-named, @optional-named, @positional);
            for $sub.signature.params -> $param {
                my $argument;
                if $param.named {
                    my @names = $param.named_names.reverse;
                    $argument = @names.map({($^n.chars == 1 ?? '-' !! '--') ~ $^n}).join('|');
                    $argument ~= "=<{$param.type.^name}>" unless $param.type === Bool;
                    if $param.optional {
                        @optional-named.push("[$argument]");
                    }
                    else {
                        @required-named.push($argument);
                    }
                }
                else {
                    my $constraints = $param.value_constraint_list;
                    $argument = $constraints ?? $constraints !!
                                $param.name ?? '<' ~ $param.name.substr(1) ~ '>' !!
                                                 '<' ~ $param.type.^name ~ '>' ;

                    $argument = "[$argument ...]" if $param.slurpy;
                    $argument = "[$argument]" if $param.optional;
                    @positional.push($argument);
                }
            }
            my $msg = join(' ', $prog-name, @required-named, @optional-named, @positional);
            @help-msgs.push($msg);
        }
        my $usage = "Usage:\n" ~ @help-msgs.map(' ' ~ *).join("\n");
        return $usage;
    }

    # Process command line arguments
    my $cap = process-cmd-args(@*ARGS);

    # Generate default $?USAGE message
    my $USAGE = gen-usage();

    # If dispatch to MAIN is possible, do so
    if $m.candidates_matching(|$cap).elems {
        return $m(|$cap);
    }

    # We could not find the correct MAIN to dispatch to!
    # Let's try to run a user defined USAGE sub
    my $h = CALLER::<&USAGE>;
    return $h() if $h;

    # We could not find a user defined USAGE sub!
    # Let's display the default USAGE message
    if ($cap.hash<help>) {
        $*OUT.say($USAGE);
        exit 1;
    }
    else {
        $*ERR.say($USAGE);
        exit 2;
    }
}

INIT {
    $PROCESS::IN ::= Q:CgOp { (box TextReader (treader_stdin)) };
    $PROCESS::OUT ::= Q:CgOp { (box TextWriter (twriter_stdout)) };
    $PROCESS::ERR ::= Q:CgOp { (box TextWriter (twriter_stderr)) };
    $PROCESS::ARGFILES ::= IO::ArgFiles.new;
    @PROCESS::ARGS = Q:CgOp { (sysquery (i 0)) };
    %PROCESS::ENV = Q:CgOp { (sysquery (i 4)) };
    $PROCESS::EXECUTABLE_NAME ::= Q:CgOp { (sysquery (i 2)) };
    $PROCESS::PROGRAM_NAME ::= Q:CgOp { (sysquery (i 1)) };
    $PROCESS::BASE_DIRECTORY ::= Q:CgOp { (sysquery (i 3)) };
    $PROCESS::OS ::= Q:CgOp { (sysquery (i 5)) };
    $PROCESS::CWD ::= Q:CgOp { (box Str (cwd_path)) };
    @GLOBAL::INC = ();
}
# }}}
# Network {{{

class IO::Socket::INET {
    has $!sock;
    has Str $!buffer = '';

    # TODO: This code is horribly broken, especially if a character gets cut by
    # a buffer or packet boundry, or you want to switch from char to binary mode
    # doing it right seems to require some kind of Decoder class

    method recv (Cool $chars = Inf) {
        die('Socket not available') unless $!sock;

        if $!buffer.chars < $chars {
            $!buffer ~= self.read(2048).decode('UTF-8');
        }

        if $!buffer.chars > $chars {
            my $rec = $!buffer.substr(0, $chars);
            $!buffer = $!buffer.substr($chars);
            $rec
        } else {
            my $rec = $!buffer;
            $!buffer = '';
            $rec;
        }
    }

    method read(IO::Socket::INET:D: Cool $bufsize) {
        die('Socket not available') unless $!sock;
        Q:CgOp { (box Buf (socket_read (unbox socket {$!sock}) (unbox int {$bufsize.Int}))) }
    }

    #method poll(Int $bitmask, $seconds) {
    # $!sock.poll(
    # nqp::unbox_i($bitmask), nqp::unbox_i($seconds.floor),
    # nqp::unbox_i((($seconds - $seconds.floor) * 1000).Int)
    # );
    #}

    method send (Cool $string) {
        self.write($string.encode('UTF-8'));
    }

    method write(Buf:D $buf) {
        die('Socket not available') unless $!sock;
        Q:CgOp { (rnull (socket_write (unbox socket {$!sock}) (unbox blob {$buf}))) }
    }

    method close () {
        die("Not connected!") unless $!sock;
        Q:CgOp { (rnull (socket_close (unbox socket {$!sock}))) };
        $!sock = Any;
    }

    my module sock {
        # XXX these constants are backend-sensitive.
        constant PF_LOCAL = 0;
        constant PF_UNIX = 1;
        constant PF_INET = 2;
        constant PF_INET6 = 0x17;
        #constant PF_MAX = 4;
        #constant SOCK_PACKET = 0;
        constant SOCK_STREAM = 1;
        constant SOCK_DGRAM = 2;
        constant SOCK_RAW = 3;
        constant SOCK_RDM = 4;
        constant SOCK_SEQPACKET = 5;
        constant SOCK_MAX = 6;
        constant PROTO_TCP = 6;
        constant PROTO_UDP = 17;
    }

    has Str $.host;
    has Int $.port = 80;
    has Str $.localhost;
    has Int $.localport;
    has Bool $.listen;
    has $.family = sock::PF_INET;
    has $.proto = sock::PROTO_TCP;
    has $.type = sock::SOCK_STREAM;
    has Str $.input-line-separator is rw = "\n";
    has Int $.ins = 0;

    my sub v4-split($uri) {
        return $uri.split(':', 2);
    }

    my sub v6-split($uri) {
        my ($host, $port) = ($uri ~~ /^'[' (.+) ']' \: (\d+)$/)[0,1];
        return $host ?? ($host, $port) !! $uri;
    }

    method new (*%args is copy) {
        die "Nothing given for new socket to connect or bind to" unless %args<host> || %args<listen>;

        if %args<host> {
            my ($host, $port) = %args<family> && %args<family> == sock::PF_INET6()
                ?? v6-split(%args<host>)
                !! v4-split(%args<host>);
            if $port {
                %args<port> //= $port;
                %args<host> = $host;
            }
        }
        if %args<localhost> {
            my ($peer, $port) = %args<family> && %args<family> == sock::PF_INET6()
                ?? v6-split(%args<localhost>)
                !! v4-split(%args<localhost>);
            if $port {
                %args<localport> //= $port;
                %args<localhost> = $peer;
            }
        }

        %args<listen>.=Bool if %args<listen> :exists;

        #TODO: Learn what protocols map to which socket types and then determine which is needed.
        self.bless(*, |%args)!initialize()
    }

    method !initialize() {
        $!sock = Q:CgOp { (box Any (socket_new (unbox int {$.family}) (unbox int {$.type}) (unbox int {$.proto}))) };

        #Quoting perl5's SIO::INET:
        #If Listen is defined then a listen socket is created, else if the socket type,
        #which is derived from the protocol, is SOCK_STREAM then connect() is called.
        if $.listen || $.localhost || $.localport {
            Q:CgOp { (rnull (socket_bind (unbox socket {$!sock}) (unbox str {$.localhost || "0.0.0.0"}) (unbox int {$.localport || 0}))) };
        }

        if $.listen {
            Q:CgOp { (rnull (socket_listen (unbox socket {$!sock}) (unbox int {20}))) };
        }
        elsif $.type == sock::SOCK_STREAM {
            Q:CgOp { (rnull (socket_connect (unbox socket {$!sock}) (unbox str {$.host}) (unbox int {$.port}))) };
        }

        self;
    }

    method get() {
        ++$!ins;
        my $inbuf = '';
        my $irs = $!input-line-separator;
        my $irslen = chars($irs);
        until substr($inbuf, chars($inbuf)-$irslen, $irslen) eq $irs {
            $inbuf ~= (self.recv(1) || return $inbuf);
        }
        substr($inbuf, 0, chars($inbuf)-$irslen);
    }

    method lines() {
        gather { take self.get() };
    }

    method !setsock($ns) {
        $!sock = $ns;
        $!buffer = '';
        self;
    }

    method accept() {
        my $new_sock := self.WHAT.bless(*, :$!family, :$!proto, :$!type);
        $new_sock!setsock( Q:CgOp { (box Any (socket_accept (unbox socket {$!sock}))) } );
    }

    #method remote_address() {
    # return nqp::p6box_s(nqp::getattr(self, $?CLASS, '$!sock').remote_address());
    #}

    #method local_address() {
    # return nqp::p6box_s(nqp::getattr(self, $?CLASS, '$!sock').local_address());
    #}
}
# }}}

{YOU_ARE_HERE}
Something went wrong with that request. Please try again.