Skip to content
This repository
branch: master
executable file 4070 lines (3643 sloc) 134.449 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
; Copyright (c) Rich Hickey. All rights reserved.
; The use and distribution terms for this software are covered by the
; Eclipse Public License 1.0 (http://opensource.org/licenses/eclipse-1.0.php)
; which can be found in the file epl-v10.html at the root of this distribution.
; By using this software in any fashion, you are agreeing to be bound by
; the terms of this license.
; You must not remove this notice, or any other, from this software.

(in-ns ^{:doc "The core Clojure language."
       :author "Rich Hickey"}
  clojure.core)

;;; preparing support for defn and defmacro

(def unquote)
(def unquote-splicing)

(def
 ^{:arglists '([& items])
   :doc "Creates a new list containing the items."
   :added "1.0"}
 list clojure.lang.persistentlist/creator)

(def
 ^{:arglists '([x seq])
   :doc "Returns a new seq where x is the first element and seq is the rest."}
 cons (fn* cons [x seq] (clojure.lang.rt/cons x seq)))

;during bootstrap we don't have destructuring let, loop or fn, will redefine later
(def
 ^{:macro true
   :added "1.0"}
 let (fn* let [&form &env & decl] (cons 'let* decl)))

(def
 ^{:macro true
   :added "1.0"}
 loop (fn* loop [&form &env & decl] (cons 'loop* decl)))

(def
 ^{:macro true
   :added "1.0"}
 fn (fn* fn [&form &env & decl]
         (cons 'fn* decl)))

(def
 ^{:arglists '(^clojure.lang.ISeq [coll])
   :doc "Returns a seq on the collection. If the collection is empty, returns
nil. (seq nil) returns nil. seq also works on Strings, native Python lists
and any objects that implement __getitem__."
   :tag clojure.lang.ISeq
   :added "1.0"
   :static true}
 seq (fn seq [coll] (. clojure.lang.rt (seq coll))))

(def
 ^{:arglists '([^Class c x])
   :doc "Evaluates x and tests if it is an instance of the class
c. Returns true or false"
   :added "1.0"}
 instance? (fn instance? [c x] (py/isinstance x c)))

(def
 ^{:arglists '([x])
   :doc "Return true if x implements ISeq"
   :added "1.0"
   :static true}
 seq? (fn seq? [x] (instance? clojure.lang.iseq/ISeq x)))

(def
 ^{:arglists '([x])
   :doc "Return true if x is a String"
   :added "1.0"
   :static true}
 string? (fn string? [x] (instance? py/str x)))

(def
 ^{:arglists '([x])
   :doc "Return true if x implements IPersistentMap"
   :added "1.0"
   :static true}
 map? (fn ^:static map? [x] (instance? clojure.lang.ipersistentmap/IPersistentMap x)))

(def
 ^{:arglists '([x])
   :doc "Return true if x implements IPersistentVector"
   :added "1.0"
   :static true}
 vector? (fn vector? [x] (instance? clojure.lang.ipersistentvector/IPersistentVector x)))

(def
 ^{:arglists '([& args])
   :doc "Clojure version of RT.assoc"
   :added "1.0"}
 _assoc (fn* assoc [col k v]
          (py/if col
            (.assoc col k v)
            (clojure.lang.rt/map k v))))

(def
 ^{:arglists '([coll])
   :doc "Returns the first item in the collection. Calls seq on its argument.
If coll is nil, returns nil."
   :added "1.0"
   :static true}
 first (fn first [s]
         (py/if (py.bytecode/COMPARE_OP "is not" s nil)
           (py/if (instance? ISeq s)
             (.first s)
             (let [s (seq s)]
               (py/if (py.bytecode/COMPARE_OP "is not" s nil)
                 (.first s)
                 nil)))
           nil)))

(def
 ^{:arglists '([coll])
   :tag clojure.lang.ISeq
   :doc "Returns a seq of the items after the first. Calls seq on its argument.
If there are no more items, returns nil."
   :added "1.0"
   :static true}
 next (fn next [s]
        (py/if (is? nil s)
          nil
          (py/if (instance? ISeq s)
            (.next s)
            (let [s (seq s)]
              (.next s))))))

(def
 ^{:arglists '([coll])
   :tag clojure.lang.ISeq
   :doc "Returns a possibly empty seq of the items after the first. Calls seq
on its argument."
   :added "1.0"
   :static true}
 rest (fn rest [x]
        (py/if (py/isinstance x ISeq)
          (.more x)
          (let [s (seq x)]
            (py/if s
              (.more s)
              clojure.lang.persistentlist/EMPTY)))))

(def
 ^{:doc "Same as (first (next x))"
   :arglists '([x])
   :added "1.0"
   :static true}
 second (fn second [x] (first (next x))))

(def
 ^{:doc "Same as (first (first x))"
   :arglists '([x])
   :added "1.0"
   :static true}
 ffirst (fn ffirst [x] (first (first x))))

(def
 ^{:doc "Same as (next (first x))"
   :arglists '([x])
   :added "1.0"
   :static true}
 nfirst (fn nfirst [x] (next (first x))))

(def
 ^{:doc "Same as (first (next x))"
   :arglists '([x])
   :added "1.0"
   :static true}
 fnext (fn fnext [x] (first (next x))))

(def
 ^{:doc "Same as (next (next x))"
   :arglists '([x])
   :added "1.0"
   :static true}
 nnext (fn nnext [x] (next (next x))))

(def
 ^{:tag Boolean
   :doc "Returns true if x is nil, false otherwise."
   :added "1.0"
   :static true}
 nil? (fn nil? [x] (is? x nil)))

(def
 ^{:arglists '([& args])
   :doc "Clojure version of RT.conj"
   :added "1.0"}
 _conj (fn _conj [coll x]
         (py/if (nil? coll)
           (.cons clojure.lang.persistentlist/EMPTY x)
           (.cons coll x))))

(def
 ^{:arglists '([coll x] [coll x & xs])
   :doc "conj[oin]. Returns a new collection with the xs 'added'. (conj nil
item) returns (item). The 'addition' may happen at different 'places'
depending on the concrete type."
   :added "1.0"}
 conj (fn conj
        ([coll x] (_conj coll x))
        ([coll x & xs]
          (py/if (nil? xs)
            (conj coll x)
            (recur (conj coll x) (first xs) (next xs))))))

(def
 ^{:arglists '([map key val] [map key val & kvs])
   :doc "assoc[iate]. When applied to a map, returns a new map of the same
(hashed/sorted) type, that contains the mapping of key(s) to val(s). When
applied to a vector, returns a new vector that contains val at index. Note -
index must be <= (count vector)."
   :added "1.0"}
 assoc
 (fn assoc
   ([map key val] (_assoc map key val))
   ([map key val & kvs]
    (let [ret (assoc map key val)]
      (py/if kvs
        (recur ret (first kvs) (second kvs) (nnext kvs))
        ret)))))

(def
 ^{:arglists '([obj])
   :doc "Returns the metadata of obj, returns nil if there is no metadata."
   :added "1.0"}
 meta (fn meta [x] ((py/getattr x "meta" (fn [] nil)))))

(def
 ^{:arglists '([obj m])
   :doc "Returns an object of the same type and value as obj, with map m as its
metadata."
   :added "1.0"}
 with-meta (fn with-meta [x m] (.withMeta x m)))

(def ^{:private true :dynamic true}
 assert-valid-fdecl (fn [fdecl]))

(def ^{:private true}
 sigs
 (fn [fdecl]
   (assert-valid-fdecl fdecl)
   (let [asig
         (fn [fdecl]
           (let [arglist (first fdecl)
                 ;elide implicit macro args
                 arglist (py/if (.__eq__ '&form (first arglist))
                           (clojure.lang.rt/subvec arglist 2 (py/len arglist))
                           arglist)
                 body (next fdecl)]
             (py/if (map? (first body))
               (py/if (next body)
                 (with-meta
                   arglist
                   (conj (py/if (meta arglist) (meta arglist) {}) (first body)))
                 arglist)
               arglist)))]
     (py/if (seq? (first fdecl))
       (loop [ret [] fdecls fdecl]
         (py/if fdecls
           (recur (conj ret (asig (first fdecls))) (next fdecls))
           (seq ret)))
       (list (asig fdecl))))))

(def
 ^{:arglists '([coll])
   :doc "Return the last item in coll, in linear time"
   :added "1.0"}
 last (fn last [s]
        (py/if (next s)
          (recur (next s))
          (first s))))

(def
 ^{:arglists '([coll])
   :doc "Return a seq of all but the last item in coll, in linear time"
   :added "1.0"}
 butlast (fn butlast [s]
           (loop [ret [] s s]
             (py/if (nil? (next s))
               (seq ret)
               (recur (conj ret (first s)) (next s))))))

(def
 ^{:doc "Same as (def name (fn [params* ] exprs*)) or (def name (fn ([params*]
exprs*)+)) with any doc-string or attrs added to the var metadata.
prepost-map defines a map with optional keys :pre and :post that contain
collections of pre or post conditions."
   :arglists '([name doc-string? attr-map? [params*] prepost-map? body]
               [name doc-string? attr-map? ([params*] prepost-map? body)+ attr-map?])
   :added "1.0"}
 defn (fn defn [&form &env name & fdecl]
        (let [m (py/if (string? (first fdecl))
                  {:doc (first fdecl)}
                  {})
              fdecl (py/if (string? (first fdecl))
                      (next fdecl)
                      fdecl)
              m (py/if (map? (first fdecl))
                  (conj m (first fdecl))
                  m)
              fdecl (py/if (map? (first fdecl))
                      (next fdecl)
                      fdecl)
              fdecl (py/if (vector? (first fdecl))
                      (list fdecl)
                      fdecl)
              m (py/if (map? (last fdecl))
                  (conj m (last fdecl))
                  m)
              fdecl (py/if (map? (last fdecl))
                      (butlast fdecl)
                      fdecl)
              m (conj {:arglists (list 'quote (sigs fdecl))} m)
              m (let [inline (:inline m)
                      ifn (first inline)
                      iname (second inline)]
                  ;; same as: (py/if (and (= 'fn ifn) (not (symbol? iname))) ...)
                  (py/if (py/if (.__eq__ 'fn ifn)
                           (py/if (instance? clojure.lang.symbol/Symbol iname) false true))
                    ;; inserts the same fn name to the inline fn if it does not have one
                    (assoc m :inline
                      (cons
                        ifn
                        (cons (clojure.lang.symbol/Symbol
                                (.concat (.getName name) "__inliner"))
                              (next inline))))
                    m))
              m (conj (py/if (meta name) (meta name) {}) m)]
          (list 'def (with-meta name m)
                ;;todo - restore propagation of fn name
                ;;must figure out how to convey primitive hints to self calls first
                (cons `fn fdecl)))))

(def set-macro
  (fn set-macro [f]
    (py/setattr f "macro?" true)
    f))

(set-macro defn)

(def
 ^{:arglists '([& items])
   :doc "Creates a new vector containing the items."
   :added "1.0"}
  vector clojure.lang.rt/vector)

(defn vec
  "Creates a new vector containing the contents of coll."
  {:added "1.0"
   :static true}
  ([coll]
    (py/if (nil? coll)
      nil
      (clojure.lang.persistentvector/vec coll))))

(defn hash-map
  "keyval => key val
Returns a new hash map with supplied mappings."
  {:added "1.0"}
  ([] {})
  ([& keyvals]
    (let [coll {}]
      (loop [keyvals (seq keyvals) coll coll]
        (py/if (nil? keyvals)
          coll
          (do
            (py/if (py.bytecode/COMPARE_OP "==" (py/len keyvals) 1)
              (throw (py/Exception "Even number of args required to hash-map")))
            (py/if (py.bytecode/COMPARE_OP "in" (first keyvals) coll)
              (throw (py/Exception "Duplicate keys found in hash-map")))
            (recur (nnext keyvals)
              (.assoc coll
                (first keyvals)
                (fnext keyvals)))))))))

(def
 ^{:arglists '([& items])
   :doc "Creates a new hashmap containing the items."
   :added "1.0"}
  hashmap clojure.lang.rt/map)

(def
 ^{:doc "Like defn, but the resulting function name is declared as a macro and
will be used as a macro by the compiler when it is called."
   :arglists '([name doc-string? attr-map? [params*] body]
               [name doc-string? attr-map? ([params*] body)+ attr-map?])
   :added "1.0"}
 defmacro (fn [&form &env
                name & args]
            (let [prefix (loop [p (list name) args args]
                           (let [f (first args)]
                             (py/if (string? f)
                               (recur (cons f p) (next args))
                               (py/if (map? f)
                                 (recur (cons f p) (next args))
                                 p))))
                  fdecl (loop [fd args]
                          (py/if (string? (first fd))
                            (recur (next fd))
                            (py/if (map? (first fd))
                              (recur (next fd))
                              fd)))
                  fdecl (py/if (vector? (first fdecl))
                          (list fdecl)
                          fdecl)
                  add-implicit-args (fn [fd]
                            (let [args (first fd)]
                              (cons (vec (cons '&form (cons '&env args))) (next fd))))
                  add-args (fn [acc ds]
                             (py/if (nil? ds)
                               acc
                               (let [d (first ds)]
                                 (py/if (map? d)
                                   (conj acc d)
                                   (recur (conj acc (add-implicit-args d)) (next ds))))))
                  fdecl (seq (add-args [] fdecl))
                  decl (loop [p prefix d fdecl]
                         (py/if p
                           (recur (next p) (cons (first p) d))
                           d))]
              (list 'do
                    (cons `defn decl)
                    (list 'set-macro name)
                    (list 'py/setattr name "_macro-form" (list 'quote decl))
                    name))))

(set-macro defmacro)

;;; preparing support for the syntax-quote

(def
  ^{:macro true
    :added "1.0"
    :arglists '([pred val] [pred val else])}
  if (fn* if [form env & decl] (cons 'if* decl)))

(defmacro when
  "Evaluates test. If logical true, evaluates body in an implicit do."
  {:added "1.0"}
  [test & body]
  (list 'clojure.core/if test (cons 'do body)))

(defmacro when-not
  "Evaluates test. If logical false, evaluates body in an implicit do."
  {:added "1.0"}
  [test & body]
  (list 'clojure.core/if test nil (cons 'do body)))

(defn not
  "Returns true if x is logical false, false otherwise."
  {:added "1.0"}
  [x] (if* x false true))

(defmacro cond
  "Takes a set of test/expr pairs. It evaluates each test one at a time. If a
test returns logical true, cond evaluates and returns the value of the
corresponding expr and doesn't evaluate any of the other tests or exprs.
(cond) returns nil."
  {:added "1.0"}
  [& clauses]
    (when clauses
      (list 'py/if (first clauses)
        (py/if (next clauses)
          (second clauses)
          (throw (IllegalArgumentException "cond requires an even number of forms")))
        (cons 'clojure.core/cond (next (next clauses))))))

(defn spread
  {:private true}
  [arglist]
  (cond
    (nil? arglist) nil
    (nil? (next arglist)) (seq (first arglist))
    :else (cons (first arglist) (spread (next arglist)))))

(defn list*
  "Creates a new list containing the items prepended to the rest, the
last of which will be treated as a sequence."
  {:added "1.0"}
  ([args] (seq args))
  ([a args] (cons a args))
  ([a b args] (cons a (cons b args)))
  ([a b c args] (cons a (cons b (cons c args))))
  ([a b c d & more]
    (cons a (cons b (cons c (cons d (spread more)))))))

(defn apply
  "Applies fn f to the argument list formed by prepending intervening arguments
to args."
  {:added "1.0"
   :static true}
  ([f args]
     (applyTo f (seq args)))
  ([f x args]
     (applyTo f (list* x args)))
  ([f x y args]
     (applyTo f (list* x y args)))
  ([f x y z args]
     (applyTo f (list* x y z args)))
  ([f a b c d & args]
     (applyTo f (cons a (cons b (cons c (cons d (spread args))))))))

(defn =
  "Equality. Returns true if x equals y, false if not. Same as Java x.equals(y)
except it also works for nil, and compares numbers and collections in a
type-independent manner. Clojure's immutable data structures define equals()
(and thus =) as a value, not an identity, comparison."
  {:added "1.0"}
  ([x] true)
  ([x y] (py.bytecode/COMPARE_OP "==" x y))
  ([x y & more]
   (py/if (py.bytecode/COMPARE_OP "==" x y)
     (py/if (next more)
       (recur y (first more) (next more))
       (py.bytecode/COMPARE_OP "==" y (first more)))
     false)))

(defn not=
  "Same as (not (= obj1 obj2))"
  {:added "1.0"}
  ([x] false)
  ([x y] (not (= x y)))
  ([x y & more]
   (not (apply = x y more))))

(defn false?
  "Returns true if x is the value false, false otherwise."
  {:added "1.0"}
  [x] (= x false))

(defn true?
  "Returns true if x is the value true, false otherwise."
  {:added "1.0"}
  [x] (= x true))

(defn str
  "With no args, returns the empty string. With one arg x, returns x.__str__().
(str nil) returns the empty string. With more than one arg, returns the
concatenation of the str values of the args."
  {:added "1.0"}
  ([] "")
  ([x]
    (if (nil? x) "" (py/str x)))
  ([x & ys]
    (let [lst (py/list (str x))
          lst (loop [remain ys]
                (if remain
                  (do (.append lst (str (first remain)))
                      (recur (next remain)))
                  lst))]
      (.join "" lst))))

(defn symbol?
  "Return true if x is a Symbol"
  {:added "1.0"}
  [x] (instance? clojure.lang.symbol/Symbol x))

(defn keyword?
  "Return true if x is a Keyword"
  {:added "1.0"}
  [x] (instance? clojure.lang.cljkeyword/Keyword x))

(defn symbol
  "Returns a Symbol with the given namespace and name."
  {:tag clojure.lang.Symbol
   :added "1.0"}
  ([name] (clojure.lang.symbol/Symbol name))
  ([ns name] (clojure.lang.symbol/Symbol ns name)))

(defn gensym
  "Returns a new symbol with a unique name. If a prefix string is supplied, the
name is prefix# where # is some unique number. If prefix is not supplied, the
prefix is 'G__'."
  {:added "1.0"}
  ([] (gensym "G__"))
  ([prefix-string]
    (symbol (str prefix-string (py/str (. clojure.lang.rt (nextID)))))))

(defn keyword
  "Returns a keyword for the given string"
  [x]
  (clojure.lang.cljkeyword/Keyword x))

(def
  ^{:doc "Returns the name String of a string, symbol or keyword."
    :static true}
  name
  clojure.lang.rt/name)

(defn vary-meta
  "Returns an object of the same type and value as obj, with (apply f (meta
obj) args) as its metadata."
 {:added "1.0"
   :static true}
 [obj f & args]
  (with-meta obj (apply f (meta obj) args)))

(defn identical?
  "Tests if 2 arguments are the same object"
  {:added "1.0"}
  ([x y] (py.bytecode/COMPARE_OP "is" x y)))

;;; private defs
(defmacro defn-
  "same as defn, yielding non-public def"
  {:added "1.0"}
  [name & decls]
    (list* `defn (with-meta name (assoc (meta name) :private true)) decls))

;;; deftype
(defn make-init
  "Creates a __init__ method for use in deftype"
  [fields]
  (loop [fields fields
         args ['self]
         body []]
    (py/if (not fields)
      (cons 'fn (cons '__init__ (cons args body)))
      (let [newargs (conj args (first fields))
            newbody (conj body
                          (list 'py/setattr 'self (py/str (first fields)) (first fields)))]
           (recur (next fields) newargs newbody)))))

(defn make-props
  [fields selfname]
  (loop [remain (seq fields)
         props []]
    (py/if (nil? remain)
      props
      (recur (next remain)
             (conj (conj props (first remain))
                   (list 'py/getattr selfname (.-name (first remain))))))))

(defn prop-wrap-fn
  [name members f]
  (list 'fn
    (symbol (str name "_" (first f)))
    (second f)
    (list* 'let-macro
      (make-props members
                  (first (fnext f)))
      (next (next f)))))

(defn prop-wrap-multi
  [name members f]
  (let [name (symbol (str name "_" (first f)))
        f (next f)
        wrapped (loop [remain f
                       wr []]
    (py/if remain
      (let [cur (first remain)
            args (first cur)
            body (next cur)]
        (recur (next remain)
               (cons (list args
                       (list* 'let-macro
                         (make-props members (first args))
                        body))
                     wr)))
      wr))]
  (list* 'fn name wrapped)))

(defn prop-wrap
  [name members f]
  (if (vector? (fnext f))
    (prop-wrap-fn name members f)
    (prop-wrap-multi name members f)))

(defmacro deftype
  [name fields & specs]
  (loop [specs (seq specs)
         inherits []
         fns (if (= (py/len fields) 0) {} {"__init__" (make-init fields)})]
    (cond (not specs)
            (list 'def name (list 'py/type (.-name name)
                            (list 'py/tuple (conj inherits py/object))
                            (list '.toDict fns)))
          (symbol? (first specs))
            (recur (next specs)
                   (conj inherits (first specs))
                   fns)
          (instance? clojure.lang.ipersistentlist/IPersistentList (first specs))
            (recur (next specs)
                   inherits
                   (assoc fns (py/str (ffirst specs))
                     (prop-wrap name fields (first specs)))))))

(def definterface deftype)

(set-macro definterface)

(def
  ^{:static true}
  extend clojure.lang.protocol/extend)

;;; lazy and chunked seqs
(defn inc
  "Returns a number one greater than num. Does not auto-promote longs, will
throw on overflow. See also: inc'"
  {:added "1.2"
   :static true}
  [x] (py.bytecode/BINARY_ADD x 1))

(defmacro lazy-seq
  "Takes a body of expressions that returns an ISeq or nil, and yields a
Seqable object that will invoke the body only the first time seq is called,
and will cache the result and return it on all subsequent seq calls. See also
- realized?"
  {:added "1.0"}
  [& body]
  (list 'clojure.core/LazySeq (list* '^{:once true} fn* [] body) nil nil nil))

(definterface IPending []
  (isRealized [self] nil))

(deftype LazySeq [fnc sv s _meta]
  (withMeta [self meta]
    (LazySeq nil nil (.seq self) meta))
  (sval [self]
    (when (not (nil? fnc))
      (py/setattr self "sv" (fnc))
      (py/setattr self "fnc" nil))
    (py/if (not (nil? sv))
      sv
      s))
  clojure.lang.iseq/ISeq
  (seq [self]
    (.sval self)
    (when (not (nil? sv))
      (let [ls sv]
        (py/setattr self "sv" nil)
          (py/setattr self "s"
          (loop [ls ls]
            (py/if (instance? LazySeq ls)
              (recur (.sval ls))
              (seq ls))))))
    s)
  (__len__ [self]
    (loop [c 0
           s (.seq self)]
      (py/if (nil? s)
        c
        (recur (inc c) (next s)))))
  (__eq__ [self other]
    (loop [s (seq self)
           o (seq other)]
      (if (nil? s)
        (if (nil? o)
          true
          false)
        (if (nil? o)
          false
          (if (py.bytecode/COMPARE_OP "==" (first s) (first o))
            (recur (next s) (next o))
            false)))))
  (__iter__ [self]
    (loop [s (seq self)]
      (when s
        (py.bytecode/YIELD_VALUE (first s))
        (recur (next s)))))
  (__repr__ [self]
    (loop [c []
           s (seq self)
           cnt 0]
      (if (not (nil? s))
        (if (py.bytecode/COMPARE_OP "<" cnt 10)
          (recur (conj c (str (first s)))
                 (next s)
                 (inc cnt))
          (recur (conj c "...")
                 nil
                 11)))
      (str "[" (.join " " c) "]")))
  (first [self]
    (.seq self)
    (py/if (nil? s)
      nil
      (.first s)))
  (next [self]
    (.seq self)
    (py/if (nil? s)
      nil
      (.next s)))
  (more [self]
    (.seq self)
    (py/if (nil? s)
      (list)
      (.more s)))
  (cons [self o]
    (cons o (.seq self)))
  (empty [self]
    (list))
    ;; IPrintable protocol
    ;; These methods realize the entire sequence as Clojure does. But
    ;; __repr__ does not. Is the intent to prevent spamming the repl?
    clojure.lang.iprintable/IPrintable
    (writeAsString [self writer]
      (.write writer "(")
      (loop [s (.seq self)]
      (when s
        (clojure.protocols/writeAsString (.first s) writer)
        (when (.next s)
        (.write writer " "))
        (recur (.next s))))
      (.write writer ")"))
    (writeAsReplString [self writer]
      (.write writer "(")
      (loop [s (.seq self)]
      (when s
        (clojure.protocols/writeAsReplString (.first s) writer)
        (when (.next s)
        (.write writer " "))
        (recur (.next s))))
      (.write writer ")")))

(clojure.lang.protocol/extendForAllSubclasses clojure.lang.iseq/ISeq)
(clojure.lang.protocol/extendForAllSubclasses
 clojure.lang.iprintable/IPrintable)

(def generic-interator-fn
  {:seq (fn generator-seq [self]
          (lazy-seq
            (try
              (let [result (.next self)]
                (cons result (generator-seq self)))
              (catch py/StopIteration e nil))))})

(extend clojure.lang.pytypes/pyTypeGenerator
    Seqable
    generic-interator-fn)

(extend clojure.lang.pytypes/pyReversedType
    Seqable
    generic-interator-fn)

(definterface IChunkedSeq []
  clojure.lang.sequential/Sequential
  clojure.lang.iseq/ISeq
  (chunkedFirst [self] nil)
  (chunkedNext [self] nil)
  (chunkedMore [self] nil))

(deftype ArrayChunk [array off end]
  (__getitem__
    ([self i]
      (py.bytecode/BINARY_SUBSCR array (py.bytecode/BINARY_ADD off i)))
    ([self i not-found]
      (if (py.bytecode/COMPARE_OP ">=" i 0)
        (if (py.bytecode/COMPARE_OP "<" i (py/len self))
          (py.bytecode/BINARY_SUBSCR array i)
          not-found)
        not-found)))
  (__len__ [self]
    (py.bytecode/BINARY_SUBTRACT end off))
  (nth [self & args]
    (apply (.-__getitem__ self) args))
  (dropFirst [self]
    (if (= off end)
      (throw (IllegalStateException "dropFirst of empty chunk")))
    (ArrayChunk array (inc off) end))
  (reduce [self f start]
    (loop [ret (f start (py.bytecode/BINARY_SUBSCR array off))
         x (inc off)]
       (if (py.bytecode/COMPARE_OP "<" x end)
       (recur (f ret (py.bytecode/BINARY_SUBSCR array x))
        (inc x))
       ret))))

(deftype ChunkBuffer [buffer end]
  (add [self o]
    (py.bytecode/STORE_SUBSCR o buffer end)
    (py/setattr self "end" (inc end)))
  (chunk [self]
    (let [ret (ArrayChunk buffer 0 end)]
       (py/setattr self "buffer" nil)
       ret))
  (__len__ [self] end))

(deftype ChunkedCons [_meta chunk _more]
  clojure.lang.aseq/ASeq
  (first [self]
    (py.bytecode/BINARY_SUBSCR chunk 0))
  (withMeta [self meta]
    (if (py.bytecode/COMPARE_OP "is not" meta _meta)
      (ChunkedCons meta chunk _more)
    self))
  (meta [self] _meta)
  (next [self]
    (if (py.bytecode/COMPARE_OP ">" (py/len chunk) 1)
      (ChunkedCons nil (.dropFirst chunk) _more)
      (.chunkedNext self)))
  (more [self]
    (cond (py.bytecode/COMPARE_OP ">" (py/len chunk) 1)
            (ChunkedCons nil (.dropFirst chunk) _more)
          (py.bytecode/COMPARE_OP "is" _more nil)
            '()
          :else
            _more))

  IChunkedSeq
  (chunkedFirst [self] chunk)
  (chunkedNext [self]
    (.seq (.chunkedMore self)))
  (chunkedMore [self]
    (if (is? _more nil)
      '()
      _more)))

(defn chunk-buffer [capacity]
  (ChunkBuffer (py.bytecode/BINARY_MULTIPLY (py/list [nil]) capacity) 0))

(defn chunk-append [b x]
  (.add b x))

(defn chunk [b]
  (.chunk b))

(defn chunk-first [s]
  (.chunkedFirst s))

(defn chunk-rest [s]
  (.chunkedMore s))

(defn chunk-next [s]
  (.chunkedNext s))

(defn chunk-cons [chunk rest]
  (if (= (py/len chunk) 0)
    rest
    (ChunkedCons nil chunk rest)))

(defn chunked-seq? [s]
  (instance? IChunkedSeq s))

(defn concat
  "Returns a lazy seq representing the concatenation of the elements in the
supplied colls."
  {:added "1.0"}
  ([] (lazy-seq nil))
  ([x] (lazy-seq x))
  ([x y]
    (lazy-seq
      (let [s (seq x)]
        (if s
          (if (chunked-seq? s)
            (chunk-cons (chunk-first s) (concat (chunk-rest s) y))
            (cons (first s) (concat (rest s) y)))
          y))))
  ([x y & zs]
     (let [cat (fn cat [xys zs]
                 (lazy-seq
                   (let [xys (seq xys)]
                     (if xys
                       (if (chunked-seq? xys)
                         (chunk-cons (chunk-first xys)
                                     (cat (chunk-rest xys) zs))
                         (cons (first xys) (cat (rest xys) zs)))
                       (when zs
                         (cat (first zs) (next zs)))))))]
       (cat (concat x y) zs))))

;; at this point all the support for the syntax quote exists

;;; flow control
(defmacro if-not
  "Evaluates test. If logical false, evaluates and returns then expr,
otherwise else expr, if supplied, else nil."
  {:added "1.0"}
  ([test then] `(if-not ~test ~then nil))
  ([test then else]
   `(if (not ~test) ~then ~else)))

(defmacro and
  "Evaluates exprs one at a time, from left to right. If a form returns logical
false (nil or false), and returns that value and doesn't evaluate any of the
other expressions, otherwise it returns the value of the last expr. (and)
returns true."
  {:added "1.0"}
  ([] true)
  ([x] x)
  ([x & next]
   `(let [and# ~x]
      (if and# (and ~@next) and#))))

(defmacro or
  "Evaluates exprs one at a time, from left to right. If a form returns a
logical true value, or returns that value and doesn't evaluate any of the
other expressions, otherwise it returns the value of the last expression.
(or) returns nil."
  {:added "1.0"}
  ([] nil)
  ([x] x)
  ([x & next]
    `(let [or# ~x]
       (if or# or# (or ~@next)))))

;; reduce is defined again later after InternalReduce loads
(defn reduce1
  ([f coll]
    (let [s (seq coll)]
      (if s
        (reduce1 f (first s) (next s))
        (f))))
  ([f val coll]
    (let [s (seq coll)]
      (if s
        (if (chunked-seq? s)
          (recur f
                 (.reduce (chunk-first s) f val)
                 (chunk-next s))
          (recur f (f val (first s)) (next s)))
       val))))

(defn reverse
  "Returns a seq of the items in coll in reverse order. Not lazy."
  {:added "1.0"}
  [coll] (reduce1 conj () coll))

;;; math functions
(defn >1? [n] (py.bytecode/COMPARE_OP ">" n 1))
(defn >0? [n] (py.bytecode/COMPARE_OP ">" n 0))

(defn +
  "Returns the sum of nums. (+) returns 0. Does not auto-promote longs, will
throw on overflow. See also: +'"
  {:added "1.2"}
  ([] 0)
  ([x] x)
  ([x y] (py.bytecode/BINARY_ADD x y))
  ([x y & more]
     (reduce1 + (+ x y) more)))

(defn *
  "Returns the product of nums. (*) returns 1. Does not auto-promote longs,
will throw on overflow. See also: *'"
  {:added "1.2"}
  ([] 1)
  ([x] x)
  ([x y] (py.bytecode/BINARY_MULTIPLY x y))
  ([x y & more]
     (reduce1 * (* x y) more)))

(defn /
  "If no denominators are supplied, returns 1/numerator, else returns numerator
divided by all of the denominators."
  {:added "1.0"}
  ([x] (/ 1 x))
  ([x y] (py.bytecode/BINARY_DIVIDE x y))
  ([x y & more]
   (reduce1 / (/ x y) more)))

(defn -
  "If no ys are supplied, returns the negation of x, else subtracts the ys from
x and returns the result. Does not auto-promote longs, will throw on
overflow. See also: -'"
  {:added "1.2"}
  ([x] (py.bytecode/UNARY_NEGATIVE x))
  ([x y] (py.bytecode/BINARY_SUBTRACT x y))
  ([x y & more]
     (reduce1 - (- x y) more)))

(defn <
  "Returns non-nil if nums are in monotonically increasing order, otherwise
false."
  {:added "1.0"
   :static true}
  ([x] true)
  ([x y] (py.bytecode/COMPARE_OP "<" x y))
  ([x y & more]
   (if (< x y)
     (if (next more)
       (recur y (first more) (next more))
       (< y (first more)))
     false)))

(defn <=
  "Returns non-nil if nums are in monotonically non-decreasing order, otherwise
false."
  {:added "1.0"}
  ([x] true)
  ([x y] (py.bytecode/COMPARE_OP "<=" x y))
  ([x y & more]
   (if (<= x y)
     (if (next more)
       (recur y (first more) (next more))
       (<= y (first more)))
     false)))

(defn >
  "Returns non-nil if nums are in monotonically decreasing order, otherwise
false."
  {:added "1.0"}
  ([x] true)
  ([x y] (py.bytecode/COMPARE_OP ">" x y))
  ([x y & more]
   (if (> x y)
     (if (next more)
       (recur y (first more) (next more))
       (> y (first more)))
     false)))

(defn >=
  "Returns non-nil if nums are in monotonically non-increasing order, otherwise
false."
  {:added "1.0"}
  ([x] true)
  ([x y] (py.bytecode/COMPARE_OP ">=" x y))
  ([x y & more]
   (if (>= x y)
     (if (next more)
       (recur y (first more) (next more))
       (>= y (first more)))
     false)))

(defn ==
  "Returns non-nil if nums all have the equivalent value (type-independent),
otherwise false"
  {:added "1.0"}
  ([x] true)
  ([x y] (py.bytecode/COMPARE_OP "==" x y))
  ([x y & more]
   (if (== x y)
     (if (next more)
       (recur y (first more) (next more))
       (== y (first more)))
     false)))

(defn dec
  "Returns a number one less than num. Does not auto-promote longs, will throw
on overflow. See also: dec'"
  {:added "1.2"}
  [x] (py.bytecode/BINARY_SUBTRACT x 1))

(defn max
  "Returns the greatest of the nums."
  {:added "1.0"}
  ([x] x)
  ([x y] (py/max x y))
  ([x y & more]
    (reduce1 max (max x y) more)))

(defn min
  "Returns the least of the nums."
  {:added "1.0"}
  ([x] x)
  ([x y] (py/min x y))
  ([x y & more]
    (reduce1 min (min x y) more)))

(defn zero?
  "Returns true if num is zero, else false"
  {:added "1.0"}
  [x] (py.bytecode/COMPARE_OP "==" x 0))

(defn pos?
  "Returns true if num is greater than zero, else false"
  {:added "1.0"}
  [x] (> x 0))

(defn neg?
  "Returns true if num is less than zero, else false"
  {:added "1.0"}
  [x] (< x 0))

(defn quot
  "quot[ient] of dividing numerator by denominator."
  {:added "1.0"}
  [num div]
    (let [q (py.bytecode/BINARY_FLOOR_DIVIDE num div)]
      (if (>= q 0)
        q
        (if (= 0 (py.bytecode/BINARY_MODULO num div))
          q
          (inc q)))))

(defn mod
  "modulus of dividing numerator by denominator. Truncates toward negative infinity."
  {:added "1.0"}
  [num div]
    (py.bytecode/BINARY_MODULO num div))

(defn rem
  "remainder of dividing numerator by denominator."
  {:added "1.0"
   :static true}
  [num div]
  (let [m (quot num div)]
      (- num (* m div))))

(defn bit-not
  "Bitwise complement"
  {:added "1.0"}
  [x] (py.bytecode/UNARY_INVERT x))

(defn bit-and
  "Bitwise and"
   {:added "1.0"}
   ([x y] (py.bytecode/BINARY_AND x y))
   ([x y & more]
     (reduce1 bit-and (bit-and x y) more)))

(defn bit-or
  "Bitwise or"
  {:added "1.0"}
  ([x y] (py.bytecode/BINARY_OR x y))
  ([x y & more]
    (reduce1 bit-or (bit-or x y) more)))

(defn bit-xor
  "Bitwise exclusive or"
  {:added "1.0"}
  ([x y] (py.bytecode/BINARY_XOR x y))
  ([x y & more]
    (reduce1 bit-xor (bit-xor x y) more)))

(defn bit-and-not
  "Bitwise and with complement"
  {:added "1.0"}
  ([x y] (py.bytecode/BINARY_AND x (py.bytecode/UNARY_NOT y)))
  ([x y & more]
    (reduce1 bit-and-not (bit-and-not x y) more)))

(defn bit-shift-left
  "Bitwise shift left"
  {:added "1.0"}
  [x n] (py.bytecode/BINARY_LSHIFT x n))

(defn bit-shift-right
  "Bitwise shift right"
  {:added "1.0"}
  [x n] (py.bytecode/BINARY_RSHIFT x n))

(defn bit-clear
  "Clear bit at index n"
  {:added "1.0"}
  [x n] (bit-and x (bit-not (bit-shift-left 1 n))))

(defn bit-set
  "Set bit at index n"
  {:added "1.0"}
  [x n] (bit-or x (bit-shift-left 1 n)))

(defn bit-flip
  "Flip bit at index n"
  {:added "1.0"}
  [x n] (bit-xor x (bit-shift-left 1 n)))

(defn bit-test
  "Test bit at index n"
  {:added "1.0"}
  [x n] (py.bytecode/COMPARE_OP "==" (bit-and (bit-shift-right x n) 1) 1))

(defn integer?
  "Returns true if n is an integer"
  {:added "1.0"}
  [n] (or (instance? py/int n)))

(defn even?
  "Returns true if n is even, throws an exception if n is not an integer"
  {:added "1.0"}
  [n]
  (if (integer? n)
    (zero? (bit-and n 1))
    (throw (py/TypeError (str "Argument must be an integer: " n)))))

(defn odd?
  "Returns true if n is odd, throws an exception if n is not an integer"
  {:added "1.0"}
  [n] (not (even? n)))

;;; collections
(defn coll?
  "Returns true if x implements IPersistentCollection"
  {:added "1.0"}
  [x] (instance? clojure.lang.ipersistentcollection/IPersistentCollection x))

(defn list?
  "Returns true if x implements IPersistentList"
  {:added "1.0"}
  [x] (instance? clojure.lang.ipersistentlist/IPersistentList x))

(defn set?
  "Returns true if x implements IPersistentSet"
  {:added "1.0"}
  [x] (instance? clojure.lang.ipersistentset/IPersistentSet x))

(defn pylist?
  "Returns true if coll is a native python list"
  [coll] (instance? py/list coll))

(defn tuple?
  "Returns true if toll is a native python tuple"
  [coll] (instance? py/tuple coll))

(defn unicode?
  "Returns true if x is unicode"
  [x] (instance? py/unicode x))

(defn sequential?
  "Returns true if coll implements Sequential"
  {:added "1.0"
   :static true}
  [coll] (instance? clojure.lang/Sequential coll))

(defn count
  "Returns the number of items in the collection. (count nil) returns 0. Also
works on strings, arrays, and Java Collections and Maps"
  {:added "1.0"}
  [coll] (if (nil? coll) 0 (py/len coll)))

;;; list stuff
(defn peek
  "For a list or queue, same as first, for a vector, same as, but much more
efficient than, last. If the collection is empty, returns nil."
  {:added "1.0"}
  [coll]
  (if (nil? coll) nil (.peek coll)))

(defn pop
  "For a list or queue, returns a new list/queue without the first item, for a
vector, returns a new vector without the last item. If the collection is
empty, throws an exception. Note - not the same as next/butlast."
  {:added "1.0"}
  [coll]
  (if (nil? coll) nil (.pop coll)))

;;; map stuff
(defn contains?
  "Returns true if key is present in the given collection, otherwise returns
false. Note that for numerically indexed collections like vectors and Java
arrays, this tests if the numeric key is within the range of indexes.
'contains?' operates constant or logarithmic time; it will not perform a
linear search for a value. See also 'some'."
  {:added "1.0"}
  [coll key]
  (cond (or (vector? coll)
            (list? coll)
            (tuple? coll)
            (pylist? coll)
            (string? coll)
            (and (not (py/hasattr coll "__contains__"))
                 (py/hasattr coll "__len__")))
          (and (>= key 0) (< key (count coll)))
        (nil? coll)
          false
        :else
          (py.bytecode/COMPARE_OP "in" key coll)))

(defn get
  "Returns the value mapped to key, not-found or nil if key not present."
  {:added "1.0"}
  ([map key]
   (get map key nil))
  ([map key not-found]
   (cond (instance? clojure.lang.ilookup/ILookup map)
           (.valAt map key not-found)
         :else
           (if (contains? map key)
               (py.bytecode/BINARY_SUBSCR map key)
               not-found))))

(defn dissoc
  "dissoc[iate]. Returns a new map of the same (hashed/sorted) type, that does
not contain a mapping for key(s)."
  {:added "1.0"
   :static true}
  ([map] map)
  ([map key]
   (if (nil? map) nil (.without map key)))
  ([map key & ks]
   (let [ret (dissoc map key)]
     (if ks
       (recur ret (first ks) (next ks))
       ret))))

(defn disj
  "disj[oin]. Returns a new set of the same (hashed/sorted) type, that does not
contain key(s)."
  {:added "1.0"
   :static true}
  ([set] set)
  ([set key]
   (when set
     (. set (disjoin key))))
  ([set key & ks]
   (when set
     (let [ret (disj set key)]
       (if ks
         (recur ret (first ks) (next ks))
         ret)))))

(defn find
  "Returns the map entry for key, or nil if key not present."
  {:added "1.0"}
  [map key]
   (cond (nil? map)
           nil
         (instance? clojure.lang.associative/Associative map)
           (.entryAt map key)
         :else
           (if (contains? map key)
             (clojure.lang.mapentry/MapEntry key (get map key))
             nil)))

(defn select-keys
  "Returns a map containing only those entries in map whose key is in keys"
  {:added "1.0"}
  [map keyseq]
  (loop [ret {} keys (seq keyseq)]
    (if keys
      (let [entry (find map (first keys))]
        (recur
          (if entry
            (conj ret entry)
            ret)
          (next keys)))
      ret)))

(defn keys
  "Returns a sequence of the map's keys."
  {:added "1.0"
   :static true}
  [map]
  (if (map? map)
    (clojure.lang.apersistentmap/createKeySeq (seq map))
    (seq (.keys map))))

(defn vals
  "Returns a sequence of the map's keys."
  {:added "1.0"
   :static true}
  [map]
  (if (map? map)
    (clojure.lang.apersistentmap/createValueSeq (seq map))
    (seq (.items map))))

(defn key
  "Returns the key of the map entry."
  {:added "1.0"
   :static true}
  [e] (.getKey e))

(defn val
  "Returns the value in the map entry."
  {:added "1.0"
   :static true}
  [e] (. e (getValue)))

;;; classes and coercion
(defn class
  "Returns the Class of x"
  {:added "1.0"}
  [x] (py/type x))

(defn type
  "Returns the :type metadata of x, or its Class if none"
  {:added "1.0"
   :static true}
  [x] (or (get (meta x) :type) (class x)))

(defn int
  "Coerce to int"
  {:added "1.0"}
  [x] (py/int x))

(defn num
  "Coerce to Number"
  {:added "1.0"}
  [x] (py/float x))

(defn float?
  "Returns true if n is a floating point number"
  {:added "1.0"
   :static true}
  [n] (instance? py/float n))

(defn int?
  "Returns true if n is a floating point number"
  {:added "1.0"
   :static true}
  [n] (instance? py/int n))

(defn boolean [x] (if x true false))

;;; binding forms
(defmacro assert-args
  [& pairs]
  `(do (when-not ~(first pairs)
         (throw (py/Exception
                  (str (first ~'&form) " requires " ~(second pairs) " in " ~'*ns* ":" (:line (meta ~'&form))))))
     ~(let [more (nnext pairs)]
        (when more
          (list* `assert-args more)))))

(defmacro if-let
  "bindings => binding-form test

If test is true, evaluates then with binding-form bound to the value of
test, if not, yields else"
  {:added "1.0"}
  ([bindings then]
   `(if-let ~bindings ~then nil))
  ([bindings then else & oldform]
   (assert-args
     (and (vector? bindings) (nil? oldform)) "a vector for its binding"
     (= 2 (count bindings)) "exactly 2 forms in binding vector")
   (let [form (bindings 0) tst (bindings 1)]
     `(let [temp# ~tst]
        (if temp#
          (let [~form temp#]
            ~then)
          ~else)))))

(defmacro when-let
  "bindings => binding-form test

When test is true, evaluates body with binding-form bound to the value of test"
  {:added "1.0"}
  [bindings & body]
  (assert-args
     (vector? bindings) "a vector for its binding"
     (= 2 (count bindings)) "exactly 2 forms in binding vector")
   (let [form (bindings 0) tst (bindings 1)]
    `(let [temp# ~tst]
       (when temp#
         (let [~form temp#]
           ~@body)))))

;;; higher-order functions
(def FunctionType (py/type (fn x [] "")))
(defn fn?
  "Returns true if x s a builtin function, i.e. is an object created via fn."
  {:added "1.0"
   :static true}
  [x] (instance? FunctionType x))

(defn complement
  "Takes a fn f and returns a fn that takes the same arguments as f, has the
same effects, if any, and returns the opposite truth value."
  {:added "1.0"}
  [f]
  (fn
    ([] (not (f)))
    ([x] (not (f x)))
    ([x y] (not (f x y)))
    ([x y & zs] (not (apply f x y zs)))))

(defn constantly
  "Returns a function that takes any number of arguments and returns x."
  {:added "1.0"}
  [x] (fn [& args] x))

(defn identity
  "Returns its argument."
  {:added "1.0"}
  [x] x)

(defn comp
  "Takes a set of functions and returns a fn that is the composition of those
fns. The returned fn takes a variable number of args, applies the rightmost
of fns to the args, the next fn (right-to-left) to the result, etc."
  {:added "1.0"}
  ([] identity)
  ([f] f)
  ([f g]
   (fn
     ([] (f (g)))
     ([x] (f (g x)))
     ([x y] (f (g x y)))
     ([x y z] (f (g x y z)))
     ([x y z & args] (f (apply g x y z args)))))
  ([f g h]
   (fn
     ([] (f (g (h))))
     ([x] (f (g (h x))))
     ([x y] (f (g (h x y))))
     ([x y z] (f (g (h x y z))))
     ([x y z & args] (f (g (apply h x y z args))))))
  ([f1 f2 f3 & fs]
   (let [fs (reverse (list* f1 f2 f3 fs))]
     (fn [& args]
       (loop [ret (apply (first fs) args) fs (next fs)]
         (if fs
           (recur ((first fs) ret) (next fs))
           ret))))))

(defn juxt
  "Takes a set of functions and returns a fn that is the juxtaposition of those
fns. The returned fn takes a variable number of args, and returns a vector
containing the result of applying each fn to the args (left-to-right).
((juxt a b c) x) => [(a x) (b x) (c x)]"
  {:added "1.1"}
  ([f]
   (fn
     ([] [(f)])
     ([x] [(f x)])
     ([x y] [(f x y)])
     ([x y z] [(f x y z)])
     ([x y z & args] [(apply f x y z args)])))
  ([f g]
   (fn
     ([] [(f) (g)])
     ([x] [(f x) (g x)])
     ([x y] [(f x y) (g x y)])
     ([x y z] [(f x y z) (g x y z)])
     ([x y z & args] [(apply f x y z args) (apply g x y z args)])))
  ([f g h]
   (fn
     ([] [(f) (g) (h)])
     ([x] [(f x) (g x) (h x)])
     ([x y] [(f x y) (g x y) (h x y)])
     ([x y z] [(f x y z) (g x y z) (h x y z)])
     ([x y z & args] [(apply f x y z args) (apply g x y z args) (apply h x y z args)])))
  ([f g h & fs]
   (let [fs (list* f g h fs)]
     (fn
       ([] (reduce1 #(conj %1 (%2)) [] fs))
       ([x] (reduce1 #(conj %1 (%2 x)) [] fs))
       ([x y] (reduce1 #(conj %1 (%2 x y)) [] fs))
       ([x y z] (reduce1 #(conj %1 (%2 x y z)) [] fs))
       ([x y z & args] (reduce1 #(conj %1 (apply %2 x y z args)) [] fs))))))

(defn partial
  "Takes a function f and fewer than the normal arguments to f, and returns a
fn that takes a variable number of additional args. When called, the returned
function calls f with args + additional args."
  {:added "1.0"}
  ([f arg1]
   (fn [& args] (apply f arg1 args)))
  ([f arg1 arg2]
   (fn [& args] (apply f arg1 arg2 args)))
  ([f arg1 arg2 arg3]
   (fn [& args] (apply f arg1 arg2 arg3 args)))
  ([f arg1 arg2 arg3 & more]
   (fn [& args] (apply f arg1 arg2 arg3 (concat more args)))))

(defn compare
  "Comparator. Returns a negative number, zero, or a positive number when x is
logically 'less than', 'equal to', or 'greater than' y. Same as Java
x.compareTo(y) except it also works for nil, and compares numbers and
collections in a type-independent manner. x must implement Comparable"
  {:added "1.0"}
  [x y] (py/cmp x y))

;;; collections
(defn sequence
  "Coerces coll to a (possibly empty) sequence, if it is not already one. Will
not force a lazy seq. (sequence nil) yields ()"
  {:added "1.0"}
  [coll]
   (if (seq? coll) coll
    (or (seq coll) ())))

(defn empty?
  "Returns true if coll has no items - same as (not (seq coll)). Please use the
idiom (seq x) rather than (not (empty? x))"
  {:added "1.0"
   :static true}
  [coll] (not (seq coll)))

(defn not-empty
  "If coll is empty, returns nil, else coll"
  {:added "1.0"
   :static true}
  [coll] (when (seq coll) coll))

(defn every?
  "Returns true if (pred x) is logical true for every x in coll, else false."
  {:added "1.0"}
  [pred coll]
  (cond
   (nil? (seq coll)) true
   (pred (first coll)) (recur pred (next coll))
   :else false))

(def
 ^{:doc "Returns false if (pred x) is logical true for every x in coll, else
true."
   :added "1.0"}
 not-every? (comp not every?))

(defn some
  "Returns the first logical true value of (pred x) for any x in coll, else
nil. One common idiom is to use a set as pred, for example this will return
:fred if :fred is in the sequence, otherwise nil: (some #{:fred} coll)"
  {:added "1.0"}
  [pred coll]
    (when (seq coll)
      (or (pred (first coll)) (recur pred (next coll)))))

(def
 ^{:doc "Returns false if (pred x) is logical true for any x in coll, else
true."
   :added "1.0"}
 not-any? (comp not some))

;will be redefed later with arg checks
(defmacro dotimes
  "bindings => name n

Repeatedly executes body (presumably for side-effects) with name bound to
integers from 0 through n-1."
  {:added "1.0"}
  [bindings & body]
  (let [i (first bindings)
        n (second bindings)]
    `(let [n# ~n]
       (loop [~i 0]
         (when (< ~i n#)
           ~@body
           (recur (inc ~i)))))))

(defn map
  "Returns a lazy sequence consisting of the result of applying f to the set of
first items of each coll, followed by applying f to the set of second items
in each coll, until any one of the colls is exhausted. Any remaining items
in other colls are ignored. Function f should accept number-of-colls
arguments."
  {:added "1.0"
   :static true}
  ([f coll]
   (lazy-seq
    (when-let [s (seq coll)]
      (if (chunked-seq? s)
        (let [c (chunk-first s)
              size (int (count c))
              b (chunk-buffer size)]
          (dotimes [i size]
              (chunk-append b (f (.__getitem__ c i))))
          (chunk-cons (chunk b) (map f (chunk-rest s))))
        (cons (f (first s)) (map f (rest s)))))))
  ([f c1 c2]
   (lazy-seq
    (let [s1 (seq c1) s2 (seq c2)]
      (when (and s1 s2)
        (cons (f (first s1) (first s2))
              (map f (rest s1) (rest s2)))))))
  ([f c1 c2 c3]
   (lazy-seq
    (let [s1 (seq c1) s2 (seq c2) s3 (seq c3)]
      (when (and s1 s2 s3)
        (cons (f (first s1) (first s2) (first s3))
              (map f (rest s1) (rest s2) (rest s3)))))))
  ([f c1 c2 c3 & colls]
   (let [step (fn step [cs]
                 (lazy-seq
                  (let [ss (map seq cs)]
                    (when (every? identity ss)
                      (cons (map first ss) (step (map rest ss)))))))]
     (map #(apply f %) (step (conj colls c3 c2 c1))))))

(defn mapcat
  "Returns the result of applying concat to the result of applying map to f and
colls. Thus function f should return a collection."
  {:added "1.0"
   :static true}
  [f & colls]
    (apply concat (apply map f colls)))

(defn filter
  "Returns a lazy sequence of the items in coll for which (pred item) returns
true. pred must be free of side-effects."
  {:added "1.0"
   :static true}
  ([pred coll]
   (lazy-seq
     (when-let [s (seq coll)]
       (if (chunked-seq? s)
         (let [c (chunk-first s)
               size (count c)
               b (chunk-buffer size)]
           (dotimes [i size]
             (when (pred (.nth c i))
               (chunk-append b (.nth c i))))
           (chunk-cons (chunk b) (filter pred (chunk-rest s))))
         (let [f (first s) r (rest s)]
           (if (pred f)
             (cons f (filter pred r))
             (filter pred r))))))))

(defn remove
  "Returns a lazy sequence of the items in coll for which (pred item) returns
false. pred must be free of side-effects."
  {:added "1.0"
   :static true}
  [pred coll]
  (filter (complement pred) coll))

(defn take
  "Returns a lazy sequence of the first n items in coll, or all items if there
are fewer than n."
  {:added "1.0"}
  [n coll]
  (lazy-seq
   (when (pos? n)
     (when-let [s (seq coll)]
      (cons (first s) (take (dec n) (rest s)))))))

(defn take-while
  "Returns a lazy sequence of successive items from coll while (pred item)
returns true. pred must be free of side-effects."
  {:added "1.0"}
  [pred coll]
  (lazy-seq
   (when-let [s (seq coll)]
       (when (pred (first s))
         (cons (first s) (take-while pred (rest s)))))))

(defn drop
  "Returns a lazy sequence of all but the first n items in coll."
  {:added "1.0"}
  [n coll]
  (let [step (fn [n coll]
               (let [s (seq coll)]
                 (if (and (pos? n) s)
                   (recur (dec n) (rest s))
                   s)))]
    (lazy-seq (step n coll))))

(defn drop-last
  "Return a lazy sequence of all but the last n (default 1) items in coll"
  {:added "1.0"}
  ([s] (drop-last 1 s))
  ([n s] (map (fn [x _] x) s (drop n s))))

(defn take-last
  "Returns a seq of the last n items in coll. Depending on the type of coll
may be no better than linear time. For vectors, see also subvec."
  {:added "1.1"}
  [n coll]
  (loop [s (seq coll), lead (seq (drop n coll))]
    (if lead
      (recur (next s) (next lead))
      s)))

(defn drop-while
  "Returns a lazy sequence of the items in coll starting from the first item
for which (pred item) returns nil."
  {:added "1.0"}
  [pred coll]
  (let [step (fn [pred coll]
               (let [s (seq coll)]
                 (if (and s (pred (first s)))
                   (recur pred (rest s))
                   s)))]
    (lazy-seq (step pred coll))))

(defn cycle
  "Returns a lazy (infinite!) sequence of repetitions of the items in coll."
  {:added "1.0"}
  [coll] (lazy-seq
          (when-let [s (seq coll)]
              (concat s (cycle s)))))

(defn split-at
  "Returns a vector of [(take n coll) (drop n coll)]"
  {:added "1.0"}
  [n coll]
    [(take n coll) (drop n coll)])

(defn split-with
  "Returns a vector of [(take-while pred coll) (drop-while pred coll)]"
  {:added "1.0"}
  [pred coll]
    [(take-while pred coll) (drop-while pred coll)])

(defn repeat
  "Returns a lazy (infinite!, or length n if supplied) sequence of xs."
  {:added "1.0"}
  ([x] (lazy-seq (cons x (repeat x))))
  ([n x] (take n (repeat x))))

(defn iterate
  "Returns a lazy sequence of x, (f x), (f (f x)) etc. f must be free of
side-effects"
  {:added "1.0"}
  [f x] (cons x (lazy-seq (iterate f (f x)))))

(defn range
  "Returns a lazy seq of nums from start (inclusive) to end (exclusive), by
step, where start defaults to 0, step to 1, and end to infinity."
  {:added "1.0"}
  ([] (range 0 (py/float "inf")))
  ([end] (range 0 end 1))
  ([start end] (range start end 1))
  ([start end step]
   (lazy-seq
    (let [b (chunk-buffer 32)
          comp (if (pos? step) < >)]
      (loop [i start]
        (if (and (< (count b) 32)
                 (comp i end))
          (do
            (chunk-append b i)
            (recur (+ i step)))
          (chunk-cons (chunk b)
                      (when (comp i end)
                        (range i end step)))))))))

(defn merge
  "Returns a map that consists of the rest of the maps conj-ed onto the first.
If a key occurs in more than one map, the mapping from the latter
(left-to-right) will be the mapping in the result."
  {:added "1.0"}
  [& maps]
  (when (some identity maps)
    (reduce1 #(conj (or %1 {}) %2) maps)))

(defn merge-with
  "Returns a map that consists of the rest of the maps conj-ed onto the first.
If a key occurs in more than one map, the mapping(s) from the latter
(left-to-right) will be combined with the mapping in the result by calling (f
val-in-result val-in-latter)."
  {:added "1.0"}
  [f & maps]
  (when (some identity maps)
    (let [merge-entry (fn [m e]
                        (let [k (key e) v (val e)]
                          (if (contains? m k)
                            (assoc m k (f (get m k) v))
                            (assoc m k v))))
          merge2 (fn [m1 m2]
                   (reduce1 merge-entry (or m1 {}) (seq m2)))]
      (reduce1 merge2 maps))))

(defn zipmap
  "Returns a map with the keys mapped to the corresponding vals."
  {:added "1.0"}
  [keys vals]
    (loop [map {}
           ks (seq keys)
           vs (seq vals)]
      (if (and ks vs)
        (recur (assoc map (first ks) (first vs))
               (next ks)
               (next vs))
        map)))

(defn line-seq
  "Returns the lines of text from rdr as a lazy sequence of strings. rdr must
implement .readline"
  {:added "1.0"}
  [rdr]
  (let [line (.readline rdr)]
    (when-not (= line "")
              (cons line (lazy-seq (line-seq rdr))))))

(defn comparator
  "Returns an implementation of java.util.Comparator based upon pred."
  {:added "1.0"
   :static true}
  [pred]
    (fn [x y]
      (cond (pred x y) -1 (pred y x) 1 :else 0)))

(defn wrap-fn-for-compare
  [f]
  (fn [x y]
    (let [ret (f x y)]
      (if (instance? py/bool ret)
        (if ret -1 1)
        ret))))

(defn sort
  "Returns a sorted sequence of the items in coll. If no comparator is
supplied, uses compare. comparator must implement java.util.Comparator."
  {:added "1.0"}
  ([coll]
   (sort compare coll))
  ([comp coll]
   (if (seq coll)
     (seq (py/sorted coll (wrap-fn-for-compare comp)))
     ())))

(defn sort-by
  "Returns a sorted sequence of the items in coll, where the sort order is
determined by comparing (keyfn item). If no comparator is supplied, uses
compare. comparator must implement java.util.Comparator."
  {:added "1.0"}
  ([keyfn coll]
   (sort-by keyfn compare coll))
  ([keyfn comp coll]
   (seq (py/sorted coll (wrap-fn-for-compare comp) keyfn))))

(defn dorun
  "When lazy sequences are produced via functions that have side effects, any
effects other than those needed to produce the first element in the seq do
not occur until the seq is consumed. dorun can be used to force any effects.
Walks through the successive nexts of the seq, does not retain the head and
returns nil."
  {:added "1.0"}
  ([coll]
   (when (seq coll)
     (recur (next coll))))
  ([n coll]
   (when (and (seq coll) (pos? n))
     (recur (dec n) (next coll)))))

(defn doall
  "When lazy sequences are produced via functions that have side effects, any
effects other than those needed to produce the first element in the seq do
not occur until the seq is consumed. doall can be used to force any effects.
Walks through the successive nexts of the seq, retains the head and returns
it, thus causing the entire seq to reside in memory at one time."
  {:added "1.0"}
  ([coll]
   (dorun coll)
   coll)
  ([n coll]
   (dorun n coll)
   coll))

(defmacro doseq
  "Repeatedly executes body (presumably for side-effects) with bindings and
filtering as provided by \"for\". Does not retain the head of the sequence.
Returns nil."
  {:added "1.0"}
  [seq-exprs & body]
  (assert-args
     (vector? seq-exprs) "a vector for its binding"
     (even? (count seq-exprs)) "an even number of forms in binding vector")
  (let [step (fn step [recform exprs]
               (if-not exprs
                 [true `(do ~@body)]
                 (let [k (first exprs)
                       v (second exprs)]
                   (if (keyword? k)
                     (let [steppair (step recform (nnext exprs))
                           needrec (steppair 0)
                           subform (steppair 1)]
                       (cond
                         (= k :let) [needrec `(let ~v ~subform)]
                         (= k :while) [false `(when ~v
                                                ~subform
                                                ~@(when needrec [recform]))]
                         (= k :when) [false `(if ~v
                                               (do
                                                 ~subform
                                                 ~@(when needrec [recform]))
                                               ~recform)]))
                     (let [seq- (gensym "seq_")
                           chunk- (with-meta (gensym "chunk_")
                                             {:tag 'clojure.lang.IChunk})
                           count- (gensym "count_")
                           i- (gensym "i_")
                           recform `(recur (next ~seq-) nil 0 0)
                           steppair (step recform (nnext exprs))
                           needrec (steppair 0)
                           subform (steppair 1)
                           recform-chunk
                             `(recur ~seq- ~chunk- ~count- (inc ~i-))
                           steppair-chunk (step recform-chunk (nnext exprs))
                           subform-chunk (steppair-chunk 1)]
                       [true
                        `(loop [~seq- (seq ~v), ~chunk- nil,
                                ~count- 0, ~i- 0]
                           (if (< ~i- ~count-)
                             (let [~k (.__getitem__ ~chunk- ~i-)]
                               ~subform-chunk
                               ~@(when needrec [recform-chunk]))
                             (when-let [~seq- (seq ~seq-)]
                               (if (chunked-seq? ~seq-)
                                 (let [c# (chunk-first ~seq-)]
                                   (recur (chunk-rest ~seq-) c#
                                          (int (count c#)) (int 0)))
                                 (let [~k (first ~seq-)]
                                   ~subform
                                   ~@(when needrec [recform]))))))])))))]
    (.__getitem__ (step nil (seq seq-exprs)) 1)))

(defmacro dotimes
  "bindings => name n

Repeatedly executes body (presumably for side-effects) with name bound to
integers from 0 through n-1."
  {:added "1.0"}
  [bindings & body]
  (assert-args
    (vector? bindings) "a vector for its binding"
    (= 2 (count bindings)) "exactly 2 forms in binding vector")
  (let [i (first bindings)
        n (second bindings)]
    `(let [n# ~n]
       (loop [~i 0]
         (when (< ~i n#)
           ~@body
           (recur (inc ~i)))))))

(defn nthnext
  "Returns the nth next of coll, (seq coll) when n is 0."
  {:added "1.0"}
  [coll n]
    (loop [n n xs (seq coll)]
      (if (and xs (pos? n))
        (recur (dec n) (next xs))
        xs)))

(defn nthrest
  "Returns the nth rest of coll, coll when n is 0."
  {:added "1.3"}
  [coll n]
    (loop [n n xs coll]
      (if (and (pos? n) (seq xs))
        (recur (dec n) (rest xs))
        xs)))

(defn partition
  "Returns a lazy sequence of lists of n items each, at offsets step apart. If
step is not supplied, defaults to n, i.e. the partitions do not overlap. If a
pad collection is supplied, use its elements as necessary to complete last
partition upto n items. In case there are not enough padding elements, return
a partition with less than n items."
  {:added "1.0"}
  ([n coll]
     (partition n n coll))
  ([n step coll]
     (lazy-seq
       (when-let [s (seq coll)]
         (let [p (doall (take n s))]
           (when (= n (count p))
             (cons p (partition n step (nthrest s step))))))))
  ([n step pad coll]
     (lazy-seq
       (when-let [s (seq coll)]
         (let [p (doall (take n s))]
           (if (= n (count p))
             (cons p (partition n step pad (nthrest s step)))
             (list (take n (concat p pad)))))))))

(defn take-nth
  "Returns a lazy seq of every nth item in coll."
  {:added "1.0"
   :static true}
  [n coll]
    (lazy-seq
     (when-let [s (seq coll)]
       (cons (first s) (take-nth n (drop n s))))))

(defn nth
  ([coll x]
    (if (py/hasattr coll "__getitem__")
      (py.bytecode/BINARY_SUBSCR coll x)
      (first (drop x coll))))
  ([coll x default]
    (if (contains? coll x)
      (nth coll x)
      default)))

(defn subvec
  "Returns a persistent vector of the items in vector from start (inclusive) to
end (exclusive). If end is not supplied, defaults to (count vector). This
operation is O(1) and very fast, as the resulting vector shares structure
with the original and no trimming is done."
  {:added "1.0"}
  ([v start]
   (subvec v start (count v)))
  ([v start end]
   (. clojure.lang.rt (subvec v start end))))

(defn interleave
  "Returns a lazy seq of the first item in each coll, then the second etc."
  {:added "1.0"
   :static true}
  ([c1 c2]
     (lazy-seq
      (let [s1 (seq c1) s2 (seq c2)]
        (when (and s1 s2)
          (cons (first s1) (cons (first s2)
                                 (interleave (rest s1) (rest s2))))))))
  ([c1 c2 & colls]
     (lazy-seq
      (let [ss (map seq (conj colls c2 c1))]
        (when (every? identity ss)
          (concat (map first ss) (apply interleave (map rest ss))))))))

(defn interpose
  "Returns a lazy seq of the elements of coll separated by sep"
  {:added "1.0"
   :static true}
  [sep coll] (drop 1 (interleave (repeat sep) coll)))

(defn max-key
  "Returns the x for which (k x), a number, is greatest."
  {:added "1.0"
   :static true}
  ([k x] x)
  ([k x y] (if (> (k x) (k y)) x y))
  ([k x y & more]
   (reduce1 #(max-key k %1 %2) (max-key k x y) more)))

(defn min-key
  "Returns the x for which (k x), a number, is lesser."
  {:added "1.0"
   :static true}
  ([k x] x)
  ([k x y] (if (< (k x) (k y)) x y))
  ([k x y & more]
   (reduce1 #(min-key k %1 %2) (min-key k x y) more)))

;; redef into with batch support
(defn- into1
  "Returns a new coll consisting of to-coll with all of the items of from-coll
conjoined."
  {:added "1.0"
   :static true}
  [to from]
    (reduce1 conj to from))

;;; sets
(defn set
  "Returns a set of the distinct elements of coll."
  {:added "1.0"
   :static true}
  [coll]
  (if-let [s (seq coll)]
    (clojure.lang.persistenthashset/create s)
    #{}))

(defn hash-set
  "Creates a hash set for the arguments"
  [& args]
  (set args))

;;; multiple forms
(defmacro ..
  "form => fieldName-symbol or (instanceMethodName-symbol args*)

Expands into a member access (.) of the first member on the first argument,
followed by the next member on the result, etc. For instance:

(.. System (getProperties) (get \"os.name\"))

expands to:

(. (. System (getProperties)) (get \"os.name\"))

but is easier to write, read, and understand."
  {:added "1.0"}
  ([x form] `(. ~x ~form))
  ([x form & more] `(.. (. ~x ~form) ~@more)))

(defmacro doto
  "Evaluates x then calls all of the methods and functions with the value of x
supplied at the front of the given arguments. The forms are evaluated in
order. Returns x.

(doto (new java.util.HashMap) (.put \"a\" 1) (.put \"b\" 2))"
  {:added "1.0"}
  [x & forms]
    (let [gx (gensym)]
      `(let [~gx ~x]
         ~@(map (fn [f]
                  (if (seq? f)
                    `(~(first f) ~gx ~@(next f))
                    `(~f ~gx)))
                forms)
         ~gx)))

(defmacro ->
  "Threads the expr through the forms. Inserts x as the second item in the
first form, making a list of it if it is not a list already. If there are
more forms, inserts the first form as the second item in second form, etc."
  {:added "1.0"}
  ([x] x)
  ([x form] (if (seq? form)
              (with-meta `(~(first form) ~x ~@(next form)) (meta form))
              (list form x)))
  ([x form & more] `(-> (-> ~x ~form) ~@more)))

(defmacro ->>
  "Threads the expr through the forms. Inserts x as the last item in the first
form, making a list of it if it is not a list already. If there are more
forms, inserts the first form as the last item in second form, etc."
  {:added "1.1"}
  ([x form] (if (seq? form)
              (with-meta `(~(first form) ~@(next form) ~x) (meta form))
              (list form x)))
  ([x form & more] `(->> (->> ~x ~form) ~@more)))

;;; redefine let, fn and loop with destructuring
(defn destructure [bindings]
  (let [bents (partition 2 bindings)
        pb (fn pb [bvec b v]
               (let [pvec
                     (fn [bvec b val]
                       (let [gvec (gensym "vec__")]
                         (loop [ret (-> bvec (conj gvec) (conj val))
                                n 0
                                bs b
                                seen-rest? false]
                           (if (seq bs)
                             (let [firstb (first bs)]
                               (cond
                                (= firstb '&) (recur (pb ret (second bs) (list `nthnext gvec n))
                                                     n
                                                     (nnext bs)
                                                     true)
                                (= firstb :as) (pb ret (second bs) gvec)
                                :else (if seen-rest?
                                        (throw (py/Exception "Unsupported binding form, only :as can follow & parameter"))
                                        (recur (pb ret firstb (list `nth gvec n nil))
                                               (inc n)
                                               (next bs)
                                               seen-rest?))))
                             ret))))
                     pmap
                     (fn [bvec b v]
                       (let [gmap (or (:as b) (gensym "map__"))
                             defaults (:or b)]
                         (loop [ret (-> bvec (conj gmap) (conj v)
                                        (conj gmap) (conj `(if (seq? ~gmap) (apply hash-map ~gmap) ~gmap)))
                                bes (reduce1
                                     (fn [bes entry]
                                       (reduce1 #(assoc %1 %2 ((val entry) %2))
                                               (dissoc bes (key entry))
                                               ((key entry) bes)))
                                     (dissoc b :as :or)
                                     {:keys #(keyword (str %)), :strs str, :syms #(list `quote %)})]
                           (if (seq bes)
                             (let [bb (key (first bes))
                                   bk (val (first bes))
                                   has-default (contains? defaults bb)]
                               (recur (pb ret bb (if has-default
                                                   (list `get gmap bk (defaults bb))
                                                   (list `get gmap bk)))
                                      (next bes)))
                             ret))))]
                 (cond
                  (symbol? b) (-> bvec (conj b) (conj v))
                  (vector? b) (pvec bvec b v)
                  (map? b) (pmap bvec b v)
                  :else (throw (py/Exception (str "Unsupported binding form: " b))))))
        process-entry (fn [bvec b] (pb bvec (first b) (second b)))]
    (if (every? symbol? (map first bents))
      bindings
      (reduce1 process-entry [] bents))))

(defmacro let
  "binding => binding-form init-expr

Evaluates the exprs in a lexical context in which the symbols in
the binding-forms are bound to their respective init-exprs or parts
therein."
  {:added "1.0", :special-form true, :forms '[(let [bindings*] exprs*)]}
  [bindings & body]
  (assert-args
     (vector? bindings) "a vector for its binding"
     (even? (count bindings)) "an even number of forms in binding vector")
  `(let* ~(destructure bindings) ~@body))

(defn- maybe-destructured
  [params body]
  (if (every? symbol? params)
    (cons params body)
    (loop [params params
           new-params []
           lets []]
      (if params
        (if (symbol? (first params))
          (recur (next params) (conj new-params (first params)) lets)
          (let [gparam (gensym "p__")]
            (recur (next params) (conj new-params gparam)
                   (-> lets (conj (first params)) (conj gparam)))))
        `(~new-params
          (let ~lets
            ~@body))))))

;redefine fn with destructuring and pre/post conditions
(defmacro fn
  "params => positional-params* , or positional-params* & next-param
positional-param => binding-form
next-param => binding-form
name => symbol

Defines a function"
  {:added "1.0", :special-form true,
   :forms '[(fn name? [params* ] exprs*) (fn name? ([params* ] exprs*)+)]}
  [& sigs]
    (let [name (if (symbol? (first sigs)) (first sigs) nil)
          sigs (if name (next sigs) sigs)
          sigs (if (vector? (first sigs)) (list sigs) sigs)
          psig (fn* [sig]
                 (let [[params & body] sig
                       conds (when (and (next body) (map? (first body)))
                                           (first body))
                       body (if conds (next body) body)
                       conds (or conds (meta params))
                       pre (:pre conds)
                       post (:post conds)
                       body (if post
                              `((let [~'% ~(if (< 1 (count body))
                                            `(do ~@body)
                                            (first body))]
                                 ~@(map (fn* [c] `(assert ~c)) post)
                                 ~'%))
                              body)
                       body (if pre
                              (concat (map (fn* [c] `(assert ~c)) pre)
                                      body)
                              body)]
                   (maybe-destructured params body)))
          new-sigs (map psig sigs)]
        (if name
          (list* 'fn* name new-sigs)
          (cons 'fn* new-sigs))))

(defmacro loop
  "Evaluates the exprs in a lexical context in which the symbols in
the binding-forms are bound to their respective init-exprs or parts
therein. Acts as a recur target."
  {:added "1.0", :special-form true, :forms '[(loop [bindings*] exprs*)]}
  [bindings & body]
    (assert-args
      (vector? bindings) "a vector for its binding"
      (even? (count bindings)) "an even number of forms in binding vector")
    (let [db (destructure bindings)]
      (if (= db bindings)
        `(loop* ~bindings ~@body)
        (let [vs (take-nth 2 (drop 1 bindings))
              bs (take-nth 2 bindings)
              gs (map (fn [b] (if (symbol? b) b (gensym))) bs)
              bfs (reduce1 (fn [ret [b v g]]
                            (if (symbol? b)
                              (conj ret g v)
                              (conj ret g v b g)))
                          [] (map vector bs vs gs))]
          `(let ~bfs
             (loop* ~(vec (interleave gs gs))
               (let ~(vec (interleave bs gs))
                 ~@body)))))))

;;; more macros with destructuring
(defmacro when-first
  "bindings => x xs

Same as (when (seq xs) (let [x (first xs)] body))"
  {:added "1.0"}
  [bindings & body]
  (assert-args
     (vector? bindings) "a vector for its binding"
     (= 2 (count bindings)) "exactly 2 forms in binding vector")
  (let [[x xs] bindings]
    `(when (seq ~xs)
       (let [~x (first ~xs)]
         ~@body))))

(defmacro for
  "List comprehension. Takes a vector of one or more
binding-form/collection-expr pairs, each followed by zero or more modifiers,
and yields a lazy sequence of evaluations of expr. Collections are iterated
in a nested fashion, rightmost fastest, and nested coll-exprs can refer to
bindings created in prior binding-forms. Supported modifiers are: :let
[binding-form expr ...], :while test, :when test.

(take 100 (for [x (range 100000000) y (range 1000000) :while (< y x)] [x y]))"
  {:added "1.0"}
  [seq-exprs body-expr]
  (assert-args
     (vector? seq-exprs) "a vector for its binding"
     (even? (count seq-exprs)) "an even number of forms in binding vector")
  (let [to-groups (fn [seq-exprs]
                    (reduce1 (fn [groups [k v]]
                              (if (keyword? k)
                                (conj (pop groups) (conj (peek groups) [k v]))
                                (conj groups [k v])))
                            [] (partition 2 seq-exprs)))
        err (fn [& msg] (throw (IllegalArgumentException. ^String (apply str msg))))
        emit-bind (fn emit-bind [[[bind expr & mod-pairs]
                                  & [[_ next-expr] :as next-groups]]]
                    (let [giter (gensym "iter__")
                          gxs (gensym "s__")
                          do-mod (fn do-mod [[[k v :as pair] & etc]]
                                   (cond
                                     (= k :let) `(let ~v ~(do-mod etc))
                                     (= k :while) `(when ~v ~(do-mod etc))
                                     (= k :when) `(if ~v
                                                    ~(do-mod etc)
                                                    (recur (rest ~gxs)))
                                     (keyword? k) (err "Invalid 'for' keyword " k)
                                     next-groups
                                      `(let [iterys# ~(emit-bind next-groups)
                                             fs# (seq (iterys# ~next-expr))]
                                         (if fs#
                                           (concat fs# (~giter (rest ~gxs)))
                                           (recur (rest ~gxs))))
                                     :else `(cons ~body-expr
                                                  (~giter (rest ~gxs)))))]
                      (if next-groups
                        #_"not the inner-most loop"
                        `(fn ~giter [~gxs]
                           (lazy-seq
                             (loop [~gxs ~gxs]
                               (when-first [~bind ~gxs]
                                 ~(do-mod mod-pairs)))))
                        #_"inner-most loop"
                        (let [gi (gensym "i__")
                              gb (gensym "b__")
                              do-cmod (fn do-cmod [[[k v :as pair] & etc]]
                                        (cond
                                          (= k :let) `(let ~v ~(do-cmod etc))
                                          (= k :while) `(when ~v ~(do-cmod etc))
                                          (= k :when) `(if ~v
                                                         ~(do-cmod etc)
                                                         (recur
                                                           (inc ~gi)))
                                          (keyword? k)
                                            (err "Invalid 'for' keyword " k)
                                          :else
                                            `(do (chunk-append ~gb ~body-expr)
                                                 (recur (inc ~gi)))))]
                          `(fn ~giter [~gxs]
                             (lazy-seq
                               (loop [~gxs ~gxs]
                                 (when-let [~gxs (seq ~gxs)]
                                   (if (chunked-seq? ~gxs)
                                     (let [c# (chunk-first ~gxs)
                                           size# (int (count c#))
                                           ~gb (chunk-buffer size#)]
                                       (if (loop [~gi (int 0)]
                                             (if (< ~gi size#)
                                               (let [~bind (py.bytecode/BINARY_SUBSCR c# ~gi)]
                                                 ~(do-cmod mod-pairs))
                                               true))
                                         (chunk-cons
                                           (chunk ~gb)
                                           (~giter (chunk-rest ~gxs)))
                                         (chunk-cons (chunk ~gb) nil)))
                                     (let [~bind (first ~gxs)]
                                       ~(do-mod mod-pairs)))))))))))]
    `(let [iter# ~(emit-bind (to-groups seq-exprs))]
        (iter# ~(second seq-exprs)))))

;;; vars et al.
(defn deref
  "Also reader macro: @ref/@agent/@var/@atom/@delay/@future/@promise. Within a
transaction, returns the in-transaction-value of ref, else returns the
most-recently-committed value of ref. When applied to a var, agent or atom,
returns its current state. When applied to a delay, forces it if not already
forced. When applied to a future, will block if computation not complete.
When applied to a promise, will block until a value is delivered. The
variant taking a timeout can be used for blocking references (futures and
promises), and will return timeout-val if the timeout (in milliseconds) is
reached before a value is available. See also - realized?."
  {:added "1.0"
   :static true}
  ([ref] (.deref ref))
  ([ref timeout-ms timeout-val] (.deref ref timeout-ms timeout-val)))

(defmacro binding
  "binding => var-symbol init-expr

Creates new bindings for the (already-existing) vars, with the
supplied initial values, executes the exprs in an implicit do, then
re-establishes the bindings that existed before. The new bindings
are made in parallel (unlike let); all init-exprs are evaluated
before the vars are bound to their new values."
  {:added "1.0"}
  [bindings & body]
  (assert-args binding
    (vector? bindings) "a vector for its binding"
    (even? (count bindings)) "an even number of forms in binding vector")
  (let [var-ize (fn [var-vals]
                  (loop [ret [] vvs (seq var-vals)]
                    (if vvs
                      (recur (conj (conj ret `(var ~(first vvs))) (second vvs))
                             (next (next vvs)))
                      (seq ret))))]
   `(let []
       (clojure.lang.var/pushThreadBindings (hash-map ~@(var-ize bindings)))
       (~'try
         (~'do ~@body)
         (~'finally
           (clojure.lang.var/popThreadBindings))))))

(defmacro var
  "The symbol must resolve to a var, and the Var object itself (not its value)
is returned. The reader macro #'x expands to (var x)."
  [symbol]
  `(clojure.lang.namespace/findItem (clojure.lang.namespace/findNS ~'__name__)
                                    '~symbol))

(defn var?
  "Return true if x is a Var"
  {:static true}
  [x] (instance? clojure.lang.var/Var x))

(defn alter-var-root
  "Atomically alters the root binding of var v by applying f to its current
value plus any args"
  {:added "1.0"
   :static true}
  [v f & args] (.alterRoot v f args))

(defn bound?
  "Returns true if all of the vars provided as arguments have any bound value,
root or thread-local. Implies that deref'ing the provided vars will succeed.
Returns true if no vars are provided."
  {:added "1.2"
   :static true}
  [& vars]
  (every? #(.isBound %) vars))

(defn thread-bound?
  "Returns true if all of the vars provided as arguments have thread-local
bindings. Implies that set!'ing the provided vars will succeed. Returns true
if no vars are provided."
  {:added "1.2"
   :static true}
  [& vars]
  (every? #(.getThreadBinding %) vars))

;;; ns-related
(defmacro defonce
  "Defs name to have the root value of the expr iff the named var has no root
value, else expr is unevaluated."
  {:added "1.0"}
  [name expr]
  `(let [v# (def ~name)]
     (when-not (.hasRoot v#)
       (def ~name ~expr))))

(defonce ^:dynamic
  ^{:private true
    :doc "True while a verbose load is pending."}
  *loading-verbosely* false)

(def
  ^{:doc "Returns the namespace String of a symbol or keyword, or nil if not present."
   :added "1.0"
   :static true}
  namespace
  clojure.lang.rt/namespace)

(defn find-ns
  "Returns the namespace named by the symbol or nil if it doesn't exist."
  {:added "1.0"}
  [sym] (clojure.lang.namespace/findNS sym))

(defn create-ns
  "Create a new namespace named by the symbol if one doesn't already
exist, returns it or the already-existing namespace of the same
name."
  {:added "1.0"}
  [sym] (clojure.lang.namespace/Namespace sym))

(defn remove-ns
  "Removes the namespace named by the symbol. Use with caution.
Cannot be used to remove the clojure namespace."
  {:added "1.0"}
  [sym] (clojure.lang.namespace/remove sym))

(defn all-ns
  "Returns a sequence of all namespaces."
  {:added "1.0"
   :static true}
  [] (seq (py/tuple (.itervalues sys/modules))))

(defn the-ns
  "If passed a namespace, returns it. Else, when passed a symbol, returns the
namespace named by it, throwing an exception if not found."
  {:added "1.0"}
  [x]
  (if (instance? types/ModuleType x)
    x
    (or (find-ns x) (throw (py/Exception (str "No namespace: " x " found"))))))

(defn ns-name
  "Returns the name of the namespace, a symbol."
  {:added "1.0"
   :static true}
  [ns] (symbol (.-__name__ (the-ns ns))))

(defn ns-map
  "Returns a map of all the mappings for the namespace."
  {:added "1.0"
   :static true}
  [ns]
  (apply hash-map (mapcat (fn [[k v]] [(symbol k) v])
                          (clojure.lang.rt/map (.-__dict__ (the-ns ns))))))

(defn- ^{:static true}
  filter-key [keyfn pred amap]
    (loop [ret {} es (seq amap)]
      (if es
        (if (pred (keyfn (first es)))
          (recur (assoc ret (key (first es)) (val (first es))) (next es))
          (recur ret (next es)))
        ret)))

(defn ns-publics
  "Returns a map of the public intern mappings for the namespace."
  {:added "1.0"
   :static true}
  [ns]
  (let [ns (the-ns ns)]
    (filter-key val (fn [v] (and (var? v) (= ns (.-ns v)) (.isPublic v)))
                (ns-map ns))))

(defn ns-imports
  "Returns a map of the import mappings for the namespace, i.e. non-var names
that would be imported by 'import * from module.'"
  {:added "1.0"
   :static true}
  [ns]
  (filter-key
    identity
    (fn [[k v]]
      (and (not (var? v))
           (if (py/hasattr ns "__all__")
             (.__contains__ (.-__all__ ns) (name k)) ; use Python's "in"
             (not (.startswith (name k) "_")))))
    (ns-map ns)))

(defn ns-interns
  "Returns a map of the intern mappings for the namespace."
  {:added "1.0"
   :static true}
  [ns]
  (let [ns (the-ns ns)]
    (filter-key val (fn [v] (and (var? v) (= ns (.-ns v)))) (ns-map ns))))

(defn intern
  "Finds or creates a var named by the symbol name in the namespace ns (which
can be a symbol or a namespace), setting its root binding to val if supplied.
The namespace must exist. The var will adopt any metadata from the name
symbol. Returns the var."
  ([ns name] (clojure.lang.namespace/intern (the-ns ns) name))
  ([ns name val] (.bindRoot (intern ns name) val)))

(defn- map-one
  "Adds the var/object to the given namespace with the given name."
  [ns nm v] (py/setattr ns (name nm) v))

(defn refer
  "refers to all public vars of ns, subject to filters.
filters can include at most one each of:

:exclude list-of-symbols
:only list-of-symbols (non-existent symbols will be ignored)
:rename map-of-fromsymbol-tosymbol

For each public interned var in the namespace named by the symbol, adds a
mapping from the name of the var to the var to the current namespace. Throws
an exception if name is already mapped to something else in the current
namespace. Filters can be used to select a subset, via inclusion or
exclusion, or to provide a mapping to a symbol different from the var's name,
in order to prevent clashes. Use :use in the ns macro in preference to
calling this directly."
  {:added "1.0"}
  [ns-sym & filters]
  (let [ns (or (find-ns ns-sym) (throw (py/Exception (str "No namespace: " ns-sym))))
        fs (apply hash-map filters)
        nspublics (ns-publics ns)
        rename (or (:rename fs) {})
        exclude (set (:exclude fs))
        to-do (if (:only fs)
                (filter (set (:only fs)) (keys nspublics))
                (keys nspublics))]
    (doseq [sym to-do]
      (when-not (exclude sym)
        (if-let [v (nspublics sym)]
          (map-one *ns* (or (rename sym) sym) v)
          (throw (py/Exception
                   (if (get (ns-interns ns) sym)
                     (str sym " is not public")
                     (str sym " does not exist")))))))))

(defn import
  "imports to all public names of ns (i.e., non-var names that would be
imported by 'import * from ns'), subject to filters.
filters can include at most one each of:

:exclude list-of-symbols
:only list-of-symbols (non-existent symbols will be ignored)
:rename map-of-fromsymbol-tosymbol

For each public name in the namespace named by the symbol, adds a mapping
from the name of the object to the object to the current namespace. Throws
an exception if name is already mapped to something else in the current
namespace. Filters can be used to select a subset, via inclusion or
exclusion, or to provide a mapping to a symbol different from the object's
name, in order to prevent clashes. Use :use in the ns macro in preference to
calling this directly."
  {:added "1.0"}
  [ns-sym & filters]
  (let [ns (or (find-ns ns-sym) (throw (py/Exception (str "No namespace: " ns-sym))))
        fs (apply hash-map filters)
        nsimports (ns-imports ns)
        rename (or (:rename fs) {})
        exclude (set (:exclude fs))
        to-do (if (:only fs)
                (filter (set (:only fs)) (keys nsimports))
                (keys nsimports))]
    (doseq [sym to-do]
      (when-not (exclude sym)
        (if (contains? nsimports sym)
          (map-one *ns* (or (rename sym) sym) (nsimports sym))
          (throw (py/Exception
                   (if (get (ns-map ns) sym)
                     (str sym " is not public")
                     (str sym " does not exist")))))))))

(defmacro refer-clojure
  "Same as (refer 'clojure.core <filters>)."
  {:added "1.0"}
  [& filters]
  `(clojure.core/refer '~'clojure.core ~@filters))

(defn ns-refers
  "Returns a map of the refer mappings for the namespace."
  {:added "1.0"
   :static true}
  [ns]
  (let [ns (the-ns ns)]
    (filter-key val (fn [v] (and (instance? clojure.lang.var/Var v)
                                 (not= ns (.-ns v))))
                (ns-map ns))))

(defn ns-aliases
  "Returns a map of the aliases for the namespace."
  {:added "1.0"
   :static true}
  [ns] (py/getattr (the-ns ns) "__aliases__" {}))

(defn alias
  "Add an alias in the current namespace to another namespace. Arguments are
two symbols: the alias to be used, and the symbolic name of the target
namespace. Use :as in the ns macro in preference to calling this directly."
  {:added "1.0"
   :static true}
  [alias namespace-sym]
  (py/setattr *ns*
              "__aliases__"
              (assoc (ns-aliases *ns*) alias (the-ns namespace-sym))))

(defn ns-unalias
  "Removes the alias for the symbol from the namespace."
  {:added "1.0"
   :static true}
  [ns sym]
  (let [to-ns (the-ns ns)]
    (py/setattr to-ns "__aliases__" (dissoc (ns-aliases to-ns) sym))))

(defn ns-resolve
  "Returns the var or Class to which a symbol will be resolved in the namespace
(unless found in the environement), else nil. Note that if the symbol is
fully qualified, the var/Class to which it resolves need not be present in
the namespace."
  {:added "1.0"
   :static true}
  ([ns sym] (clojure.lang.namespace/findItem (the-ns ns) sym)))

(defn resolve
  "same as (ns-resolve *ns* symbol) or (ns-resolve *ns* &env symbol)."
  {:added "1.0"}
  ([sym] (ns-resolve *ns* sym)))

(defn format
  "Formats a string."
  {:added "1.0"
   :static true}
  [fmt & args]
  (py.bytecode/BINARY_MODULO fmt (if (nil? args) [] args)))

(defn throw-if
  "Throws an exception with a message if pred is true."
  [pred fmt & args]
  (when pred
    (let [message (apply format fmt args)
          exception (py/Exception. message)]
      (throw exception))))

(defn- libspec?
  "Returns true if x is a libspec."
  [x]
  (or (symbol? x)
      (and (vector? x)
           (or
            (nil? (second x))
            (keyword? (second x))))))

(defn- prependss
  "Prepends a symbol or a seq to coll."
  [x coll]
  (if (symbol? x)
    (cons x coll)
    (concat x coll)))

(defn- load-one
  "Loads a lib given its name. If reload, force a reload if the lib is already
loaded."
  [lib reload]
  (if (and reload (find-ns lib))
    (do (when *loading-verbosely*
          (py/print (str "py/reload " lib)))
        (py/reload (find-ns lib)))
    (do (when *loading-verbosely*
          (py/print (str "py/import " lib)))
        (try
          (py/__import__ (name lib))
          (catch NoNamespaceException e nil)))))

(defn- load-lib
  "Loads a lib with options."
  [prefix lib & options]
  (throw-if (and prefix (pos? (.find (name lib) \.)))
            "lib names inside prefix lists must not contain periods")
  (let [lib (if prefix (symbol (str prefix \. lib)) lib)
        opts (apply hash-map options)
        {:keys [as reload use verbose]} opts
        need-ns (or as use)
        filter-opts (select-keys opts '(:exclude :import :only :rename :refer))]
    (binding [*loading-verbosely* (or *loading-verbosely* verbose)]
      (load-one lib reload)
      (throw-if (and need-ns (not (find-ns lib)))
                "namespace %s not found after loading '%s'" lib lib)
      (when (and need-ns *loading-verbosely*)
        (py/print (str "(clojure.core/in-ns '" (ns-name *ns*) ")")))
      (when as
        (when *loading-verbosely*
          (py/print (str "(clojure.core/alias '" as " '" lib ")")))
        (alias as lib))
      (when (or use (:refer filter-opts))
        (when *loading-verbosely*
          (kwapply py/print {"end" ""} (str "(clojure.core/refer '" lib))
          (doseq [opt filter-opts]
            (kwapply py/print {"end" ""} (str " " (key opt) " '" (val opt))))
          (py/print ")"))
        (apply refer lib (mapcat seq filter-opts)))
      (when (or use (:import filter-opts))
        (when *loading-verbosely*
          (kwapply py/print {"end" ""} (str "(clojure.core/import '" lib))
          (doseq [opt filter-opts]
            (kwapply py/print {"end" ""} (str " " (key opt) " '" (val opt))))
          (py/print ")"))
        (apply import lib (mapcat seq filter-opts))))))

(defn- load-libs
  "Loads libs, interpreting libspecs, prefix lists, and flags for forwarding to
load-lib."
  [& args]
  (let [flags (filter keyword? args)
        opts (interleave flags (repeat true))
        args (filter (complement keyword?) args)]
    ; check for unsupported options
    (let [supported #{:as :import :reload :reload-all :require :use :verbose :refer}
          unsupported (seq (remove supported flags))]
      (throw-if unsupported
                (apply str "Unsupported option(s) supplied: "
                       (interpose \, unsupported))))
    ; check a load target was specified
    (throw-if (not (seq args)) "Nothing specified to load")
    (doseq [arg args]
      (if (libspec? arg)
        (apply load-lib nil (prependss arg opts))
        (let [[prefix & args] arg]
          (throw-if (nil? prefix) "prefix cannot be nil")
          (doseq [arg args]
            (apply load-lib prefix (prependss arg opts))))))))

(defn require
  "Loads libs, skipping any that are already loaded. Each argument is either a
libspec that identifies a lib, a prefix list that identifies multiple libs
whose names share a common prefix, or a flag that modifies how all the
identified libs are loaded. Use :require in the ns macro in preference to
calling this directly.

Libs

A 'lib' is a named set of resources in sys.path whose contents define a
library of Clojure code. Lib names are symbols and each lib is associated
with a Clojure namespace and a Python module/package that share its name. A
lib's name is resolved into a Python absolute or relative import. All
definitions a lib makes should be in its associated namespace.

Libspecs

A libspec is a lib name or a vector containing a lib name followed by options
expressed as sequential keywords and arguments.

Recognized options:
:as takes a symbol as its argument and makes that symbol an alias to the
lib's namespace in the current namespace.
:refer takes a list of var symbols to refer from the namespace.
:import takes a list of Python names to refer from the namespace.

Prefix Lists

It's common for Clojure code to depend on several libs whose names have the
same prefix. When specifying libs, prefix lists can be used to reduce
repetition. A prefix list contains the shared prefix followed by libspecs
with the shared prefix removed from the lib names. After removing the prefix,
the names that remain must not contain any periods.

Flags

A flag is a keyword.
Recognized flags: :reload, :reload-all, :verbose
:reload forces loading of all the identified libs even if they are already
loaded.
:verbose triggers printing information about each operation.

Example:

The following would load the libraries clojure.zip and clojure.set
abbreviated as 's'.

(require '(clojure zip [set :as s]))"
  {:added "1.0"}
  [& args] (apply load-libs :require args))

(defn use
  "Like 'require, but also refers to each lib's namespace using
clojure.core/refer and clojure.core/import. Use :use in the ns macro in
preference to calling this directly.

'use accepts additional options in libspecs: :exclude, :only, :rename.
The arguments and semantics for :exclude, :only, and :rename are the same
as those documented for clojure.core/refer and clojure.core/import."
  {:added "1.0"}
  [& args] (apply load-libs :require :use :import args))

;; FIXME load is not supported yet
(defmacro ns
  "Sets *ns* to the namespace named by name (unevaluated), creating it if
needed. references can be zero or more of: (:refer-clojure ...) (:require
...) (:use ...) (:import ...) (:load ...) with the syntax of
refer-clojure/require/use/import/load respectively, except the arguments are
unevaluated and need not be quoted. If :refer-clojure is not used, a default
(refer-clojure) is used. Use of ns is preferred to individual calls to
in-ns/require/use/import:

(ns foo.bar
(:refer-clojure :exclude [ancestors printf])
(:require (clojure.contrib sql sql.tests))
(:use (my.lib this that))
(:import (java.util Date Timer Random)
(java.sql Connection Statement)))"
  {:arglists '([name docstring? attr-map? references*])
   :added "1.0"}
  [name & references]
  (let [process-reference
        (fn [[kname & args]]
          `(~(symbol "clojure.core" (clojure.core/name kname))
             ~@(map #(list 'quote %) args)))
        docstring (when (string? (first references)) (first references))
        references (if docstring (next references) references)
        name (if docstring
               (vary-meta name assoc :doc docstring)
               name)
        metadata (when (map? (first references)) (first references))
        references (if metadata (next references) references)
        name (if metadata
               (vary-meta name merge metadata)
               name)
        references (remove #(= :gen-class (first %)) references)]
    `(do
       (~'in-ns ~name)
       ~(when (and (not= name 'clojure.core)
                   (not-any? #(= :refer-clojure (first %)) references))
          `(refer-clojure))
       ~@(map process-reference references))))

(def reduce reduce1)

; FIXME: Am I polluting the namespace by requiring those?!
(require 'numbers)
(defn number?
  "Returns true if n is a number. Works for int, long, Decimal, Fractions and
anything else that implements the Number Abstract Base Class"
  [n] (instance? numbers/Number n))

;; ======================================================================
;;; Printing
;; newline, flush, pr, and prn, print, println.
;; It's in place for live IPrintable testing.
;;
;; None instead of nil is printed after each call because the repl is
;; printing the raw Python result of pr, print, etc.
;;
;; None of this is final.
;; ======================================================================

;; Need binding
;; (def ^:dynamic *flush-on-newline* false)
;; (def ^:dynamic *print-dup* false)
;; (def ^:dynamic *print-meta* false)
;; (def ^:dynamic *print-readably* true)
(def ^:dynamic *out* sys/stdout)
(def ^:dynamic *err* sys/stderr)
(def ^:dynamic *in* sys/stdin)

(defn newline [] (.write *out* "\n") nil)
(defn flush [] (.flush *out*) nil)

(defn pr
  "readable, no newline"
  ([] nil)
  ([x]
     (clojure.protocols/writeAsReplString x *out*))
  ([x & more]
     (pr x)
     (.write *out* " ")
     (if-let [nmore (next more)]
       (recur (first more) nmore)
       (apply pr more))))

(defn prn
  "readable, newline follows"
  [& more]
  (apply pr more)
  (newline))

;; XXX: for testing only
(defn print-pr
  ([] nil)
  ([x]
     (clojure.protocols/writeAsString x *out*))
  ([x & more]
     (print-pr x)
     (.write *out* " ")
     (if-let [nmore (next more)]
       (recur (first more) nmore)
       (apply print-pr more))))

(defn print
  "unreadable-ish, no newline"
  [& more]
  (apply print-pr more))

;; XXX: for testing only
(defn print-prn
  [& more]
  (apply print-pr more)
  (newline))

(defn debug [x]
  (py/print x)
  x)

(defn println
  "Pass through one string to Python print. This is just for debugging,
and is not a proper final solution."
  {}
  [x] (py/print x))

(defn println
  "unreadable-ishishly, newline follows"
  [& more]
  (apply print-prn more))

;;; interactivity
(require 'clojure.lang.lispreader)
(defn read-string
  "Reads one object from the string s"
  {:added "1.0"}
  [s] (clojure.lang.lispreader/readString s))

(defn eval
  "Evaluates the form data structure (not text!) and returns the result."
  {:added "1.0"
   :static true}
  [form] (clojure.lang.compiler/evalForm form *ns*))

(defmacro doc
  [itm]
  `(let [itm# (clojure.core/var ~itm)]
     (py/print (or (:doc (meta itm#))
                   (py/getattr itm# "__doc__" "")))))

(defmacro comment
  "Ignores body, yields nil"
  {:added "1.0"}
  [& body])

;(import '(time time))
;(def pytime time)

;(defmacro time
; "Evaluates expr and prints the time it took. Returns the value of
; expr."
; {:added "1.0"}
; [expr]
; `(let [start# (pytime)
; ret# ~expr]
; (py/print (str "Elapsed time: " (* (- (pytime) start#) 1000) " msecs"))
; ret#))

(def ^:dynamic
 ^{:doc "Bound in a repl thread to the most recent value printed."
   :added "1.0"}
 *1)

(def ^:dynamic
 ^{:doc "Bound in a repl thread to the second most recent value printed."
   :added "1.0"}
 *2)

(def ^:dynamic
 ^{:doc "Bound in a repl thread to the third most recent value printed."
   :added "1.0"}
 *3)

;;; exceptions
(defn assert
  "Throws an error if val is not true"
  [val]
  (when-not val
    (throw (py/AssertionError))))

(def Exception py/Exception)

;;; more binding forms
(defmacro letfn
  "fnspec ==> (fname [params*] exprs) or (fname ([params*] exprs)+)

Takes a vector of function specs and a body, and generates a set of bindings
of functions to their names. All of the names are available in all of the
definitions of the functions, as well as the body."
  {:added "1.0", :forms '[(letfn [fnspecs*] exprs*)],
   :special-form true, :url nil}
  [fnspecs & body]
  `(let ~(vec (interleave (map first fnspecs)
                          (map #(cons `fn %) fnspecs)))
      ~@body))

(defn when-attr
  "If attr exists on obj, it calls (apply (py/getattr obj attr) args) otherwise
nil is returned"
  [obj attr & args]
  (apply (py/getattr obj attr (constantly nil)) args))

(defmacro with-open
  "bindings => [name init ...]
First, with-open calls (.__enter__ name) on all bindings if the attribute
exists. Next it evaluates body in a try expression with names bound to the
values of the inits, and a finally clause that calls (.__exit__ name) and/or
(.close name) on each name in reverse order."
  {:added "1.0"}
  [bindings & body]
  (assert-args with-open
    (vector? bindings) "a vector for its binding"
    (even? (count bindings)) "an even number of forms in binding vector")
  (cond
    (= (count bindings) 0) `(do ~@body)
    (symbol? (bindings 0)) `(let ~(subvec bindings 0 2)
                              (when-attr ~(bindings 0) "__enter__")
                              (~'try
                                (with-open ~(subvec bindings 2) ~@body)
                                (~'finally
                                  (do
                                   (when-attr ~(bindings 0) "__exit__")
                                   (when-attr ~(bindings 0) "close")))))
    :else (throw (IllegalArgumentException.
                    "with-open only allows Symbols in bindings"))))

;;; protocols
(defn extends?
  {:static true}
  [protocol atype]
  (let [p (clojure.lang.protocol/getExactProtocol protocol)]
    (if p
      (.isExtendedBy p atype))
      (py/issubclass protocol atype)))

(defn satisfies?
  "Returns true if x satisfies the protocol"
  {:added "1.2"}
  [protocol x]
  (extends? (class x) protocol))

;;; inheritance hierarchy
(defn bases
  "Returns the immediate superclass and direct interfaces of c, if any"
  {:added "1.0"
   :static true}
  [^Class c]
  (when c
    (seq (.-__bases__ c))))

(require 'inspect)
(defn supers
  "Returns the immediate and indirect superclasses and interfaces of c, if any"
  {:added "1.0"
   :static true}
  [class]
  (next (seq (inspect/getmro class))))

(defn class?
  "Returns true if cls is an instance of ClassType"
  [cls]
  (py/isinstance cls types/TypeType))

(defn make-hierarchy
  "Creates a hierarchy object for use with derive, isa? etc."
  {:added "1.0"
   :static true}
  [] {:parents {} :descendants {} :ancestors {}})

(def ^{:private true}
  global-hierarchy (make-hierarchy))

(defn isa?
  "Returns true if (= child parent), or child is directly or indirectly derived
from parent, either via a Java type inheritance relationship or a
relationship established via derive. h must be a hierarchy obtained from
make-hierarchy, if not supplied defaults to the global hierarchy"
  {:added "1.0"}
  ([child parent] (isa? global-hierarchy child parent))
  ([h child parent]
   (or (= child parent)
       (and (class? parent) (class? child)
            (py/issubclass child parent))
       (contains? ((:ancestors h) child) parent)
       (and (class? child) (some #(contains? ((:ancestors h) %) parent) (supers child)))
       (and (vector? parent) (vector? child)
            (= (count parent) (count child))
            (loop [ret true i 0]
              (if (or (not ret) (= i (count parent)))
                ret
                (recur (isa? h (child i) (parent i)) (inc i))))))))

(defn parents
  "Returns the immediate parents of tag, either via a Java type inheritance
relationship or a relationship established via derive. h must be a hierarchy
obtained from make-hierarchy, if not supplied defaults to the global
hierarchy"
  {:added "1.0"}
  ([tag] (parents global-hierarchy tag))
  ([h tag] (not-empty
            (let [tp (get (:parents h) tag)]
              (if (class? tag)
                (if tp
                  (seq (.union (py/set (bases tag)) (py/set tp)))
                  (bases tag))
                tp)))))

(defn ancestors
  "Returns the immediate and indirect parents of tag, either via a Java type
inheritance relationship or a relationship established via derive. h must be
a hierarchy obtained from make-hierarchy, if not supplied defaults to the
global hierarchy"
  {:added "1.0"}
  ([tag] (ancestors global-hierarchy tag))
  ([h tag] (not-empty
            (let [ta (get (:ancestors h) tag)]
              (if (class? tag)
                (let [superclasses (set (supers tag))]
                  (reduce1 into1 superclasses
                    (cons ta
                          (map #(get (:ancestors h) %) superclasses))))
                ta)))))

(defn descendants
  "Returns the immediate and indirect children of tag, through a relationship
established via derive. h must be a hierarchy obtained from make-hierarchy,
if not supplied defaults to the global hierarchy. Note: does not work on Java
type inheritance relationships."
  {:added "1.0"}
  ([tag] (descendants global-hierarchy tag))
  ([h tag] (if (class? tag)
             (seq (.__subclasses__ tag))
             (not-empty (get (:descendants h) tag)))))

(defn derive
  "Establishes a parent/child relationship between parent and tag. Parent must
be a namespace-qualified symbol or keyword and child can be either a
namespace-qualified symbol or keyword or a class. h must be a hierarchy
obtained from make-hierarchy, if not supplied defaults to, and modifies, the
global hierarchy."
  {:added "1.0"}
  ([tag parent]
   (assert (namespace parent))
   (assert (namespace tag))

   (alter-var-root #'global-hierarchy derive tag parent) nil)
  ([h tag parent]
   (assert (not= tag parent))
   (assert (namespace tag))
   (assert (instance? clojure.lang.named/Named parent))

   (let [tp (:parents h)
         td (:descendants h)
         ta (:ancestors h)
         tf (fn [m source sources target targets]
              (reduce1 (fn [ret k]
                        (assoc ret k
                               (reduce1 conj (get targets k #{}) (cons target (targets target)))))
                      m (cons source (sources source))))]
     (or
      (when-not (contains? (tp tag) parent)
        (when (contains? (ta tag) parent)
          (throw (py/Exception. (str tag "already has" parent "as ancestor"))))
        (when (contains? (ta parent) tag)
          (throw (py/Exception. (str "Cyclic derivation:" parent "has" tag "as ancestor"))))
        {:parents (assoc (:parents h) tag (conj (get tp tag #{}) parent))
         :ancestors (tf (:ancestors h) tag td parent ta)
         :descendants (tf (:descendants h) parent ta tag td)})
      h))))

;;; multimethods
(require 'clojure.core-deftype)
(doseq [to-add ['definterface 'deftype 'defprotocol 'defrecord
                'extend-type 'reify]]
  (intern *ns* to-add (.deref (ns-resolve 'clojure.core-deftype to-add))))
(require 'clojure.core-multimethod)
(intern *ns* 'make-multi clojure.core-multimethod/make-multi)

(defn- check-valid-options
  "Throws an exception if the given option map contains keys not listed
as valid, else returns nil."
  [options & valid-keys]
  (when (seq (apply disj (apply hash-set (keys options)) valid-keys))
    (throw
      (py/Exception.
        (apply str "Only these options are valid: "
          (first valid-keys)
          (map #(str ", " %) (rest valid-keys)))))))

(defmacro defmulti
  "Creates a new multimethod with the associated dispatch function.
The docstring and attribute-map are optional.

Options are key-value pairs and may be one of:
:default the default dispatch value, defaults to :default
:hierarchy the isa? hierarchy to use for dispatching
defaults to the global hierarchy"
  {:arglists '([name docstring? attr-map? dispatch-fn & options])
   :added "1.0"}
  [mm-name & options]
  (let [docstring (if (string? (first options))
                      (first options)
                      nil)
        options (if (string? (first options))
                      (next options)
                      options)
        m (if (map? (first options))
                      (first options)
                      {})
        options (if (map? (first options))
                      (next options)
                      options)
        dispatch-fn (first options)
        options (next options)
        m (if docstring
                      (assoc m :doc docstring)
                      m)
        m (if (meta mm-name)
                      (conj (meta mm-name) m)
                      m)]
    (when (= (count options) 1)
      (throw (py/Exception. "The syntax for defmulti has changed. Example: (defmulti name dispatch-fn :default dispatch-value)")))
    (let [options (apply hash-map options)
          default (get options :default :default)
          hierarchy (get options :hierarchy #'global-hierarchy)]
      (check-valid-options options :default :hierarchy)
      `(let [v# (def ~mm-name)]
         (when-not (and (.hasRoot v#) (instance? clojure.core-multimethod/MultiFn (deref v#)))
           (def ~(with-meta mm-name m)
                (make-multi ~(name mm-name) ~dispatch-fn ~default ~hierarchy)))))))

(defmacro defmethod
  "Creates and installs a new method of multimethod associated with dispatch-value. "
  {:added "1.0"}
  [multifn dispatch-val & fn-tail]
  `(.addMethod ~(with-meta multifn {:tag 'clojure.lang.MultiFn}) ~dispatch-val (fn ~@fn-tail)))

(defn remove-all-methods
  "Removes all of the methods of multimethod."
  {:added "1.2"
   :static true}
 [multifn]
 (.reset multifn))

(defn remove-method
  "Removes the method of multimethod associated with dispatch-value."
  {:added "1.0"
   :static true}
 [multifn dispatch-val]
 (.removeMethod multifn dispatch-val))

(defn prefer-method
  "Causes the multimethod to prefer matches of dispatch-val-x over dispatch-val-y
when there is a conflict"
  {:added "1.0"
   :static true}
  [multifn dispatch-val-x dispatch-val-y]
  (.preferMethod multifn dispatch-val-x dispatch-val-y))

(defn methods
  "Given a multimethod, returns a map of dispatch values -> dispatch fns"
  {:added "1.0"
   :static true}
  [multifn] (.getMethodTable multifn))

(defn get-method
  "Given a multimethod and a dispatch value, returns the dispatch fn
that would apply to that value, or nil if none apply and no default"
  {:added "1.0"
   :static true}
  [multifn dispatch-val] (.getMethod multifn dispatch-val))

(defn prefers
  "Given a multimethod, returns a map of preferred value -> set of other values"
  {:added "1.0"
   :static true}
  [multifn] (.getPreferTable multifn))

;;; strings
(defn subs
  "Returns the substring of s beginning at start inclusive, and ending
at end (defaults to length of string), exclusive. A negative end
counts backwards from the end of the string"
  {:added "1.0"
   :static true}
  ([s start] (.__getitem__ s (py/slice start nil)))
  ([s start end] (.__getitem__ s (py/slice start end))))

(require 're)
(defn re-pattern
  "Accepts a compiled regex or a string containing a regex pattern. Returns a
compiled Python Pattern object, for use, e.g. in re-matcher."
  {:added "1.0"
   :static true}
  [s] (re/compile s))

(defn re-matcher
  "Accepts a compiled regex or a string containing a regex pattern. Returns a
Python MatchObject. If no match, returns nil."
  {:added "1.0"
   :static true}
  [re s] (re/search re s))

(defn re-groups
  "Returns the groups from the most recent match/find. If there are no nested
groups, returns a string of the entire match. If there are nested groups,
returns a vector of the groups, the first element being the entire match. Can
also take a string containing a regular expression, instead of a compiled
regex."
  {:added "1.0"
   :static true}
  [m]
  (if (nil? m)
    []
    (let [gc (count (.groups m))]
      (loop [ret [] c 0]
        (if (<= c gc)
          (recur (conj ret (.group m c)) (inc c))
          ret)))))

(defn re-finditer
  "Returns a Python MatchObject Iterator by calling re.finditer()."
  [re s]
  (re/finditer (re-pattern re) s))

(defn re-finditer-next
   "calls next on a Python Iterable returned from re.find, and returns the
MatchObject, or nil if there are no more."
   [iter]
   (try
      (.next iter)
      (catch py/StopIteration e nil)))

(defn re-seq
  "Returns a lazy sequence of successive matches of pattern in string, using
Python re.finditer(), each such match processed with re-groups."
  {:added "1.0"
   :static true}
  [re s]
  (let [finditer (re-finditer re s)]
    ((fn step []
       (let [matcher (re-finditer-next finditer)]
         (when matcher
           (cons (re-groups matcher) (lazy-seq (step)))))))))

(defn re-matches
  "Returns the match, if any, of string to pattern, using re-matcher. Uses
re-groups to return the groups."
  {:added "1.0"
   :static true}
  [re s]
  (let [m (re-matcher re s)]
     (let [groups (re-groups m)]
        (if (and (not (nil? groups))
                 (= s (first groups)))
             groups
             nil))))

(defn re-find
  "Given a Python find iterator as returned from finditer, returns the next
regex match, if any, of string to pattern. Can also pass in a regex and
string, and re-find will call finditer itself. Uses re-groups to return the
groups."
  {:added "1.0"
   :static true}
  ([finditer]
    (let [match (re-finditer-next finditer)]
      (when (not(nil? match))
        (re-groups match))))
  ([re s]
   (let [finditer (re-finditer re s)]
     (re-find finditer))))

;;; random numbers
(require 'random)
(defn rand
  "Returns a random floating point number between 0 (inclusive) and
n (default 1) (exclusive)."
  {:added "1.0"
   :static true}
  ([] (random/random))
  ([n] (* n (rand))))

(defn rand-int
  "Returns a random integer between 0 (inclusive) and n (exclusive)."
  {:added "1.0"
   :static true}
  [n] (int (rand n)))

;;; trees
(defn tree-seq
  "Returns a lazy sequence of the nodes in a tree, via a depth-first walk.
branch? must be a fn of one arg that returns true if passed a node
that can have children (but may not). children must be a fn of one
arg that returns a sequence of the children. Will only be called on
nodes for which branch? returns true. Root is the root node of the
tree."
  {:added "1.0"
   :static true}
   [branch? children root]
   (let [walk (fn walk [node]
                (lazy-seq
                  (cons node
                    (when (branch? node)
                      (mapcat walk (children node))))))]
     (walk root)))

(require 'os)
(require 'os.path)
(defn file-seq
  "A tree seq on files"
  {:added "1.0"
   :static true}
  [dir]
    (tree-seq
      os.path/isdir
      #(map (partial os.path/join %) (os/listdir %))
     dir))

;;; Python-level lists & arrays
(defn aclone
  "Returns a clone of the Python list. Works on any type implementing slices
and lists."
  [l] (.__getitem__ l (py/slice 0 (py/len l))))

(defn aset
  "Equivalent to l[i] = item in Python."
  [l i item]
  (.__setitem__ l i item))

(require 'array)
(defmacro make-type-array
  {:private true}
  [type-name type-code added]
  `(def ~(with-meta (symbol (str type-name "-array"))
                    {:doc (str "Creates an array of " type-name "s")
                     :added added})
     (fn
       ([size-or-seq#]
         (array/array
           ~type-code
           (if (sequential? size-or-seq#)
             size-or-seq#
             (take size-or-seq# (repeat 0)))))
       ([size# init-val-or-seq#]
         (array/array
           ~type-code
           (take size# (if (sequential? init-val-or-seq#)
                         (concat init-val-or-seq# (repeat 0))
                         (take size# (repeat init-val-or-seq#)))))))))
(make-type-array "float" "f" "1.0")
(make-type-array "byte" "b" "1.1")
(make-type-array "char" "c" "1.1")
(make-type-array "short" "h" "1.1")
(make-type-array "double" "d" "1.0")
(make-type-array "int" "i" "1.0")
(make-type-array "long" "l" "1.0")

;;; STM
(defmacro sync
  "transaction-flags => TBD, pass nil for now

Runs the exprs (in an implicit do) in a transaction that encompasses
exprs and any nested calls. Starts a transaction if none is already
running on this thread. Any uncaught exception will abort the
transaction and flow out of sync. The exprs may be run more than
once, but any effects on Refs will be atomic."
  {:added "1.0"}
  [flags-ignored-for-now & body]
  `(.runInTransaction clojure.lang.lockingtransaction/LockingTransaction (fn [] ~@body)))

(defmacro dosync
  "Runs the exprs (in an implicit do) in a transaction that encompasses
exprs and any nested calls. Starts a transaction if none is already
running on this thread. Any uncaught exception will abort the
transaction and flow out of dosync. The exprs may be run more than
once, but any effects on Refs will be atomic."
  {:added "1.0"}
  [& exprs]
  `(sync nil ~@exprs))

(defn- setup-reference [^clojure.lang.ARef r options]
  (let [opts (apply hash-map options)]
    (when (:meta opts)
      (.resetMeta r (:meta opts)))
    (when (:validator opts)
      (.setValidator r (:validator opts)))
    r))

(defn reset!
  "Sets the value of atom to newval without regard for the
current value. Returns newval."
  {:added "1.0"
   :static true}
  [atom newval] (.reset atom newval))

(defn swap!
  "Atomically swaps the value of atom to be:
(apply f current-value-of-atom args). Note that f may be called
multiple times, and thus should be free of side effects. Returns
the value that was swapped in."
  {:added "1.0"
   :static true}
  ([atom f] (.swap atom f))
  ([atom f x] (.swap atom f x))
  ([atom f x y] (.swap atom f x y))
  ([atom f x y & args] (.swap atom f x y args)))

(defn atom
  "Creates and returns an Atom with an initial value of x and zero or
more options (in any order):

:meta metadata-map

:validator validate-fn

If metadata-map is supplied, it will be come the metadata on the
atom. validate-fn must be nil or a side-effect-free fn of one
argument, which will be passed the intended new state on any state
change. If the new state is unacceptable, the validate-fn should
return false or throw an exception."
  {:added "1.0"
   :static true}
  ([x] (Atom x))
  ([x & options] (setup-reference (atom x) options)))

(defn ref
  "Creates and returns a Ref with an initial value of x and zero or
more options (in any order):

:meta metadata-map

:validator validate-fn

:min-history (default 0)
:max-history (default 10)

If metadata-map is supplied, it will become the metadata on the
ref. validate-fn must be nil or a side-effect-free fn of one
argument, which will be passed the intended new state on any state
change. If the new state is unacceptable, the validate-fn should
return false or throw an exception. validate-fn will be called on
transaction commit, when all refs have their final values.

Normally refs accumulate history dynamically as needed to deal with
read demands. If you know in advance you will need history you can
set :min-history to ensure it will be available when first needed (instead
of after a read fault). History is limited, and the limit can be set
with :max-history."
  {:added "1.0"
   :static true
   }
  ([x] (Ref x)))
  ; ([x & options]
  ; (let [r ^clojure.lang.Ref (setup-reference (ref x) options)
  ; opts (apply hash-map options)]
  ; (when (:max-history opts)
  ; (.setMaxHistory r (:max-history opts)))
  ; (when (:min-history opts)
  ; (.setMinHistory r (:min-history opts)))
  ; r)))

(defn ref-set
  "Must be called in a transaction. Sets the value of ref.
Returns val."
  [ref val]
  (.refSet ref val))

(defn alter
  "Must be called in a transaction. Sets the in-transaction-value of
ref to:

(apply fun in-transaction-value-of-ref args)

and returns the in-transaction-value of ref."
  {:added "1.0"
   :static true}
  [^clojure.lang.Ref ref fun & args]
    (. ref (alter fun args)))

(defn commute
  "Must be called in a transaction. Sets the in-transaction-value of
ref to:

(apply fun in-transaction-value-of-ref args)

and returns the in-transaction-value of ref.

At the commit point of the transaction, sets the value of ref to be:

(apply fun most-recently-committed-value-of-ref args)

Thus fun should be commutative, or, failing that, you must accept
last-one-in-wins behavior. commute allows for more concurrency than
ref-set."
  {:added "1.0"
   :static true}
  [^clojure.lang.Ref ref fun & args]
    (. ref (commute fun args)))

(defn ensure
  "Must be called in a transaction. Protects the ref from modification
by other transactions. Returns the in-transaction-value of
ref. Allows for more concurrency than (ref-set ref @ref)"
  {:added "1.0"
   :static true}
  [^clojure.lang.Ref ref]
    (. ref (touch))
    (. ref (deref)))

(require 'multiprocessing.pool)
(def solo-executor (multiprocessing.pool/ThreadPool))

(defn future-call
  "Takes a function of no args and yields a future object that will
invoke the function in another thread, and will cache the result and
return it on all subsequent calls to deref/@. If the computation has
not yet finished, calls to deref/@ will block."
  {:added "1.1"}
  [f]
  (let [res (.apply_async solo-executor f)]
    (reify
      IPending
       (isRealized [_] (.ready res))
      clojure.lang.ideref/IDeref
       (deref [_] (.get res)))))

(defmacro future
  "Takes a body of expressions and yields a future object that will
invoke the body in another thread, and will cache the result and
return it on all subsequent calls to deref/@. If the computation has
not yet finished, calls to deref/@ will block."
  {:added "1.1"}
  [& body] `(future-call (fn* [] ~@body)))

;;; misc
(defmacro declare
  "defs the supplied var names with no bindings, useful for making forward declarations."
  {:added "1.0"}
  [& names] `(do ~@(map #(list 'def (vary-meta % assoc :declared true)) names)))

(defn hash-combine
  "Creates a new hash value from two other hashes"
  [seed hash]
  (bit-and 0xFFFFFFFF
           (bit-xor seed
                    (+ hash 0x9e3779b9 (bit-shift-left seed 6) (bit-shift-left seed 2)))))

(defn into
  "Returns a new coll consisting of to-coll with all of the items of
from-coll conjoined."
  {:added "1.0"
   :static true}
  [to from]
  (reduce conj to from))

(defmacro lazy-cat
  "Expands to code which yields a lazy sequence of the concatenation of the
supplied colls. Each coll expr is not evaluated until it is needed.

(lazy-cat xs ys zs) === (concat (lazy-seq xs) (lazy-seq ys) (lazy-seq zs))"
  {:added "1.0"}
  [& colls]
  `(concat ~@(map #(list `lazy-seq %) colls)))

(defn map-indexed
  "Returns a lazy sequence consisting of the result of applying f to 0 and the
first item of coll, followed by applying f to 1 and the second item in coll,
etc, until coll is exhausted. Thus function f should accept 2 arguments,
index and item."
  {:added "1.2"
   :static true}
  [f coll]
  (letfn [(mapi [idx coll]
            (lazy-seq
              (when-let [s (seq coll)]
                (if (chunked-seq? s)
                  (let [c (chunk-first s)
                        size (int (count c))
                        b (chunk-buffer size)]
                    (dotimes [i size]
                      (chunk-append b (f (+ idx i) (.nth c i))))
                    (chunk-cons (chunk b) (mapi (+ idx size) (chunk-rest s))))
                  (cons (f idx (first s)) (mapi (inc idx) (rest s)))))))]
    (mapi 0 coll)))

(defmacro memfn
  "Expands into code that creates a fn that expects to be passed an object and
any args and calls the named instance method on the object passing the args.
Use when you want to treat a Java method as a first-class fn."
  {:added "1.0"}
  [name & args]
  `(fn [target# ~@args]
     (. target# (~name ~@args))))

(defn rseq
  "Returns, in constant time, a seq of the items in rev (which can be a vector
or sorted-map), in reverse order. If rev is empty returns nil"
  {:added "1.0"
   :static true}
  [rev] (. rev (rseq)))

(defn macroexpand-1
  "If form represents a macro form, returns its expansion,
else returns form."
  {:added "1.0"
   :static true}
  [form]
  (let [current-comp-var (.-currentCompiler (.-globals clojure/lang))
        comp (if (.isBound current-comp-var)
                (.deref current-comp-var)
                (let [comp (.Compiler (.-compiler clojure/lang))]
                  (.setNS comp (.-__name__ *ns*))
                  comp))]
    (first (.macroexpand (.-compiler clojure/lang) form comp true))))

(defn macroexpand
  "Repeatedly calls macroexpand-1 on form until it no longer
represents a macro form, then returns it. Note neither
macroexpand-1 nor macroexpand expand macros in subforms."
  {:added "1.0"
   :static true}
  [form]
    (let [ex (macroexpand-1 form)]
      (if (identical? ex form)
        form
        (macroexpand ex))))

(require 'time)
(defmacro time [expr]
  `(let [start# (time/clock)
         ret# ~expr]
     (prn (str "Elapsed time: " (py/round (* (- (time/clock) start#) 1000) 3) " msecs"))
     ret#))

(defn replace
  "Given a map of replacement pairs and a vector/collection, returns a
vector/seq with any elements = a key in smap replaced with the
corresponding val in smap"
  {:added "1.0"
   :static true}
  [smap coll]
    (if (vector? coll)
      (reduce1 (fn [v i]
                (if-let [e (find smap (nth v i))]
                        (assoc v i (val e))
                        v))
              coll (range (count coll)))
      (map #(if-let [e (find smap %)] (val e) %) coll)))

(defn reductions
  "Returns a lazy seq of the intermediate values of the reduction (as
per reduce) of coll by f, starting with init."
  {:added "1.2"}
  ([f coll]
     (lazy-seq
      (if-let [s (seq coll)]
        (reductions f (first s) (rest s))
        (list (f)))))
  ([f init coll]
     (cons init
           (lazy-seq
            (when-let [s (seq coll)]
              (reductions f (f init (first s)) (rest s)))))))

(defn with-redefs-fn
  "Temporarily redefines Vars during a call to func. Each val of
binding-map will replace the root value of its key which must be
a Var. After func is called with no args, the root values of all
the Vars will be set back to their old values. These temporary
changes will be visible in all threads. Useful for mocking out
functions during testing."
  {:added "1.3"}
  [binding-map func]
  (let [root-bind (fn [m]
                    (doseq [[a-var a-val] m]
                      (.bindRoot ^clojure.lang.Var a-var a-val)))
        old-vals (zipmap (keys binding-map)
                         (map deref (keys binding-map)))]
    (try
      (root-bind binding-map)
      (func)
      (finally
        (root-bind old-vals)))))

(defmacro with-redefs
  "binding => var-symbol temp-value-expr

Temporarily redefines Vars while executing the body. The
temp-value-exprs will be evaluated and each resulting value will
replace in parallel the root value of its Var. After the body is
executed, the root values of all the Vars will be set back to their
old values. These temporary changes will be visible in all threads.
Useful for mocking out functions during testing."
  {:added "1.3"}
  [bindings & body]
  `(with-redefs-fn ~(zipmap (map #(list `var %) (take-nth 2 bindings))
                            (take-nth 2 (next bindings)))
                    (fn [] ~@body)))

(defmacro while
  "Repeatedly executes body while test expression is true. Presumes
some side-effect will cause test to become false/nil. Returns nil"
  {:added "1.0"}
  [test & body]
  `(loop []
     (when ~test
       ~@body
       (recur))))

(defn distinct?
  "Returns true if no two of the arguments are ="
  {:tag Boolean
   :added "1.0"
   :static true}
  ([x] true)
  ([x y] (not (= x y)))
  ([x y & more]
   (if (not= x y)
     (loop [s #{x y} [x & etc :as xs] more]
       (if xs
         (if (contains? s x)
           false
           (recur (conj s x) etc))
         true))
     false)))

(defn rand-nth
  "Return a random element of the (sequential) collection. Will have
the same performance characteristics as nth for the given
collection."
  {:added "1.2"
   :static true}
  [coll]
  (nth coll (rand-int (count coll))))
Something went wrong with that request. Please try again.