Skip to content
This repository
tree: 8f45f12c61
Fetching contributors…

Cannot retrieve contributors at this time

file 2537 lines (2372 sloc) 90.919 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
/*
Types
. type predicates (subtype) and type matching
. type union and intersection
. builtin type definitions
*/
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#ifdef __WIN32__
#include <malloc.h>
#endif
#include "julia.h"
#include "newobj_internal.h"
#include "jltypes_internal.h"
#include "builtin_proto.h"

jl_tag_type_t *jl_any_type;
jl_tag_type_t *jl_type_type;
jl_struct_type_t *jl_typename_type;
jl_struct_type_t *jl_sym_type;
jl_struct_type_t *jl_symbol_type;
jl_tuple_t *jl_tuple_type;
jl_tag_type_t *jl_ntuple_type;
jl_typename_t *jl_ntuple_typename;
jl_struct_type_t *jl_tvar_type;

jl_struct_type_t *jl_union_kind;
jl_struct_type_t *jl_tag_kind;
jl_struct_type_t *jl_tag_type_type;
jl_struct_type_t *jl_struct_kind;
jl_struct_type_t *jl_bits_kind;

jl_type_t *jl_bottom_type;
jl_value_t *jl_top_type;
jl_tag_type_t *jl_seq_type;
jl_tag_type_t *jl_abstractarray_type;

jl_bits_type_t *jl_bool_type;
jl_bits_type_t *jl_char_type;
jl_bits_type_t *jl_int8_type;
jl_bits_type_t *jl_uint8_type;
jl_bits_type_t *jl_int16_type;
jl_bits_type_t *jl_uint16_type;
jl_bits_type_t *jl_int32_type;
jl_bits_type_t *jl_uint32_type;
jl_bits_type_t *jl_int64_type;
jl_bits_type_t *jl_uint64_type;
jl_bits_type_t *jl_float32_type;
jl_bits_type_t *jl_float64_type;

jl_tuple_t *jl_null;
jl_value_t *jl_nothing;

void jl_add_constructors(jl_struct_type_t *t);

// --- type properties and predicates ---

int jl_is_type(jl_value_t *v)
{
    if (jl_is_tuple(v)) {
        jl_tuple_t *t = (jl_tuple_t*)v;
        size_t i;
        for(i=0; i < jl_tuple_len(t); i++) {
            jl_value_t *vv = jl_tupleref(t, i);
            if (!jl_is_typevar(vv) && !jl_is_type(vv) &&
                !jl_is_typector(vv))
                return 0;
        }
        return 1;
    }
    return jl_is_nontuple_type(v);
}

int jl_has_typevars_(jl_value_t *v, int incl_wildcard)
{
    size_t i;
    if (jl_typeis(v, jl_tvar_type)) {
        if (!((jl_tvar_t*)v)->bound)
            return incl_wildcard;
        return 1;
    }
    jl_tuple_t *t;
    if (jl_is_union_type(v))
        t = ((jl_uniontype_t*)v)->types;
    else if (jl_is_some_tag_type(v))
        t = ((jl_tag_type_t*)v)->parameters;
    else if (jl_is_tuple(v))
        t = (jl_tuple_t*)v;
    else
        t = jl_null;
    for(i=0; i < jl_tuple_len(t); i++) {
        jl_value_t *elt = jl_tupleref(t, i);
        if (elt != v) {
            if (jl_has_typevars_(elt, incl_wildcard))
                return 1;
        }
    }
    // probably not necessary; no reason to use match() instead of subtype()
    // on the unconstrained version of a type
    //if (jl_is_typector(v))
    // return jl_tuple_len((((jl_typector_t*)v)->parameters) > 0);
    return 0;
}

int jl_has_typevars(jl_value_t *v)
{
    return jl_has_typevars_(v, 0);
}

DLLEXPORT int jl_is_leaf_type(jl_value_t *v)
{
    if (jl_is_struct_type(v) || jl_is_bits_type(v)) {
        jl_tuple_t *t = ((jl_tag_type_t*)v)->parameters;
        for(int i=0; i < jl_tuple_len(t); i++) {
            if (jl_is_typevar(jl_tupleref(t,i)))
                return 0;
        }
        return 1;
    }
    if (jl_is_tuple(v)) {
        jl_tuple_t *t = (jl_tuple_t*)v;
        for(int i=0; i < jl_tuple_len(t); i++) {
            if (!jl_is_leaf_type(jl_tupleref(t, i)))
                return 0;
        }
        return 1;
    }
    if (jl_is_type_type(v)) {
        return !jl_is_typevar(jl_tparam0(v));
    }
    return 0;
}

// construct the full type of a value, possibly making a tuple type
jl_value_t *jl_full_type(jl_value_t *v)
{
    if (!jl_is_tuple(v))
        return (jl_value_t*)jl_typeof(v);
    jl_tuple_t *in = (jl_tuple_t*)v;
    jl_tuple_t *out = jl_alloc_tuple(jl_tuple_len(in));
    JL_GC_PUSH(&out);
    size_t i;
    for(i=0; i < jl_tuple_len(in); i++) {
        jl_tupleset(out, i, jl_full_type(jl_tupleref(in, i)));
    }
    JL_GC_POP();
    return (jl_value_t*)out;
}

static int type_eqv_(jl_value_t *a, jl_value_t *b);

// --- type union ---

static int count_union_components(jl_tuple_t *types)
{
    size_t i, c=0;
    for(i=0; i < jl_tuple_len(types); i++) {
        jl_value_t *e = jl_tupleref(types,i);
        if (jl_is_union_type(e)) {
            c += count_union_components(((jl_uniontype_t*)e)->types);
        }
        else {
            c++;
        }
    }
    return c;
}

static void flatten_type_union(jl_tuple_t *types, jl_value_t **out, size_t *idx)
{
    size_t i;
    for(i=0; i < jl_tuple_len(types); i++) {
        jl_value_t *e = jl_tupleref(types,i);
        if (jl_is_union_type(e)) {
            flatten_type_union(((jl_uniontype_t*)e)->types, out, idx);
        }
        else {
            out[*idx] = e;
            (*idx)++;
        }
    }
}

static int union_elt_morespecific(const void *a, const void *b)
{
    return jl_args_morespecific(*(jl_value_t**)a, *(jl_value_t**)b) ? -1 : 1;
}

DLLEXPORT
jl_tuple_t *jl_compute_type_union(jl_tuple_t *types)
{
    size_t n = count_union_components(types);
    jl_value_t **temp = alloca(n * sizeof(jl_value_t*));
    size_t idx=0;
    flatten_type_union(types, temp, &idx);
    JL_GC_PUSHARGS(temp, n);
    assert(idx == n);
    size_t i, j, ndel=0;
    for(i=0; i < n; i++) {
        for(j=0; j < n; j++) {
            if (j != i && temp[i] && temp[j]) {
                if (temp[i] == temp[j] ||
                    (!jl_has_typevars(temp[i]) &&
                     !jl_has_typevars(temp[j]) &&
                     (type_eqv_(temp[i], temp[j]) ||
                      jl_subtype(temp[i], temp[j], 0)))) {
                    temp[i] = NULL;
                    ndel++;
                }
            }
        }
    }
    jl_tuple_t *result = jl_alloc_tuple_uninit(n - ndel);
    j=0;
    for(i=0; i < n; i++) {
        if (temp[i] != NULL) {
            jl_tupleset(result, j, temp[i]);
            j++;
        }
    }
    assert(j == n-ndel);
    // TODO: maybe warn about ambiguities
    qsort(result->data, j, sizeof(jl_value_t*), union_elt_morespecific);
    JL_GC_POP();
    return result;
}

jl_value_t *jl_type_union(jl_tuple_t *types)
{
    types = jl_compute_type_union(types);
    if (jl_tuple_len(types) == 1)
        return jl_tupleref(types, 0);
    if (jl_tuple_len(types) == 0)
        return (jl_value_t*)jl_bottom_type;
    JL_GC_PUSH(&types);
    jl_value_t *tu = (jl_value_t*)jl_new_uniontype(types);
    JL_GC_POP();
    return tu;
}

// --- type intersection ---

typedef enum {invariant, covariant} variance_t;

typedef struct {
    jl_value_t *data[128];
    size_t n;
} cenv_t;

static inline int is_btv(jl_value_t *v)
{
    return jl_is_typevar(v) && ((jl_tvar_t*)v)->bound;
}

static void extend_(jl_value_t *var, jl_value_t *val, cenv_t *soln, int allow)
{
    if (!allow && var == val)
        return;
    if (val < var && is_btv(val) && is_btv(var)) {
        jl_value_t *temp = val;
        val = var;
        var = temp;
    }
    for(int i=0; i < soln->n; i+=2) {
        if (soln->data[i]==var &&
            (soln->data[i+1]==val || (!jl_is_typevar(val) &&
                                      type_eqv_(soln->data[i+1],val))))
            return;
    }
    if (soln->n >= sizeof(soln->data)/sizeof(void*))
        jl_error("type too large");
    soln->data[soln->n++] = var;
    soln->data[soln->n++] = val;
}

static void extend(jl_value_t *var, jl_value_t *val, cenv_t *soln)
{
    extend_(var, val, soln, 0);
}

static jl_value_t *jl_type_intersect(jl_value_t *a, jl_value_t *b,
                                     cenv_t *penv, cenv_t *eqc, variance_t var);

static jl_value_t *intersect_union(jl_uniontype_t *a, jl_value_t *b,
                                   cenv_t *penv, cenv_t *eqc, variance_t var)
{
    int eq0 = eqc->n, co0 = penv->n;
    jl_tuple_t *t = jl_alloc_tuple(jl_tuple_len(a->types));
    JL_GC_PUSH(&t);
    size_t i;
    for(i=0; i < jl_tuple_len(t); i++) {
        int eq_l = eqc->n, co_l = penv->n;
        jl_value_t *ti = jl_type_intersect(jl_tupleref(a->types,i), b,
                                           penv, eqc, var);
        if (ti == (jl_value_t*)jl_bottom_type) {
            eqc->n = eq0; penv->n = co0;
            ti = jl_type_intersect(jl_tupleref(a->types,i), b,
                                   penv, eqc, var);
            if (ti != (jl_value_t*)jl_bottom_type) {
                // tvar conflict among union elements; keep the conflicting
                // constraints rolled back
                eqc->n = eq0; penv->n = co0;
            }
            else {
                // union element doesn't overlap no matter what.
                // so remove only its constraints.
                eqc->n = eq_l; penv->n = co_l;
            }
        }
        jl_tupleset(t, i, ti);
    }
    // problem: an intermediate union type we make here might be too
    // complex, even though the final type after typevars are replaced
    // might be ok.
    jl_value_t *tu = jl_type_union(t);
    JL_GC_POP();
    return tu;
}

// if returns with *bot!=0, then intersection is None
static size_t tuple_intersect_size(jl_tuple_t *a, jl_tuple_t *b, int *bot)
{
    size_t al = jl_tuple_len(a);
    size_t bl = jl_tuple_len(b);
    *bot = 0;
    if (al == bl) return al;
    if (al > bl) return tuple_intersect_size(b, a, bot);
    assert(al < bl);
    if (jl_is_seq_type(jl_tupleref(b,bl-1))) {
        if (al > 0 && jl_is_seq_type(jl_tupleref(a,al-1))) {
            return bl;
        }
        else {
            if (bl == al+1)
                return al;
            *bot=1;
            return 0;
        }
    }
    if (al > 0 && jl_is_seq_type(jl_tupleref(a,al-1))) {
        return bl;
    }
    *bot=1;
    return 0;
}

static jl_value_t *intersect_tuple(jl_tuple_t *a, jl_tuple_t *b,
                                   cenv_t *penv, cenv_t *eqc, variance_t var)
{
    size_t al = jl_tuple_len(a);
    size_t bl = jl_tuple_len(b);
    int bot=0;
    size_t n = tuple_intersect_size(a, b, &bot);
    if (bot)
        return (jl_value_t*)jl_bottom_type;
    if (n == 0) return (jl_value_t*)jl_null;
    jl_tuple_t *tc = jl_alloc_tuple(n);
    jl_value_t *result = (jl_value_t*)tc;
    jl_value_t *ce = NULL;
    JL_GC_PUSH(&tc, &ce);
    size_t ai=0, bi=0, ci;
    jl_value_t *ae=NULL, *be=NULL;
    int aseq=0, bseq=0;
    for(ci=0; ci < n; ci++) {
        if (ai < al) {
            ae = jl_tupleref(a,ai);
            if (jl_is_seq_type(ae)) {
                aseq=1;
                ae = jl_tparam0(ae);
            }
            ai++;
        }
        if (bi < bl) {
            be = jl_tupleref(b,bi);
            if (jl_is_seq_type(be)) {
                bseq=1;
                be = jl_tparam0(be);
            }
            bi++;
        }
        assert(ae!=NULL && be!=NULL);
        ce = jl_type_intersect(ae,be,penv,eqc,var);
        if (ce == (jl_value_t*)jl_bottom_type) {
            if (aseq && bseq) {
                // (X∩Y)==∅ → (X...)∩(Y...) == ()
                if (n == 1) {
                    result = (jl_value_t*)jl_null;
                    goto done_intersect_tuple;
                }
                jl_tuple_set_len_unsafe(tc,jl_tuple_len(tc)-1);
                goto done_intersect_tuple;
            }
            result = (jl_value_t*)jl_bottom_type;
            goto done_intersect_tuple;
        }
        if (aseq && bseq) {
            ce = (jl_value_t*)jl_tuple1(ce);
            ce = (jl_value_t*)jl_apply_type((jl_value_t*)jl_seq_type,
                                            (jl_tuple_t*)ce);
        }
        jl_tupleset(tc, ci, ce);
    }
 done_intersect_tuple:
    JL_GC_POP();
    return result;
}

static jl_value_t *intersect_tag(jl_tag_type_t *a, jl_tag_type_t *b,
                                 cenv_t *penv, cenv_t *eqc, variance_t var)
{
    assert(a->name == b->name);
    assert(jl_tuple_len(a->parameters) == jl_tuple_len(b->parameters));
    jl_tuple_t *p = jl_alloc_tuple(jl_tuple_len(a->parameters));
    JL_GC_PUSH(&p);
    jl_value_t *ti;
    size_t i;
    if (a->name == jl_ntuple_typename) {
        assert(jl_tuple_len(p) == 2);
        // NOTE: tuples are covariant, so NTuple element type is too
        ti = jl_type_intersect(jl_tparam0(a),jl_tparam0(b),penv,eqc,invariant);
        jl_tupleset(p, 0, ti);
        ti = jl_type_intersect(jl_tparam1(a),jl_tparam1(b),penv,eqc,var);
        if (ti==(jl_value_t*)jl_bottom_type ||
            jl_t0(p)==(jl_value_t*)jl_bottom_type) {
            JL_GC_POP();
            return (jl_value_t*)jl_bottom_type;
        }
        jl_tupleset(p, 1, ti);
    }
    else {
        for(i=0; i < jl_tuple_len(p); i++) {
            jl_value_t *ap = jl_tupleref(a->parameters,i);
            jl_value_t *bp = jl_tupleref(b->parameters,i);
            if (jl_is_typevar(ap)) {
                if (var==invariant && jl_is_typevar(bp)) {
                    if (((jl_tvar_t*)ap)->bound != ((jl_tvar_t*)bp)->bound) {
                        // Foo{T} and Foo can never be equal since the former
                        // is always a subtype of the latter
                        JL_GC_POP();
                        return (jl_value_t*)jl_bottom_type;
                    }
                }
                ti = jl_type_intersect(ap,bp,penv,eqc,invariant);
                if (bp == (jl_value_t*)jl_bottom_type &&
                    !((jl_tvar_t*)ap)->bound) {
                    // "None" as a type parameter
                    jl_tupleset(p, i, ti);
                    continue;
                }
            }
            else if (jl_is_typevar(bp)) {
                ti = jl_type_intersect(ap,bp,penv,eqc,invariant);
                if (ap == (jl_value_t*)jl_bottom_type &&
                    !((jl_tvar_t*)bp)->bound) {
                    // "None" as a type parameter
                    jl_tupleset(p, i, ti);
                    continue;
                }
            }
            else if (jl_has_typevars_(ap,1) || jl_has_typevars_(bp,1)) {
                if (jl_subtype_invariant(ap,bp,0) ||
                    jl_subtype_invariant(bp,ap,0)) {
                    ti = jl_type_intersect(ap,bp,penv,eqc,invariant);
                }
                else {
                    ti = (jl_value_t*)jl_bottom_type;
                }
            }
            else if (type_eqv_(ap,bp)) {
                ti = ap;
                if (ti == (jl_value_t*)jl_bottom_type) {
                    // "None" as a type parameter
                    jl_tupleset(p, i, ti);
                    continue;
                }
            }
            else {
                ti = (jl_value_t*)jl_bottom_type;
            }
            if (ti == (jl_value_t*)jl_bottom_type) {
                JL_GC_POP();
                return (jl_value_t*)jl_bottom_type;
            }
            jl_tupleset(p, i, ti);
        }
    }
    if (a->name->primary != NULL) {
        jl_value_t *res = (jl_value_t*)jl_apply_type(a->name->primary, p);
        JL_GC_POP();
        return res;
    }
    assert(0 && "not yet implemented");
    return NULL;
}

static int match_intersection_mode = 0;

static jl_value_t *intersect_typevar(jl_tvar_t *a, jl_value_t *b,
                                     cenv_t *penv, cenv_t *eqc, variance_t var)
{
    if (jl_subtype(b, (jl_value_t*)a, 0)) {
        if (!a->bound) return b;
    }
    else if (var==invariant && !jl_has_typevars_(b,1)) {
        // for typevar a and non-typevar type b, b must be within a's bounds
        // in invariant contexts.
        return (jl_value_t*)jl_bottom_type;
    }
    else if (jl_subtype((jl_value_t*)a, b, 0)) {
        /*
TODO: get sharper types when the overlap between a typevar and
a type is not simple. Ex:
tintersect(Type{Array{T,n}}, Type{typevar(:_,Vector)})
should give Type{_<:Vector}
*/
        if (jl_is_typevar(b)) {
            if (!((jl_tvar_t*)b)->bound) return (jl_value_t*)a;
        }
        else {
            if (!a->bound) return (jl_value_t*)a;
        }
    }
    else {
        return (jl_value_t*)jl_bottom_type;
    }
    if (var == invariant && !jl_has_typevars_(b,0)) {
        int i;
        for(i=0; i < eqc->n; i+=2) {
            if (eqc->data[i] == (jl_value_t*)a) {
                jl_value_t *v = eqc->data[i+1];
                if (jl_is_typevar(v))
                    continue;
                if (jl_is_long(b)) {
                    if (jl_is_long(v)) {
                        /*
do a meet over the lattice of tuple lengths:
>=0
| \
| 0
>=1
| \
| 1
>=2
| \
| 2
...
*/
                        long bv = jl_unbox_long(b);
                        long vv = jl_unbox_long(v);
                        if (bv < 0) {
                            if (vv < 0) {
                                if (bv < vv) {
                                    eqc->data[i+1] = b;
                                }
                            }
                            else {
                                if (~bv > vv)
                                    return (jl_value_t*)jl_bottom_type;
                            }
                        }
                        else {
                            if (vv < 0) {
                                if (~vv > bv)
                                    return (jl_value_t*)jl_bottom_type;
                                eqc->data[i+1] = b;
                            }
                            else {
                                if (bv != vv)
                                    return (jl_value_t*)jl_bottom_type;
                            }
                        }
                        break;
                    }
                    else {
                        return (jl_value_t*)jl_bottom_type;
                    }
                }
                if (!jl_types_equal(v, b))
                    return (jl_value_t*)jl_bottom_type;
                break;
            }
        }
        if (i >= eqc->n) {
            extend((jl_value_t*)a, b, eqc);
        }
        return (jl_value_t*)a;
    }
    if ((jl_value_t*)a != b) {
        if (var == invariant)
            extend((jl_value_t*)a, b, eqc);
        else
            extend((jl_value_t*)a, b, penv);
    }
    return (jl_value_t*)a;
}

static jl_value_t *jl_type_intersect(jl_value_t *a, jl_value_t *b,
                                     cenv_t *penv, cenv_t *eqc, variance_t var)
{
    if (jl_is_typector(a))
        a = (jl_value_t*)((jl_typector_t*)a)->body;
    if (jl_is_typector(b))
        b = (jl_value_t*)((jl_typector_t*)b)->body;
    if (a == b) return a;
    if (jl_is_typevar(a)) {
        if (var == covariant && !((jl_tvar_t*)a)->bound)
            a = ((jl_tvar_t*)a)->ub;
        else if (a != jl_ANY_flag)
            return intersect_typevar((jl_tvar_t*)a, b, penv, eqc, var);
    }
    if (jl_is_typevar(b)) {
        if (var == covariant && !((jl_tvar_t*)b)->bound)
            b = ((jl_tvar_t*)b)->ub;
        else if (b != jl_ANY_flag)
            return intersect_typevar((jl_tvar_t*)b, a, penv, eqc, var);
    }
    if (a == (jl_value_t*)jl_bottom_type || b == (jl_value_t*)jl_bottom_type)
        return (jl_value_t*)jl_bottom_type;
    if (!jl_has_typevars(a) && !jl_has_typevars(b)) {
        if (jl_subtype(a, b, 0))
            return a;
        if (jl_subtype(b, a, 0))
            return b;
    }
    // union
    if (jl_is_union_type(a))
        return intersect_union((jl_uniontype_t*)a, b, penv, eqc, var);
    if (jl_is_union_type(b))
        return intersect_union((jl_uniontype_t*)b, a, penv, eqc, var);
    if (a == (jl_value_t*)jl_undef_type) return (jl_value_t*)jl_bottom_type;
    if (b == (jl_value_t*)jl_undef_type) return (jl_value_t*)jl_bottom_type;
    if (a == (jl_value_t*)jl_any_type ||
        a == jl_ANY_flag) return b;
    if (b == (jl_value_t*)jl_any_type ||
        b == jl_ANY_flag) return a;
    // tuple
    if (jl_is_tuple(a)) {
        jl_value_t *temp=NULL;
        JL_GC_PUSH(&b, &temp);
        if (jl_is_ntuple_type(b)) {
            long alen = (long)jl_tuple_len(a);
            jl_value_t *lenvar = jl_tparam0(b);
            jl_value_t *elty = jl_tparam1(b);
            int i;
            for(i=0; i < eqc->n; i+=2) {
                if (eqc->data[i] == lenvar) {
                    jl_value_t *v = eqc->data[i+1];
                    if (jl_is_long(v) && jl_unbox_long(v)>=0) {
                        // N is already known in NTuple{N,...}
                        alen = jl_unbox_long(v);
                        break;
                    }
                }
            }
            b = (jl_value_t*)jl_tuple_fill(alen, elty);
            if (i >= eqc->n) {
                // don't know N yet, so add a constraint for it based on
                // the length of the other tuple
                if (alen > 0 && jl_is_seq_type(jl_tupleref(a,alen-1))) {
                    temp = (jl_value_t*)jl_tuple1(elty);
                    jl_tupleset(b, alen-1, jl_apply_type((jl_value_t*)jl_seq_type,
                                                         (jl_tuple_t*)temp));
                    // if the value of an NTuple typevar, N, is negative,
                    // it means the tuple needs to be at least ~N long.
                    alen = ~(alen-1);
                }
                if (jl_is_typevar(lenvar)) {
                    temp = jl_box_long(alen);
                    if (intersect_typevar((jl_tvar_t*)lenvar,temp,penv,eqc,
                                          invariant) ==
                        (jl_value_t*)jl_bottom_type) {
                        JL_GC_POP();
                        return (jl_value_t*)jl_bottom_type;
                    }
                }
            }
        }
        if (!jl_is_tuple(b)) {
            JL_GC_POP();
            return (jl_value_t*)jl_bottom_type;
        }
        a = intersect_tuple((jl_tuple_t*)a, (jl_tuple_t*)b, penv,eqc,var);
        JL_GC_POP();
        return a;
    }
    if (jl_is_tuple(b)) {
        return jl_type_intersect(b, a, penv,eqc,var);
    }
    if (jl_is_long(a) || jl_is_long(b))
        return (jl_value_t*)jl_bottom_type;
    // tag
    assert(jl_is_some_tag_type(a));
    assert(jl_is_some_tag_type(b));
    jl_tag_type_t *tta = (jl_tag_type_t*)a;
    jl_tag_type_t *ttb = (jl_tag_type_t*)b;
    if (tta->name == ttb->name)
        return (jl_value_t*)intersect_tag(tta, ttb, penv, eqc, var);
    jl_tag_type_t *super = NULL;
    jl_tag_type_t *sub = NULL;
    jl_value_t *env = NULL;
    jl_tuple_t *p = NULL;
    JL_GC_PUSH(&super, &sub, &env, &p);
    while (tta != jl_any_type) {
        if (tta->name == ttb->name) {
            sub = (jl_tag_type_t*)a;
            super = (jl_tag_type_t*)b;
            break;
        }
        tta = tta->super;
    }
    if (sub == NULL) {
        tta = (jl_tag_type_t*)a;
        while (ttb != jl_any_type) {
            if (tta->name == ttb->name) {
                sub = (jl_tag_type_t*)b;
                super = (jl_tag_type_t*)a;
                break;
            }
            ttb = ttb->super;
        }
        if (sub == NULL) {
            JL_GC_POP();
            return (jl_value_t*)jl_bottom_type;
        }
    }

    if (sub->super == jl_type_type && jl_is_type_type((jl_value_t*)super)) {
        // subtypes of Type like BitsKind do not constrain the type
        // parameter, and yet contain Type instances with a more specific
        // parameter (like Type{Int}). This is a special case.
        jl_value_t *tp0 = jl_tparam0(super);
        if (jl_is_typevar(tp0) || (jl_type_t*)sub == jl_typeof(tp0)) {
            JL_GC_POP();
            return (jl_value_t*)super;
        }
        JL_GC_POP();
        return (jl_value_t*)jl_bottom_type;
    }

    super = (jl_tag_type_t*)jl_type_intersect((jl_value_t*)sub->super, (jl_value_t*)super, penv, eqc, var);

    if ((jl_type_t*)super == jl_bottom_type) {
        JL_GC_POP();
        return (jl_value_t*)jl_bottom_type;
    }

    // super needs to be instantiated so the matching below finds actual types
    // and doesn't fail due to the presence of extra typevars.
    super = (jl_tag_type_t*)jl_instantiate_type_with((jl_type_t*)super, eqc->data, eqc->n/2);

    size_t n = jl_tuple_len(sub->parameters);

    assert(sub->name->primary != NULL);
    jl_value_t *tc = sub->name->primary;
    jl_tuple_t *tc_params = ((jl_tag_type_t*)tc)->parameters;
    // compute what constraints the supertype imposes on the subtype
    jl_tuple_t *subs_sup_params =
        ((jl_tag_type_t*)((jl_tag_type_t*)tc)->super)->parameters;
    // match the intersected supertype against the pattern this subtype
    // uses to instantiate its supertype. this tells us what subtype parameter
    // values are implied by the intersected supertype, or that the
    // intersected supertype cannot come from this subtype (in which case
    // our final answer is None).
    size_t i;
    // hack: we need type_match to find assignments for all typevars
    int prev_mim = match_intersection_mode;
    match_intersection_mode = 1;
    env = jl_type_match((jl_value_t*)super->parameters,
                        (jl_value_t*)subs_sup_params);
    int sub_needs_parameters = 0;
    if (env == jl_false) {
        env = jl_type_match((jl_value_t*)subs_sup_params,
                            (jl_value_t*)super->parameters);
    }
    else {
        // this means it needs to be possible to instantiate the subtype
        // such that the supertype gets the matching parameters we just
        // determined.
        sub_needs_parameters = 1;
    }
    match_intersection_mode = prev_mim;
    if (env == jl_false) {
        JL_GC_POP();
        return (jl_value_t*)jl_bottom_type;
    }
    if (sub_needs_parameters) {
        for(int e=0; e < jl_tuple_len(env); e+=2) {
            jl_value_t *tp = jl_tupleref(env, e);
            // make sure each needed parameter is actually set by the subtype
            size_t j;
            for(j=0; j < n; j++) {
                if (tp == jl_tupleref(tc_params, j))
                    break;
            }
            if (j >= n) {
                JL_GC_POP();
                return (jl_value_t*)jl_bottom_type;
            }
        }
    }

    p = jl_alloc_tuple(n);
    for(i=0; i < n; i++) {
        jl_value_t *tp = jl_tupleref(tc_params, i);
        jl_value_t *elt = jl_tupleref(sub->parameters, i);
        for(int e=0; e < jl_tuple_len(env); e+=2) {
            if (jl_tupleref(env, e) == tp) {
                elt = jl_type_intersect(elt, jl_tupleref(env, e+1),
                                        penv, eqc, invariant);
                // note: elt might be None if "None" was the type parameter
                break;
            }
        }
        jl_tupleset(p, i, elt);
    }
    jl_value_t *result = (jl_value_t*)jl_apply_type(tc, p);
    JL_GC_POP();
    return result;
}

jl_value_t *jl_type_intersection(jl_value_t *a, jl_value_t *b)
{
    jl_tuple_t *env = jl_null;
    JL_GC_PUSH(&env);
    jl_value_t *ti = jl_type_intersection_matching(a, b, &env, jl_null);
    JL_GC_POP();
    return ti;
}

/*
constraint satisfaction algorithm:
- keep lists of equality constraints and subtype constraints
(invariant and covariant)
- all constraints between two typevars are equality, i.e. it means the
two corresponding typevars must end up with the same value. however
they are kept in the subtype constraint list because they are not part
of the final answer yet.
- after computing the intersection, we try to solve the typevar constraints
- for each equality constraint T=S, add T=S to the results
- for each other constraint T=S, do
if T=U is in the results
if S is a typevar
if S=R is in the results
update R to meet(lookup(R),lookup(U))
else
add S=meet(S,lookup(U))
end
update U to S
else
update U to meet(lookup(U),S)
end
else
if S has typevars
add T=S
else
add T=_<:S
end
end

meet(X,Y) =
if X and Y both have no typevars and not equal, fail
if X has no typevars and X<:Y, return X, else fail
if Y has no typevars and Y<:X, return Y, else fail
if one or both is typevar, return meet_typevar(X,Y)
else return intersect(X,Y)

update X to Y =
if X is a typevar, trace to its class root and put Y there
else put Y where X was

lookup(X) =
if X is a typevar and X=Y is in the results, return lookup(Y)
else return X
*/

static jl_value_t **tvar_lookup(cenv_t *env, jl_value_t **pX)
{
    jl_value_t *v = *pX;
    if (is_btv(v)) {
        for(int i=0; i < env->n; i+=2) {
            if (env->data[i] == v) {
                if (env->data[i+1] == v) // allow T=T
                    return pX;
                return tvar_lookup(env, &env->data[i+1]);
            }
        }
    }
    return pX;
}

static jl_value_t *meet_tvars(jl_tvar_t *a, jl_tvar_t *b)
{
    jl_value_t *lb=NULL, *ub=NULL;
    if (type_eqv_((jl_value_t*)a->lb, (jl_value_t*)b->lb) &&
        type_eqv_((jl_value_t*)a->ub, (jl_value_t*)b->ub))
        return (jl_value_t*)b;
    ub = jl_type_intersection((jl_value_t*)a->ub, (jl_value_t*)b->ub);
    if (ub == (jl_value_t*)jl_bottom_type)
        return ub;
    JL_GC_PUSH(&lb, &ub);
    lb = (jl_value_t*)jl_tuple2(a->lb, b->lb);
    lb = jl_type_union((jl_tuple_t*)lb);
    if (!jl_subtype(lb, ub, 0)) {
        JL_GC_POP();
        return (jl_value_t*)jl_bottom_type;
    }
    // TODO: might not want to collapse tvar to non-tvar in all cases
    if (jl_is_leaf_type(ub)) {
        JL_GC_POP();
        return ub;
    }
    jl_value_t *res = (jl_value_t*)jl_new_typevar(underscore_sym, lb, ub);
    JL_GC_POP();
    return res;
}

static jl_value_t *meet_tvar(jl_tvar_t *tv, jl_value_t *ty)
{
    if (jl_is_typevar(ty))
        return (jl_value_t*)meet_tvars(tv, (jl_tvar_t*)ty);
    //if (jl_types_equal((jl_value_t*)tv->ub, ty))
    // return ty;
    if (jl_subtype((jl_value_t*)tv->ub, ty, 0))
        return (jl_value_t*)tv;
    // TODO: should we check type_intersection(tv->ub, ty) instead?
    if (!jl_subtype(ty, (jl_value_t*)tv->ub, 0))
        return (jl_value_t*)jl_bottom_type;
    //if (jl_types_equal((jl_value_t*)tv->lb, ty))
    // return ty;
    if (jl_subtype((jl_value_t*)tv->lb, ty, 0)) {
        if (jl_is_leaf_type(ty) || jl_is_long(ty))
            return ty;
        return (jl_value_t*)jl_new_typevar(underscore_sym, tv->lb, ty);
    }
    return (jl_value_t*)jl_bottom_type;
}

static jl_value_t *meet(jl_value_t *X, jl_value_t *Y, variance_t var)
{
    if (jl_is_typevar(X)) {
        jl_value_t *tv;
        if (jl_is_typevar(Y)) {
            tv = meet_tvars((jl_tvar_t*)X, (jl_tvar_t*)Y);
        }
        else {
            tv = meet_tvar((jl_tvar_t*)X, Y);
        }
        if (tv == (jl_value_t*)jl_bottom_type)
            return NULL;
        return tv;
    }
    if (jl_is_typevar(Y)) {
        jl_value_t *tv = meet_tvar((jl_tvar_t*)Y, X);
        if (tv == (jl_value_t*)jl_bottom_type)
            return NULL;
        return tv;
    }
    if (!jl_has_typevars_(X,1)) {
        if (!jl_has_typevars_(Y,1)) {
            if (var==invariant) {
                return (jl_types_equal(X,Y) ? X : NULL);
            }
        }
        return (jl_subtype(X,Y,0) ? X : NULL);
    }
    if (!jl_has_typevars_(Y,1)) {
        return (jl_subtype(Y,X,0) ? Y : NULL);
    }
    jl_value_t *v = jl_type_intersection(X, Y);
    return (v == (jl_value_t*)jl_bottom_type ? NULL : v);
}

static int solve_tvar_constraints(cenv_t *env, cenv_t *soln)
{
    //JL_PRINTF(JL_STDOUT, "\n");
    jl_value_t *v=NULL;
    for(int i=0; i < env->n; i+=2) {
        jl_value_t *T = env->data[i];
        jl_value_t *S = env->data[i+1];
        jl_value_t **pT;
        pT = tvar_lookup(soln, &T);
        if (pT != &T) {
            // T=U is in the results
            jl_value_t **pU = pT;
            //jl_value_t *U = *pU;
            if (is_btv(S)) {
                // S is a typevar
                jl_value_t **pS;
                pS = tvar_lookup(soln, &S);
                if (pS != &S) {
                    // S=R is in the results
                    jl_value_t **pR = pS;
                    *pR = meet(*pR, *pU, invariant);
                    if (*pR == NULL) {
                        return 0;
                    }
                }
                else {
                    v = meet(*pU, S, covariant);
                    if (v == NULL) {
                        return 0;
                    }
                    extend(S, v, soln);
                }
                if (pS != pU)
                    *pU = S;
            }
            else {
                if (!jl_subtype(*pU, S, 0)) {
                    // T<:S and T=U and !(U<:S)
                    return 0;
                }
                v = meet(*pU, S, covariant);
                if (v == NULL) {
                    return 0;
                }
                if (is_btv(*pU)) {
                    extend(*pU, v, soln);
                }
                else {
                    *pU = v;
                }
            }
        }
        else {
            if (jl_has_typevars_(S,1)) {
                if (*tvar_lookup(soln, &S) != T)
                    extend(T, S, soln);
            }
            else {
                if (jl_is_leaf_type(S) || jl_is_long(S) ||
                    S == (jl_value_t*)jl_bottom_type) {
                    v = S;
                }
                else {
                    assert(jl_is_typevar(T));
                    v = meet(S, T, covariant);
                    if (!jl_is_typevar(v)) {
                        v = (jl_value_t*)
                            jl_new_typevar(underscore_sym,
                                           (jl_value_t*)jl_bottom_type, v);
                    }
                }
                extend(T, v, soln);
            }
        }
    }
    return 1;
}

#if 0
static char *type_summary(jl_value_t *t)
{
    if (jl_is_tuple(t)) return "Tuple";
    if (jl_is_some_tag_type(t))
        return ((jl_tag_type_t*)t)->name->name->name;
    return "?";
}
static void print_env(cenv_t *soln)
{
    for(int i=0; i < soln->n; i+=2) {
        jl_value_t *T, *S;
        T = soln->data[i]; S = soln->data[i+1];
        ios_printf(ios_stdout,
                   "%s@%x=%s ",
                   ((jl_tvar_t*)T)->name->name, T,
                   type_summary(S));
    }
    ios_printf(ios_stdout, "\n");
}
#endif

jl_value_t *jl_type_intersection_matching(jl_value_t *a, jl_value_t *b,
                                          jl_tuple_t **penv, jl_tuple_t *tvars)
{
    cenv_t eqc; eqc.n = 0; memset(eqc.data, 0, sizeof(eqc.data));
    cenv_t env; env.n = 0; memset(env.data, 0, sizeof(env.data));
    jl_value_t *ti = NULL;

    JL_GC_PUSH(&ti);
    int nrts = sizeof(eqc.data)/sizeof(void*);
    JL_GC_PUSHARGS(eqc.data, nrts);
    jl_gcframe_t __gc_stkf3_ = { (jl_value_t***)env.data, nrts,
                                 0, jl_pgcstack };
    jl_pgcstack = &__gc_stkf3_;

    JL_TRY {
        // This is kind of awful, but an inner call to instantiate_type
        // might fail due to a mismatched type parameter. The problem is
        // that we allow Range{T} to exist, even though the declaration of
        // Range specifies Range{T<:Real}. Therefore intersection cannot see
        // that some parameter values actually don't match.
        ti = jl_type_intersect(a, b, &env, &eqc, covariant);
    }
    JL_CATCH {
        ti = (jl_value_t*)jl_bottom_type;
    }
    if (ti == (jl_value_t*)jl_bottom_type ||
        !(env.n > 0 || eqc.n > 0 || tvars != jl_null)) {
        JL_GC_POP(); JL_GC_POP(); JL_GC_POP();
        return ti;
    }

    int e;
    for(e=0; e < eqc.n; e+=2) {
        jl_value_t *val = eqc.data[e+1];
        if (jl_is_long(val) && jl_unbox_long(val)>=0) {
            break;
        }
    }
    if (e < eqc.n) {
        /*
if there are integer-valued parameters, repeat intersection
with the full environment visible. this is needed because
NTuple has only one element type, so we can't keep track of
the fact that an arbitrary tuple's length must match some
typevar, e.g. "(Int8,Int32...) of length N". the solution is
to find all other constraints on N first, then do intersection
again with that knowledge.
*/
        ti = jl_type_intersect(a, b, &env, &eqc, covariant);
        if (ti == (jl_value_t*)jl_bottom_type) {
            JL_GC_POP(); JL_GC_POP(); JL_GC_POP();
            return ti;
        }
    }

    if (!solve_tvar_constraints(&env, &eqc)) {
        JL_GC_POP(); JL_GC_POP(); JL_GC_POP();
        return (jl_value_t*)jl_bottom_type;
    }
    //JL_PRINTF(JL_STDOUT, "env: "); print_env(&env);
    //JL_PRINTF(JL_STDOUT, "sol: "); print_env(&eqc);

    // convert non-specific integer vars to typevars
    for(e=0; e < eqc.n; e+=2) {
        jl_value_t *val = eqc.data[e+1];
        if (jl_is_long(val) && jl_unbox_long(val)<0) {
            eqc.data[e+1] = eqc.data[e];
        }
    }

    int env0 = eqc.n;
    jl_value_t **tvs;
    int tvarslen;
    if (jl_is_typevar(tvars)) {
        tvs = (jl_value_t**)&tvars;
        tvarslen = 1;
    }
    else {
        tvs = &jl_t0(tvars);
        tvarslen = jl_tuple_len(tvars);
    }
    for(int tk=0; tk < tvarslen; tk++) {
        jl_value_t *tv = tvs[tk];
        for(e=0; e < env0; e+=2) {
            if (eqc.data[e] == tv) {
                break;
            }
        }
        // bind type vars to themselves if they were not matched explicitly
        // during type intersection.
        if (e >= env0)
            extend_(tv, tv, &eqc, 1);
    }

    *penv = jl_alloc_tuple_uninit(eqc.n);
    for(int i=0; i < eqc.n; i+=2) {
        jl_tupleset(*penv, i, eqc.data[i]);
        jl_tupleset(*penv, i+1, *tvar_lookup(&eqc, &eqc.data[i+1]));
    }

    if (env0 > 0) {
        ti = (jl_value_t*)
            jl_instantiate_type_with((jl_type_t*)ti, &jl_t0(*penv), eqc.n/2);
    }

    JL_GC_POP(); JL_GC_POP(); JL_GC_POP();
    return ti;
}

// --- type instantiation and cache ---

static int extensionally_same_type(jl_value_t *a, jl_value_t *b)
{
    return jl_subtype(a, b, 0) && jl_subtype(b, a, 0);
}

static int type_eqv_(jl_value_t *a, jl_value_t *b)
{
    if (a == b) return 1;
    if (jl_is_typector(a)) a = (jl_value_t*)((jl_typector_t*)a)->body;
    if (jl_is_typector(b)) b = (jl_value_t*)((jl_typector_t*)b)->body;
    if (jl_is_typevar(a)) {
        if (jl_is_typevar(b)) {
            return type_eqv_(((jl_tvar_t*)a)->ub, ((jl_tvar_t*)b)->ub) &&
                type_eqv_(((jl_tvar_t*)a)->lb, ((jl_tvar_t*)b)->lb);
        }
        else {
            return 0;
        }
    }
    if (jl_is_long(a)) {
        if (jl_is_long(b))
            return (jl_unbox_long(a) == jl_unbox_long(b));
        return 0;
    }
    if (jl_is_tuple(a)) {
        if (jl_is_tuple(b)) {
            jl_tuple_t *ta = (jl_tuple_t*)a; jl_tuple_t *tb = (jl_tuple_t*)b;
            int sqa = (jl_tuple_len(ta)>0 &&
                       jl_is_seq_type(jl_tupleref(ta,jl_tuple_len(ta)-1)));
            int sqb = (jl_tuple_len(tb)>0 &&
                       jl_is_seq_type(jl_tupleref(tb,jl_tuple_len(tb)-1)));
            if (sqa && sqb)
                return extensionally_same_type(a, b);
            if (sqa != sqb || jl_tuple_len(ta) != jl_tuple_len(tb))
                return 0;
            for(int i=0; i < jl_tuple_len(ta); i++) {
                if (!type_eqv_(jl_tupleref(ta,i),jl_tupleref(tb,i)))
                    return 0;
            }
            return 1;
        }
        return 0;
    }
    if (jl_is_union_type(a)) {
        if (jl_is_union_type(b)) {
            return extensionally_same_type(a, b);
        }
        return 0;
    }
    assert(jl_is_some_tag_type(a));
    if (!jl_is_some_tag_type(b)) return 0;
    jl_tag_type_t *tta = (jl_tag_type_t*)a;
    jl_tag_type_t *ttb = (jl_tag_type_t*)b;
    if (tta->name != ttb->name) return 0;
    jl_tuple_t *ap = tta->parameters;
    jl_tuple_t *bp = ttb->parameters;
    assert(jl_tuple_len(ap) == jl_tuple_len(bp));
    size_t i;
    for(i=0; i < jl_tuple_len(ap); i++) {
        jl_value_t *api = jl_tupleref(ap,i);
        jl_value_t *bpi = jl_tupleref(bp,i);
        if (api == bpi) continue;
        if (!type_eqv_(api, bpi))
            return 0;
    }
    return 1;
}

int jl_types_equal(jl_value_t *a, jl_value_t *b)
{
    return type_eqv_(a, b);
}

static int type_le_generic(jl_value_t *a, jl_value_t *b)
{
    jl_value_t *env = jl_type_match(a, b);
    if (env == jl_false) return 0;
    // make sure all typevars correspond to other unique typevars
    for(int i=0; i < jl_tuple_len(env); i+=2) {
        if (!jl_is_typevar(jl_tupleref(env,i+1)))
            return 0;
        for(int j=0; j < jl_tuple_len(env); j+=2) {
            if (i != j) {
                if (jl_tupleref(env,i+1) == jl_tupleref(env,j+1))
                    return 0;
            }
        }
    }
    return 1;
}

int jl_types_equal_generic(jl_value_t *a, jl_value_t *b)
{
    return type_le_generic(a, b) && type_le_generic(b, a);
}

jl_value_t *jl_apply_type_(jl_value_t *tc, jl_value_t **params, size_t n)
{
    if (n == 0) {
        if (jl_is_typector(tc))
            return (jl_value_t*)((jl_typector_t*)tc)->body;
        return tc;
    }
    size_t i;
    char *tname;
    jl_tuple_t *tp;
    if (jl_is_typector(tc)) {
        tp = ((jl_typector_t*)tc)->parameters;
        tname = "alias";
    }
    else {
        assert(jl_is_some_tag_type(tc));
        tp = ((jl_tag_type_t*)tc)->parameters;
        tname = ((jl_tag_type_t*)tc)->name->name->name;
    }
    for(i=0; i < n; i++) {
        jl_value_t *pi = params[i];
        if (!jl_is_type(pi) && !jl_is_long(pi) && !jl_is_typevar(pi)) {
            jl_type_error_rt("apply_type", tname,
                             (jl_value_t*)jl_type_type, pi);
        }
    }
    if (tc == (jl_value_t*)jl_ntuple_type && (n==1||n==2) &&
        jl_is_long(params[0])) {
        size_t nt = jl_unbox_long(params[0]);
        return (jl_value_t*)jl_tuple_fill(nt, (n==2) ? params[1] :
                                          (jl_value_t*)jl_any_type);
    }
    if (n > jl_tuple_len(tp))
        jl_errorf("too many parameters for type %s", tname);
    jl_value_t **env = alloca(2 * jl_tuple_len(tp) * sizeof(jl_value_t*));
    size_t ne = 0;
    for(i=0; i < jl_tuple_len(tp); i++) {
        jl_tvar_t *tv = (jl_tvar_t*)jl_tupleref(tp,i);
        if (!jl_is_typevar(tv))
            continue;
        env[ne*2+0] = (jl_value_t*)tv;
        if (i >= n) {
            env[ne*2+1] = (jl_value_t*)tv;
        }
        else {
            // NOTE: type checking deferred to inst_type_w_ to make sure
            // supertype parameters are checked recursively.
            if (jl_is_typector(params[i]))
                env[ne*2+1] = (jl_value_t*)((jl_typector_t*)params[i])->body;
            else
                env[ne*2+1] = params[i];
        }
        ne++;
    }
    if (jl_is_typector(tc)) tc = (jl_value_t*)((jl_typector_t*)tc)->body;
    return (jl_value_t*)jl_instantiate_type_with((jl_type_t*)tc, env, ne);
}

jl_value_t *jl_apply_type(jl_value_t *tc, jl_tuple_t *params)
{
    return jl_apply_type_(tc, &jl_tupleref(params,0), jl_tuple_len(params));
}

static jl_type_t *lookup_type(jl_tuple_t *table,
                              jl_typename_t *tn, jl_value_t **key, size_t n)
{
    if (n==0) return NULL;
    while (table != jl_null) {
        jl_tag_type_t *tt = (jl_tag_type_t*)jl_t0(table);
        if (tt->name == tn && n == jl_tuple_len(tt->parameters)) {
            size_t i;
            for(i=0; i < n; i++) {
                if (!type_eqv_(jl_tupleref(tt->parameters,i), key[i]))
                    break;
            }
            if (i==n) return (jl_type_t*)tt;
        }
        table = (jl_tuple_t*)jl_t1(table);
    }
    return NULL;
}

static int t_uid_ctr = 1;

int jl_get_t_uid_ctr(void) { return t_uid_ctr; }
void jl_set_t_uid_ctr(int i) { t_uid_ctr=i; }

int jl_assign_type_uid(void)
{
    return t_uid_ctr++;
}

static void cache_type_(jl_type_t *type)
{
    // only cache concrete types
    jl_tuple_t *t = ((jl_tag_type_t*)type)->parameters;
    if (jl_tuple_len(t) == 0) return;
    if (jl_is_tag_type(type)) {
        if (jl_has_typevars_((jl_value_t*)type,1))
            return;
    }
    else {
        if (jl_has_typevars_((jl_value_t*)type,0))
            return;
        for(int i=0; i < jl_tuple_len(t); i++) {
            if (jl_is_typevar(jl_tupleref(t,i)))
                return;
        }
    }
    // assign uid
    if (jl_is_struct_type(type) && ((jl_struct_type_t*)type)->uid==0)
        ((jl_struct_type_t*)type)->uid = jl_assign_type_uid();
    else if (jl_is_bits_type(type) && ((jl_bits_type_t*)type)->uid==0)
        ((jl_bits_type_t*)type)->uid = jl_assign_type_uid();
    jl_tuple_t *tc = ((jl_tag_type_t*)type)->name->cache;
    ((jl_tag_type_t*)type)->name->cache = jl_tuple2(type, tc);
}

void jl_cache_type_(jl_tag_type_t *type)
{
    cache_type_((jl_type_t*)type);
}

JL_CALLABLE(jl_f_tuple);
JL_CALLABLE(jl_f_ctor_trampoline);

static jl_type_t *inst_type_w_(jl_value_t *t, jl_value_t **env, size_t n,
                               jl_tuple_t *stack)
{
    jl_tuple2_t top;
    size_t i;
    if (n == 0) return (jl_type_t*)t;
    if (jl_is_typevar(t)) {
        for(i=0; i < n; i++) {
            if (env[i*2] == t)
                return (jl_type_t*)env[i*2+1];
        }
        return (jl_type_t*)t;
    }
    if (jl_is_tuple(t)) {
        jl_tuple_t *p = (jl_tuple_t*)t;
        jl_tuple_t *nt = jl_alloc_tuple(jl_tuple_len(p));
        JL_GC_PUSH(&nt);
        for(i=0; i < jl_tuple_len(p); i++) {
            jl_tupleset(nt, i, (jl_value_t*)inst_type_w_(jl_tupleref(p,i), env, n, stack));
        }
        JL_GC_POP();
        return (jl_type_t*)nt;
    }
    if (jl_is_union_type(t)) {
        jl_tuple_t *tw = (jl_tuple_t*)inst_type_w_((jl_value_t*)((jl_uniontype_t*)t)->types,
                                                   env, n, stack);
        JL_GC_PUSH(&tw);
        jl_type_t *res = (jl_type_t*)jl_new_uniontype(tw);
        JL_GC_POP();
        return res;
    }
    if (jl_is_some_tag_type(t)) {
        jl_tag_type_t *tt = (jl_tag_type_t*)t;
        jl_tuple_t *tp = tt->parameters;
        if (jl_is_null(tp))
            return (jl_type_t*)t;
        jl_typename_t *tn = tt->name;
        jl_value_t *tc = tn->primary;
        jl_type_t *result;
        size_t ntp = jl_tuple_len(tp);
        assert(ntp == jl_tuple_len(((jl_tag_type_t*)tc)->parameters));
        jl_value_t **iparams = (jl_value_t**)alloca((ntp+2) * sizeof(void*));
        for(i=0; i < ntp+2; i++) iparams[i] = NULL;
        jl_value_t **rt1 = &iparams[ntp+0]; // some extra gc roots
        jl_value_t **rt2 = &iparams[ntp+1];
        int cacheable = 1, isabstract = 0;
        JL_GC_PUSHARGS(iparams, ntp+2);
        for(i=0; i < ntp; i++) {
            jl_value_t *elt = jl_tupleref(tp, i);
            if (elt == t) {
                iparams[i] = t;
            }
            else {
                iparams[i] = (jl_value_t*)inst_type_w_(elt, env, n, stack);
                jl_value_t *tv =
                    jl_tupleref(((jl_tag_type_t*)tc)->parameters, i);
                if (jl_is_typevar(tv) && !jl_is_typevar(iparams[i])) {
                    // TODO: Undef should not be special here; fix.
                    // maybe introduce Top == Union(Any,Undef), and make this
                    // the default upper bound.
                    if (!jl_subtype(iparams[i], tv, 0)) {
                        jl_type_error_rt(tt->name->name->name,
                                         ((jl_tvar_t*)tv)->name->name,
                                         ((jl_tvar_t*)tv)->ub,
                                         iparams[i]);
                    }
                }
            }
            if (jl_is_typevar(iparams[i]))
                isabstract = 1;
            if (jl_has_typevars_(iparams[i],0))
                cacheable = 0;
        }

        // if an identical instantiation is already in process somewhere
        // up the stack, return it. this computes a fixed point for
        // recursive types.
        jl_type_t *lkup = lookup_type(stack, tn, iparams, ntp);
        if (lkup != NULL) { result = lkup; goto done_inst_tt; }

        // check type cache
        if (cacheable) {
            lkup = lookup_type(tn->cache, tn, iparams, ntp);
            if (lkup != NULL) { result = lkup; goto done_inst_tt; }
        }

        // always use original type constructor
        if (tc != t) {
            //(tc != NULL && tc != t)
            result = (jl_type_t*)jl_apply_type_(tc, iparams, ntp);
            goto done_inst_tt;
        }

        // move array of instantiated parameters to heap; we need to keep it
        jl_tuple_t *iparams_tuple = jl_alloc_tuple_uninit(ntp);
        for(i=0; i < ntp; i++)
            jl_tupleset(iparams_tuple, i, iparams[i]);
        *rt1 = (jl_value_t*)iparams_tuple;
        if (jl_is_tag_type(t)) {
            jl_tag_type_t *tagt = (jl_tag_type_t*)t;
            jl_tag_type_t *ntt =
                (jl_tag_type_t*)newobj((jl_type_t*)jl_tag_kind, TAG_TYPE_NW);
            *rt2 = (jl_value_t*)ntt;
            top.data[0] = (jl_value_t*)ntt;
            top.data[1] = (jl_value_t*)stack;
            stack = (jl_tuple_t*)&top;
            ntt->name = tn;
            // temporarily initialize all fields so object is valid during
            // allocation of other objects (possible GC)
            ntt->fptr = NULL;
            ntt->env = NULL;
            ntt->linfo = NULL;
            ntt->super = jl_any_type;
            ntt->parameters = iparams_tuple;
            ntt->super = (jl_tag_type_t*)inst_type_w_((jl_value_t*)tagt->super,env,n,stack);
            if (cacheable) cache_type_((jl_type_t*)ntt);
            result = (jl_type_t*)ntt;
        }
        else if (jl_is_bits_type(t)) {
            jl_bits_type_t *bitst = (jl_bits_type_t*)t;
            jl_bits_type_t *nbt =
                (jl_bits_type_t*)newobj((jl_type_t*)jl_bits_kind, BITS_TYPE_NW);
            *rt2 = (jl_value_t*)nbt;
            top.data[0] = (jl_value_t*)nbt;
            top.data[1] = (jl_value_t*)stack;
            stack = (jl_tuple_t*)&top;
            nbt->name = tn;
            nbt->fptr = NULL;
            nbt->env = NULL;
            nbt->linfo = NULL;
            nbt->super = jl_any_type;
            nbt->parameters = iparams_tuple;
            nbt->nbits = bitst->nbits;
            nbt->bnbits = bitst->bnbits;
            nbt->super = (jl_tag_type_t*)inst_type_w_((jl_value_t*)bitst->super, env, n, stack);
            nbt->uid = 0;
            if (cacheable) cache_type_((jl_type_t*)nbt);
            result = (jl_type_t*)nbt;
        }
        else {
            assert(jl_is_struct_type(t));
            jl_struct_type_t *st = (jl_struct_type_t*)t;
            // create and initialize new struct type
            jl_struct_type_t *nst =
                (jl_struct_type_t*)newobj((jl_type_t*)jl_struct_kind,
                                          STRUCT_TYPE_NW);
            *rt2 = (jl_value_t*)nst;
            // associate these parameters with the new struct type on
            // the stack, in case one of its field types references it.
            top.data[0] = (jl_value_t*)nst;
            top.data[1] = (jl_value_t*)stack;
            stack = (jl_tuple_t*)&top;
            nst->name = tn;
            nst->super = jl_any_type;
            nst->parameters = iparams_tuple;
            nst->names = st->names;
            nst->types = jl_null; // to be filled in below
            if (isabstract)
                nst->fptr = jl_f_no_function;
            else
                nst->fptr = jl_f_ctor_trampoline;
            nst->env = (jl_value_t*)nst;
            nst->linfo = NULL;
            nst->ctor_factory = st->ctor_factory;
            nst->instance = NULL;
            nst->uid = 0;
            nst->super = (jl_tag_type_t*)inst_type_w_((jl_value_t*)st->super, env,n,stack);
            jl_tuple_t *ftypes = st->types;
            if (ftypes != NULL) {
                // recursively instantiate the types of the fields
                jl_tuple_t *nftypes = jl_alloc_tuple(jl_tuple_len(ftypes));
                nst->types = nftypes;
                for(i=0; i < jl_tuple_len(ftypes); i++) {
                    jl_tupleset(nftypes, i,
                                (jl_value_t*)inst_type_w_(jl_tupleref(ftypes,i),
                                                          env,n,stack));
                }
            }
            if (cacheable) cache_type_((jl_type_t*)nst);
            result = (jl_type_t*)nst;
        }
    done_inst_tt:
        JL_GC_POP();
        return result;
    }
    return (jl_type_t*)t;
}

jl_type_t *jl_instantiate_type_with(jl_type_t *t, jl_value_t **env, size_t n)
{
    return inst_type_w_((jl_value_t*)t, env, n, jl_null);
}

jl_tag_type_t *jl_wrap_Type(jl_value_t *t)
{
    jl_value_t *env[2];
    env[0] = jl_tparam0(jl_type_type);
    env[1] = t;
    return (jl_tag_type_t*)
        jl_instantiate_type_with((jl_type_t*)jl_type_type, env, 1);
}

void jl_reinstantiate_inner_types(jl_tag_type_t *t)
{
    jl_tuple2_t top;
    top.data[0] = (jl_value_t*)t;
    top.data[1] = (jl_value_t*)jl_null;
    size_t n = jl_tuple_len(t->parameters);
    jl_value_t **env = alloca(n*2*sizeof(void*));
    for(int i=0; i < n; i++) {
        env[i*2] = jl_tupleref(t->parameters,i);
        env[i*2+1] = env[i*2];
    }
    t->super = (jl_tag_type_t*)inst_type_w_((jl_value_t*)t->super, env, n, (jl_tuple_t*)&top);
    if (jl_is_struct_type(t)) {
        jl_struct_type_t *st = (jl_struct_type_t*)t;
        st->types = (jl_tuple_t*)inst_type_w_((jl_value_t*)st->types, env, n, (jl_tuple_t*)&top);
    }
}

static int jl_subtype_le(jl_value_t *a,jl_value_t *b,int ta,int morespecific,
                         int invariant);

static int jl_tuple_subtype_(jl_value_t **child, size_t cl,
                             jl_value_t **parent, size_t pl, int ta,
                             int morespecific, int invariant)
{
    size_t ci=0, pi=0;
    int mode = 0;
    while(1) {
        int cseq = !ta && (ci<cl) && jl_is_seq_type(child[ci]);
        int pseq = (pi<pl) && jl_is_seq_type(parent[pi]);
        if ((!morespecific||mode) && cseq && !pseq)
            return mode;
        if (ci >= cl)
            return (pi>=pl || pseq);
        if (pi >= pl)
            return 0;
        jl_value_t *ce = child[ci];
        jl_value_t *pe = parent[pi];
        if (cseq) ce = jl_tparam0(ce);
        if (pseq) pe = jl_tparam0(pe);

        if (!jl_subtype_le(ce, pe, ta, morespecific, invariant))
            return 0;

        if (morespecific) {
            // stop as soon as one element is strictly more specific
            if (!(jl_types_equal(ce,pe) ||
                  (jl_is_typevar(pe) &&
                   jl_types_equal(ce,((jl_tvar_t*)pe)->ub)))) {
                mode = 1;
                assert(!ta);
                // here go into a different mode where we return 1
                // if the only reason the child is not more specific is
                // argument count (i.e. ...)
            }
        }

        if (cseq && pseq) return 1;
        if (!cseq) ci++;
        if (!pseq) pi++;
    }
    return 0;
}

int jl_tuple_subtype(jl_value_t **child, size_t cl,
                     jl_value_t **parent, size_t pl, int ta, int morespecific)
{
    return jl_tuple_subtype_(child, cl, parent, pl, ta, morespecific, 0);
}

static int tuple_all_subtype(jl_tuple_t *t, jl_value_t *super,
                             int ta, int morespecific, int invariant)
{
    size_t ci;
    for(ci=0; ci < jl_tuple_len(t); ci++) {
        jl_value_t *ce = jl_tupleref(t,ci);
        if (!ta && jl_is_seq_type(ce))
            ce = jl_tparam0(ce);
        if (!jl_subtype_le(ce, super, ta, morespecific, invariant))
            return 0;
    }
    return 1;
}

/*
ta specifies whether typeof() should be implicitly applied to a.
this is used for tuple types to avoid allocating them explicitly.
morespecific means we only care whether a is more specific than b,
not necessarily a strict subtype
*/
static int jl_subtype_le(jl_value_t *a, jl_value_t *b, int ta, int morespecific,
                         int invariant)
{
    if (!ta&&jl_is_typector(a)) a = (jl_value_t*)((jl_typector_t*)a)->body;
    if (jl_is_typector(b)) b = (jl_value_t*)((jl_typector_t*)b)->body;
    if (ta) {
        if (jl_is_type_type(b)) {
            jl_value_t *bp = jl_tparam0(b);
            return jl_subtype_le((jl_value_t*)jl_typeof(a),
                                 (jl_value_t*)jl_type_type, 0, morespecific, 0) &&
                jl_subtype_le(a, bp, 0, morespecific, 1);
        }
    }
    else if (a == b) {
        // None <: None
        return 1;
    }
    size_t i, j;
    if (jl_is_tuple(a)) {
        if ((jl_tuple_t*)b == jl_tuple_type) return 1;
        if (jl_is_tag_type(b) &&
            ((jl_tag_type_t*)b)->name == jl_ntuple_typename) {
            jl_tuple_t *tp = ((jl_tag_type_t*)b)->parameters;
            return tuple_all_subtype((jl_tuple_t*)a,
                                     jl_tupleref(tp,1), ta, morespecific,
                                     invariant);
        }
        if (jl_is_tuple(b)) {
            return jl_tuple_subtype_(&jl_tupleref(a,0),jl_tuple_len(a),
                                     &jl_tupleref(b,0),jl_tuple_len(b),
                                     ta, morespecific,invariant);
        }
    }

    if (!ta && jl_is_union_type(a)) {
        jl_tuple_t *ap = ((jl_uniontype_t*)a)->types;
        if (morespecific) {
            // Union a is more specific than b if some element of a is
            // more specific than b, and b is not more specific than any
            // element of a.
            for(i=0; i < jl_tuple_len(ap); i++) {
                if (jl_subtype_le(jl_tupleref(ap,i), b, 0, 1, invariant) &&
                    !jl_subtype_le(b, jl_tupleref(ap,i), 0, 1, invariant)) {
                    for(j=0; j < jl_tuple_len(ap); j++) {
                        if (jl_subtype_le(b, jl_tupleref(ap,j), 0, 1, invariant) &&
                            !jl_subtype_le(jl_tupleref(ap,j), b, 0, 1, invariant)) {
                            return 0;
                        }
                    }
                    return 1;
                }
            }
            if (!jl_is_typevar(b))
                return 0;
        }
        else {
            if (invariant && !jl_is_typevar(b)) {
                return jl_subtype_le(a,b,0,0,0) && jl_subtype_le(b,a,0,0,0);
            }
            for(i=0; i < jl_tuple_len(ap); i++) {
                if (!jl_subtype_le(jl_tupleref(ap,i), b, 0, morespecific,
                                   invariant))
                    return 0;
            }
        }
        return 1;
    }

    if (jl_is_union_type(b)) {
        if (invariant)
            return 0;
        jl_tuple_t *bp = ((jl_uniontype_t*)b)->types;
        for(i=0; i < jl_tuple_len(bp); i++) {
            if (jl_subtype_le(a, jl_tupleref(bp,i), ta, morespecific, invariant))
                return 1;
        }
        return 0;
    }

    if (ta) a = (jl_value_t*)jl_typeof(a);

    if (a == b) return 1;
    if ((a==(jl_value_t*)jl_undef_type && !jl_is_typevar(b)) ||
        b==(jl_value_t*)jl_undef_type)
        return 0;
    if (!invariant && (jl_tag_type_t*)b == jl_any_type) return 1;

    if (jl_is_some_tag_type(a) && jl_is_some_tag_type(b)) {
        if ((jl_tag_type_t*)a == jl_any_type) return 0;
        jl_tag_type_t *tta = (jl_tag_type_t*)a;
        jl_tag_type_t *ttb = (jl_tag_type_t*)b;
        int super=0;
        while (tta != (jl_tag_type_t*)jl_any_type) {
            if (tta->name == ttb->name) {
                if (super && morespecific) {
                    if (tta->name != jl_type_type->name)
                        return 1;
                }
                if (tta->name == jl_ntuple_typename) {
                    // NTuple must be covariant
                    return jl_subtype_le(jl_tupleref(tta->parameters,1),
                                         jl_tupleref(ttb->parameters,1),
                                         0, morespecific, invariant);
                }
                assert(jl_tuple_len(tta->parameters) == jl_tuple_len(ttb->parameters));
                for(i=0; i < jl_tuple_len(tta->parameters); i++) {
                    jl_value_t *apara = jl_tupleref(tta->parameters,i);
                    jl_value_t *bpara = jl_tupleref(ttb->parameters,i);
                    if (invariant && !morespecific && jl_is_typevar(bpara) &&
                        !((jl_tvar_t*)bpara)->bound) {
                        if (!jl_is_typevar(apara))
                            return 0;
                    }
                    if (!jl_subtype_le(apara, bpara, 0, morespecific, 1))
                        return 0;
                }
                return 1;
            }
            else if (invariant) {
                return 0;
            }
            tta = tta->super; super = 1;
        }
        assert(!invariant);
        if (((jl_tag_type_t*)a)->name == jl_type_type->name) {
            // Type{T} also matches >:typeof(T)
            if (!jl_is_typevar(jl_tparam0(a)))
                return jl_subtype_le(jl_tparam0(a), b, 1, morespecific, 0);
        }
        return 0;
    }

    if (jl_is_typevar(a)) {
        if (jl_is_typevar(b)) {
            return
                jl_subtype_le((jl_value_t*)((jl_tvar_t*)a)->ub,
                              (jl_value_t*)((jl_tvar_t*)b)->ub, 0, 0, 0) &&
                jl_subtype_le((jl_value_t*)((jl_tvar_t*)b)->lb,
                              (jl_value_t*)((jl_tvar_t*)a)->lb, 0, 0, 0);
        }
        if (invariant) {
            return 0;
            //return
            // jl_subtype_le((jl_value_t*)((jl_tvar_t*)a)->ub, b, 0, 0, 1) &&
            // jl_subtype_le((jl_value_t*)((jl_tvar_t*)a)->lb, b, 0, 0, 1);
        }
        return jl_subtype_le((jl_value_t*)((jl_tvar_t*)a)->ub, b, 0, 0, 0);
    }
    if (jl_is_typevar(b)) {
        return jl_subtype_le(a, (jl_value_t*)((jl_tvar_t*)b)->ub, 0, 0, 0) &&
            jl_subtype_le((jl_value_t*)((jl_tvar_t*)b)->lb, a, 0, 0, 0);
    }
    if ((jl_tag_type_t*)a == jl_any_type) return 0;
    if (jl_is_tuple(b)) {
        if (jl_is_tag_type(a) &&
            ((jl_tag_type_t*)a)->name == jl_ntuple_typename) {
            // only ((T>:S)...,) can be a supertype of NTuple[N,S]
            jl_tuple_t *tp = (jl_tuple_t*)b;
            jl_value_t *ntp = jl_tupleref(((jl_tag_type_t*)a)->parameters, 1);
            if (jl_tuple_len(tp) == 1 && jl_is_seq_type(jl_tupleref(tp,0))) {
                return jl_subtype_le(ntp, jl_tparam0(jl_tupleref(tp,0)),
                                     0, morespecific, invariant);
            }
        }
        return 0;
    }
    if (jl_is_tuple(a)) return 0;

    if (jl_is_long(a)) {
        if (jl_is_long(b))
            return (jl_unbox_long(a)==jl_unbox_long(b));
        return 0;
    }
    if (jl_is_long(b)) return 0;
    return 0;
}

int jl_subtype(jl_value_t *a, jl_value_t *b, int ta)
{
    return jl_subtype_le(a, b, ta, 0, 0);
}

int jl_subtype_invariant(jl_value_t *a, jl_value_t *b, int ta)
{
    return jl_subtype_le(a, b, ta, 0, 1);
}

int jl_type_morespecific(jl_value_t *a, jl_value_t *b, int ta)
{
    return jl_subtype_le(a, b, ta, 1, 0);
}

static jl_value_t *type_match_(jl_value_t *child, jl_value_t *parent,
                               cenv_t *env, int morespecific, int invariant);

static jl_value_t *tuple_match(jl_tuple_t *child, jl_tuple_t *parent,
                               cenv_t *env, int morespecific, int invariant)
{
    size_t ci=0, pi=0;
    size_t cl = jl_tuple_len(child);
    size_t pl = jl_tuple_len(parent);
    while(1) {
        int cseq = (ci<cl) && jl_is_seq_type(jl_tupleref(child,ci));
        int pseq = (pi<pl) && jl_is_seq_type(jl_tupleref(parent,pi));
        if (ci >= cl)
            return (pi>=pl || pseq) ? jl_true : jl_false;
        if (cseq && !pseq)
            return jl_false;
        if (pi >= pl)
            return jl_false;
        jl_value_t *ce = jl_tupleref(child,ci);
        jl_value_t *pe = jl_tupleref(parent,pi);
        if (cseq) ce = jl_tparam0(ce);
        if (pseq) pe = jl_tparam0(pe);

        int n = env->n;
        if (type_match_(ce, pe, env, morespecific, invariant) == jl_false)
            { env->n = n; return jl_false; }

        if (cseq && pseq) return jl_true;
        if (!cseq) ci++;
        if (!pseq) pi++;
    }
    return jl_true;
}

static jl_value_t *type_match_(jl_value_t *child, jl_value_t *parent,
                               cenv_t *env, int morespecific, int invariant)
{
    jl_value_t *tmp, *tmp2;
    if (jl_is_typector(child))
        child = (jl_value_t*)((jl_typector_t*)child)->body;
    if (jl_is_typector(parent))
        parent = (jl_value_t*)((jl_typector_t*)parent)->body;
    size_t i, j;
    if (jl_is_typevar(parent)) {
        // make sure type is within this typevar's bounds
        if (!jl_subtype_le(child, parent, 0, 0, 0))
            return jl_false;
        if (!match_intersection_mode) {
            if (!((jl_tvar_t*)parent)->bound) return jl_true;
        }
        for(int i=0; i < env->n; i+=2) {
            if (env->data[i] == (jl_value_t*)parent) {
                jl_value_t *pv = env->data[i+1];
                if (jl_is_typevar(pv) && jl_is_typevar(child)) {
                    if (pv == (jl_value_t*)child)
                        return jl_true;
                    return jl_false;
                }
                if (morespecific) {
                    if (jl_subtype(child, pv, 0)) {
                        return jl_true;
                    }
                    else if (jl_subtype(pv, child, 0)) {
                        env->data[i+1] = (jl_value_t*)child;
                        return jl_true;
                    }
                }
                else {
                    if (type_eqv_(child, pv))
                        return jl_true;
                }
                return jl_false;
            }
        }
        extend(parent, child, env);
        return jl_true;
    }

    if (child == parent) return jl_true;

    if (jl_is_typevar(child)) {
        if (!invariant) {
            if (jl_subtype_le(child, parent, 0, morespecific, 0))
                return jl_true;
        }
        return jl_false;
    }
    if (jl_is_long(child)) {
        if (jl_is_long(parent)) {
            if (jl_unbox_long((jl_value_t*)child) ==
                jl_unbox_long((jl_value_t*)parent))
                return jl_true;
        }
        return jl_false;
    }
    if (jl_is_long(parent))
        return jl_false;
    if (!invariant && parent == (jl_value_t*)jl_any_type)
        return jl_true;
    if (child == (jl_value_t*)jl_any_type) return jl_false;

    if (jl_is_union_type(child)) {
        jl_tuple_t *t = ((jl_uniontype_t*)child)->types;
        if (morespecific) {
            cenv_t tenv;
            for(i=0; i < jl_tuple_len(t); i++) {
                int n = env->n;
                tmp = type_match_(jl_tupleref(t,i), parent, env, 1, invariant);
                if (tmp != jl_false) {
                    tenv.n = 0;
                    tmp2 = type_match_(parent, jl_tupleref(t,i), &tenv, 1,
                                       invariant);
                    if (tmp2 == jl_false) {
                        n = env->n;
                        for(j=0; j < jl_tuple_len(t); j++) {
                            tenv.n = 0;
                            env->n = n;
                            if (type_match_(parent, jl_tupleref(t,j),
                                            &tenv, 1, invariant) != jl_false &&
                                type_match_(jl_tupleref(t,j), parent,
                                            env, 1, invariant) == jl_false) {
                                env->n = n;
                                return jl_false;
                            }
                        }
                        return jl_true;
                    }
                }
                else {
                    env->n = n;
                }
            }
            return jl_false;
        }
        else {
            for(i=0; i < jl_tuple_len(t); i++) {
                int n = env->n;
                if (type_match_(jl_tupleref(t,i), parent, env, morespecific,
                                invariant) == jl_false)
                    { env->n = n; return jl_false; }
            }
            if (invariant && child == (jl_value_t*)jl_bottom_type &&
                !jl_is_typevar(parent))
                return jl_false;
        }
        return jl_true;
    }
    if (jl_is_union_type(parent)) {
        jl_tuple_t *t = ((jl_uniontype_t*)parent)->types;
        int n = env->n;
        for(i=0; i < jl_tuple_len(t); i++) {
            env->n = n;
            if (type_match_(child, jl_tupleref(t,i), env,
                            morespecific, invariant) != jl_false)
                return jl_true;
        }
        return jl_false;
    }

    if (jl_is_tuple(child)) {
        if (jl_is_tag_type(parent) &&
            ((jl_tag_type_t*)parent)->name == jl_ntuple_typename) {
            jl_tuple_t *tp = ((jl_tag_type_t*)parent)->parameters;
            size_t alen = jl_tuple_len(child);
            // if child has a sequence type, there exists no N such that
            // NTuple[N,Any] could be its supertype.
            if (alen>0 && jl_is_seq_type(jl_tupleref(child,alen-1)))
                return jl_false;
            jl_value_t *nt_len = jl_tupleref(tp,0);
            jl_value_t *childlen = jl_box_long(jl_tuple_len(child));
            if (jl_is_typevar(nt_len)) {
                int n = env->n;
                if (type_match_(childlen, nt_len, env, morespecific,
                                invariant) == jl_false)
                    { env->n = n; return jl_false; }
            }
            else {
                return jl_false;
            }
            jl_value_t *p_seq = (jl_value_t*)jl_tuple1(jl_tupleref(tp,1));
            JL_GC_PUSH(&p_seq);
            p_seq = (jl_value_t*)jl_apply_type((jl_value_t*)jl_seq_type,
                                               (jl_tuple_t*)p_seq);
            p_seq = (jl_value_t*)jl_tuple1(p_seq);
            tmp = tuple_match((jl_tuple_t*)child, (jl_tuple_t*)p_seq,
                              env, morespecific, invariant);
            JL_GC_POP();
            return tmp;
        }

        if (jl_is_tuple(parent)) {
            return tuple_match((jl_tuple_t*)child, (jl_tuple_t*)parent, env,
                               morespecific, invariant);
        }
        return jl_false;
    }
    if (jl_is_tuple(parent)) {
        if (jl_is_tag_type(child) &&
            ((jl_tag_type_t*)child)->name == jl_ntuple_typename) {
            // only ((T>:S)...,) can be a supertype of NTuple[N,S]
            jl_tuple_t *tp = (jl_tuple_t*)parent;
            jl_value_t *ntp = jl_tupleref(((jl_tag_type_t*)child)->parameters,
                                          1);
            if (jl_tuple_len(tp) == 1 && jl_is_seq_type(jl_tupleref(tp,0))) {
                return type_match_(ntp, jl_tparam0(jl_tupleref(tp,0)),
                                   env, morespecific, invariant);
            }
        }
        return jl_false;
    }

    assert(jl_is_some_tag_type(child));
    assert(jl_is_some_tag_type(parent));
    jl_tag_type_t *tta = (jl_tag_type_t*)child;
    jl_tag_type_t *ttb = (jl_tag_type_t*)parent;
    int super = 0;
    while (tta != (jl_tag_type_t*)jl_any_type) {
        if (tta->name == ttb->name) {
            if (super && morespecific)
                return jl_true;
            assert(jl_tuple_len(tta->parameters) == jl_tuple_len(ttb->parameters));
            for(i=0; i < jl_tuple_len(tta->parameters); i++) {
                int n = env->n;
                if (type_match_(jl_tupleref(tta->parameters,i),
                                jl_tupleref(ttb->parameters,i),
                                env, morespecific, 1) == jl_false)
                    { env->n = n; return jl_false; }
            }
            return jl_true;
        }
        else if (invariant) {
            return jl_false;
        }
        tta = tta->super; super = 1;
    }
    assert(!invariant);
    if (((jl_tag_type_t*)child)->name == jl_type_type->name &&
        ttb->name != jl_type_type->name) {
        // Type{T} also matches >:typeof(T)
        return type_match_(jl_full_type(jl_tparam0(child)),
                           parent, env, morespecific, 0);
    }
    return jl_false;
}

/*
typically a is a concrete type and b is a type containing typevars.
this function tries to find a typevar assignment such that "a" is a subtype
of "b".
returns a tuple of (typevar,type,...) pairs.
used to infer static parameter values in generic method definitions.
*/
jl_value_t *jl_type_match_(jl_value_t *a, jl_value_t *b, int morespecific)
{
    cenv_t env; env.n = 0; memset(env.data, 0, sizeof(env.data));
    JL_GC_PUSHARGS(env.data, sizeof(env.data)/sizeof(void*));
    jl_value_t *m = type_match_(a, b, &env, morespecific, 0);
    if (m != jl_false) {
        m = (jl_value_t*)jl_alloc_tuple_uninit(env.n);
        for(int i=0; i < env.n; i++) {
            jl_tupleset(m, i, env.data[i]);
        }
    }
    JL_GC_POP();
    return m;
}

jl_value_t *jl_type_match(jl_value_t *a, jl_value_t *b)
{
    return jl_type_match_(a, b, 0);
}

jl_value_t *jl_type_match_morespecific(jl_value_t *a, jl_value_t *b)
{
    return jl_type_match_(a, b, 1);
}

// initialization -------------------------------------------------------------

jl_tvar_t *jl_new_typevar(jl_sym_t *name, jl_value_t *lb, jl_value_t *ub)
{
    jl_tvar_t *tv = (jl_tvar_t*)newobj((jl_type_t*)jl_tvar_type, 4);
    tv->name = name;
    tv->lb = lb;
    tv->ub = ub;
    tv->bound = 0;
    return tv;
}

static jl_tvar_t *tvar(const char *name)
{
    return jl_new_typevar(jl_symbol(name), (jl_value_t*)jl_bottom_type,
                          (jl_value_t*)jl_any_type);
}

extern void jl_init_int32_int64_cache(void);

void jl_init_types(void)
{
    // create base objects
    jl_struct_kind = (jl_struct_type_t*)newobj(NULL, STRUCT_TYPE_NW);
    jl_struct_kind->type = (jl_type_t*)jl_struct_kind;
    jl_typename_type = (jl_struct_type_t*)newobj((jl_type_t*)jl_struct_kind, STRUCT_TYPE_NW);
    jl_sym_type = (jl_struct_type_t*)newobj((jl_type_t*)jl_struct_kind, STRUCT_TYPE_NW);
    jl_symbol_type = jl_sym_type;

    jl_tuple_type = jl_alloc_tuple(1);
    jl_tuple_type->type = (jl_type_t*)jl_tuple_type;

    jl_null = (jl_tuple_t*)newobj((jl_type_t*)jl_tuple_type, 1);
    jl_tuple_set_len_unsafe(jl_null, 0);
    jl_nothing = (jl_value_t*)jl_null; // for bootstrapping

    jl_tag_kind = jl_new_struct_type(jl_symbol("AbstractKind"), NULL,
                                     jl_null, jl_null, jl_null);
    jl_tag_type_type = jl_tag_kind;

    jl_any_type = jl_new_tagtype((jl_value_t*)jl_symbol("Any"), NULL, jl_null);
    jl_any_type->super = jl_any_type;
    jl_type_type = jl_new_tagtype((jl_value_t*)jl_symbol("Type"), jl_any_type, jl_null);

    jl_tag_kind->super = jl_type_type;
    jl_tag_kind->names = jl_tuple(6, jl_symbol(""),jl_symbol(""),jl_symbol(""),
                                  jl_symbol("name"), jl_symbol("super"),
                                  jl_symbol("parameters"));
    jl_tag_kind->types = jl_tuple(6, jl_any_type, jl_any_type, jl_any_type,
                                  jl_typename_type, jl_type_type,
                                  jl_tuple_type);
    jl_tag_kind->fptr = jl_f_no_function;

    // initialize them. lots of cycles.
    jl_struct_kind->name = jl_new_typename(jl_symbol("CompositeKind"));
    jl_struct_kind->name->primary = (jl_value_t*)jl_struct_kind;
    jl_struct_kind->super = (jl_tag_type_t*)jl_type_type;
    jl_struct_kind->parameters = jl_null;
    jl_struct_kind->names = jl_tuple(10, jl_symbol(""),
                                     jl_symbol("env"), jl_symbol("code"),
                                     jl_symbol("name"), jl_symbol("super"),
                                     jl_symbol("parameters"),
                                     jl_symbol("names"), jl_symbol("types"),
                                     jl_symbol(""), jl_symbol(""));
    jl_struct_kind->types = jl_tuple(10, jl_any_type, jl_any_type, jl_any_type,
                                     jl_typename_type, jl_type_type,
                                     jl_tuple_type, jl_tuple_type,
                                     jl_tuple_type, jl_any_type, jl_any_type);
    jl_struct_kind->fptr = jl_f_no_function;
    jl_struct_kind->env = (jl_value_t*)jl_null;
    jl_struct_kind->linfo = NULL;
    jl_struct_kind->ctor_factory = NULL;
    jl_struct_kind->instance = NULL;
    jl_struct_kind->uid = jl_assign_type_uid();

    jl_typename_type->name = jl_new_typename(jl_symbol("TypeName"));
    jl_typename_type->name->primary = (jl_value_t*)jl_typename_type;
    jl_typename_type->super = jl_any_type;
    jl_typename_type->parameters = jl_null;
    jl_typename_type->names = jl_tuple(3, jl_symbol("name"), jl_symbol(""),
                                       jl_symbol(""));
    jl_typename_type->types = jl_tuple(3, jl_sym_type, jl_type_type,
                                       jl_tuple_type);
    jl_typename_type->uid = jl_assign_type_uid();
    jl_typename_type->fptr = jl_f_no_function;
    jl_typename_type->env = (jl_value_t*)jl_null;
    jl_typename_type->linfo = NULL;
    jl_typename_type->ctor_factory = NULL;
    jl_typename_type->instance = NULL;

    jl_sym_type->name = jl_new_typename(jl_symbol("Symbol"));
    jl_sym_type->name->primary = (jl_value_t*)jl_sym_type;
    jl_sym_type->super = jl_any_type;
    jl_sym_type->parameters = jl_null;
    jl_sym_type->names = jl_null;
    jl_sym_type->types = jl_null;
    jl_sym_type->fptr = jl_f_no_function;
    jl_sym_type->env = (jl_value_t*)jl_null;
    jl_sym_type->linfo = NULL;
    jl_sym_type->ctor_factory = NULL;
    jl_sym_type->instance = NULL;
    jl_sym_type->uid = jl_assign_type_uid();

    // now they can be used to create the remaining base kinds and types
    jl_union_kind = jl_new_struct_type(jl_symbol("UnionKind"),
                                       jl_type_type, jl_null,
                                       jl_tuple(1, jl_symbol("types")),
                                       jl_tuple(1, jl_tuple_type));
    jl_union_kind->fptr = jl_f_no_function;

    jl_bottom_type = (jl_type_t*)jl_new_struct(jl_union_kind, jl_null);

    jl_bits_kind =
        jl_new_struct_type(jl_symbol("BitsKind"), jl_type_type,
                           jl_null,
                           jl_tuple(7, jl_symbol(""), jl_symbol(""),
                                    jl_symbol(""),
                                    jl_symbol("name"), jl_symbol("super"),
                                    jl_symbol("parameters"),
                                    jl_symbol("nbits")),
                           jl_tuple(7, jl_any_type, jl_any_type, jl_any_type,
                                    jl_typename_type, jl_type_type,
                                    jl_tuple_type, jl_any_type));
    // cannot be created with normal constructor due to hidden fields
    jl_bits_kind->fptr = jl_f_no_function;
    
    jl_tvar_type = jl_new_struct_type(jl_symbol("TypeVar"),
                                      jl_any_type, jl_null,
                                      jl_tuple(3, jl_symbol("name"),
                                               jl_symbol("lb"),
                                               jl_symbol("ub")),
                                      jl_tuple(3, jl_sym_type, jl_type_type,
                                               jl_type_type));
    jl_tvar_type->fptr = jl_f_typevar;

    jl_undef_type = jl_new_tagtype((jl_value_t*)jl_symbol("Undef"),
                                   jl_any_type, jl_null);

    jl_top_type = jl_new_struct(jl_union_kind,
                                jl_tuple2(jl_any_type, jl_undef_type));

    jl_tvar_t *tttvar = jl_new_typevar(jl_symbol("T"),
                                       (jl_value_t*)jl_bottom_type,
                                       jl_top_type);
    jl_type_type->parameters = jl_tuple(1, tttvar);

    jl_tuple_t *tv;

    tv = jl_tuple1(tvar("T"));
    jl_seq_type = jl_new_tagtype((jl_value_t*)jl_symbol("..."),
                                 jl_any_type, tv);

    jl_tupleset(jl_tuple_type, 0,
                (jl_value_t*)jl_apply_type((jl_value_t*)jl_seq_type,
                                           jl_tuple(1,jl_any_type)));

    tv = jl_tuple2(tvar("N"), tvar("T"));
    jl_ntuple_type = jl_new_tagtype((jl_value_t*)jl_symbol("NTuple"),
                                    jl_any_type, tv);
    jl_ntuple_typename = jl_ntuple_type->name;

    // non-primitive definitions follow
    jl_int32_type = NULL;
    jl_int32_type = jl_new_bits_type((jl_value_t*)jl_symbol("Int32"),
                                     jl_any_type, jl_null, 32);
    jl_int64_type = NULL;
    jl_int64_type = jl_new_bits_type((jl_value_t*)jl_symbol("Int64"),
                                     jl_any_type, jl_null, 64);
    jl_init_int32_int64_cache();
    jl_int32_type->bnbits = jl_box_int32(32);
    jl_int64_type->bnbits = jl_box_int32(64);
    jl_tupleset(jl_bits_kind->types, 3, (jl_value_t*)jl_int32_type);

    jl_bool_type = NULL;
    jl_bool_type = jl_new_bits_type((jl_value_t*)jl_symbol("Bool"),
                                    jl_any_type, jl_null, 8);
    jl_false = jl_box8(jl_bool_type, 0);
    jl_true = jl_box8(jl_bool_type, 1);

    jl_method_type =
        jl_new_struct_type(jl_symbol("Method"), jl_any_type, jl_null,
                           jl_tuple(6, jl_symbol("sig"), jl_symbol("va"),
                                    jl_symbol("tvars"), jl_symbol("func"),
                                    jl_symbol("invokes"), jl_symbol("next")),
                           jl_tuple(6, jl_tuple_type, jl_bool_type,
                                    jl_tuple_type, jl_function_type,
                                    jl_any_type, jl_any_type));
    jl_method_type->fptr = jl_f_no_function;

    jl_methtable_type =
        jl_new_struct_type(jl_symbol("MethodTable"), jl_any_type, jl_null,
                           jl_tuple(6, jl_symbol("name"), jl_symbol("defs"),
                                    jl_symbol("cache"), jl_symbol("cache_arg1"),
                                    jl_symbol("cache_targ"),
                                    jl_symbol("max_args")),
                           jl_tuple(6, jl_sym_type, jl_any_type, jl_any_type,
                                    jl_any_type, jl_any_type, jl_long_type));
    jl_methtable_type->fptr = jl_f_no_function;

    tv = jl_tuple2(tvar("T"), tvar("N"));
    jl_abstractarray_type = jl_new_tagtype((jl_value_t*)jl_symbol("AbstractArray"),
                                           jl_any_type, tv);

    tv = jl_tuple2(tvar("T"), tvar("N"));
    jl_array_type =
        jl_new_struct_type(jl_symbol("Array"),
                           (jl_tag_type_t*)
                           jl_apply_type((jl_value_t*)jl_abstractarray_type, tv),
                           tv,
                           jl_null, jl_null);
    jl_array_typename = jl_array_type->name;
    jl_array_type->linfo = NULL;
    jl_initialize_generic_function((jl_function_t*)jl_array_type,
                                   jl_array_typename->name);

    jl_array_any_type =
        (jl_type_t*)jl_apply_type((jl_value_t*)jl_array_type,
                                  jl_tuple(2, jl_any_type,
                                           jl_box_long(1)));

    jl_expr_type =
        jl_new_struct_type(jl_symbol("Expr"),
                           jl_any_type, jl_null,
                           jl_tuple(3, jl_symbol("head"), jl_symbol("args"),
                                    jl_symbol("typ")),
                           jl_tuple(3, jl_sym_type, jl_array_any_type,
                                    jl_any_type));
    jl_expr_type->fptr = jl_f_new_expr;

    jl_linenumbernode_type =
        jl_new_struct_type(jl_symbol("LineNumberNode"), jl_any_type, jl_null,
                           jl_tuple(1, jl_symbol("line")),
                           jl_tuple(1, jl_long_type));

    jl_labelnode_type =
        jl_new_struct_type(jl_symbol("LabelNode"), jl_any_type, jl_null,
                           jl_tuple(1, jl_symbol("label")),
                           jl_tuple(1, jl_long_type));

    jl_gotonode_type =
        jl_new_struct_type(jl_symbol("GotoNode"), jl_any_type, jl_null,
                           jl_tuple(1, jl_symbol("label")),
                           jl_tuple(1, jl_long_type));

    jl_quotenode_type =
        jl_new_struct_type(jl_symbol("QuoteNode"), jl_any_type, jl_null,
                           jl_tuple(1, jl_symbol("value")),
                           jl_tuple(1, jl_any_type));

    jl_topnode_type =
        jl_new_struct_type(jl_symbol("TopNode"), jl_any_type, jl_null,
                           jl_tuple(1, jl_symbol("name")),
                           jl_tuple(1, jl_sym_type));

    jl_module_type =
        jl_new_struct_type(jl_symbol("Module"), jl_any_type, jl_null,
                           jl_tuple(2, jl_symbol("name"), jl_symbol("parent")),
                           jl_tuple(2, jl_sym_type, jl_any_type));

    jl_lambda_info_type =
        jl_new_struct_type(jl_symbol("LambdaStaticData"),
                           jl_any_type, jl_null,
                           jl_tuple(12, jl_symbol("ast"), jl_symbol("sparams"),
                                    jl_symbol("tfunc"), jl_symbol("name"),
                                    /*
jl_symbol("roots"), jl_symbol("specTypes"),
jl_symbol("unspecialized"),
jl_symbol("specializations")*/
                                    jl_symbol(""), jl_symbol(""),
                                    jl_symbol(""), jl_symbol(""),
                                    jl_symbol("inferred"),
                                    jl_symbol("file"), jl_symbol("line"),
                                    jl_symbol("module")),
                           jl_tuple(12, jl_any_type, jl_tuple_type,
                                    jl_any_type, jl_sym_type,
                                    jl_any_type, jl_tuple_type,
                                    jl_function_type, jl_array_any_type,
                                    jl_bool_type,
                                    jl_sym_type, jl_long_type,
                                    jl_module_type));
    jl_lambda_info_type->fptr = jl_f_no_function;

    jl_box_type =
        jl_new_struct_type(jl_symbol("Box"),
                           jl_any_type, jl_null,
                           jl_tuple(1, jl_symbol("contents")),
                           jl_tuple(1, jl_any_type));
    jl_box_type->fptr = jl_f_new_box;
    jl_box_typename = jl_box_type->name;
    jl_box_any_type = (jl_type_t*)jl_box_type;

    jl_typector_type =
        jl_new_struct_type(jl_symbol("TypeConstructor"),
                           jl_type_type, jl_null,
                           jl_tuple(2, jl_symbol("parameters"),
                                    jl_symbol("body")),
                           jl_tuple(2, jl_tuple_type, jl_any_type));
    jl_typector_type->fptr = jl_f_new_type_constructor;

    jl_function_type =
        jl_new_struct_type(jl_symbol("Function"), jl_any_type, jl_null,
                           jl_tuple(3, jl_symbol(""), jl_symbol("env"),
                                    jl_symbol("code")),
                           jl_tuple(3, jl_any_type, jl_any_type,
                                    jl_lambda_info_type));
    jl_function_type->fptr = jl_f_no_function;

    jl_tupleset(jl_method_type->types, 3, jl_function_type);
    jl_tupleset(jl_lambda_info_type->types, 6, jl_function_type);

    jl_bottom_func = jl_new_closure(jl_f_no_function, JL_NULL, NULL);

    jl_intrinsic_type = jl_new_bits_type((jl_value_t*)jl_symbol("IntrinsicFunction"),
                                         jl_any_type, jl_null, 32);

    tv = jl_tuple1(tvar("T"));
    jl_pointer_type =
        jl_new_bits_type((jl_value_t*)jl_symbol("Ptr"), jl_any_type, tv,
                         sizeof(void*)*8);

    // Type{T}
    jl_typetype_tvar = jl_new_typevar(jl_symbol("T"),
                                      (jl_value_t*)jl_bottom_type,
                                      jl_top_type);
    jl_typetype_type = (jl_tag_type_t*)
        jl_apply_type((jl_value_t*)jl_type_type,
                      jl_tuple(1,jl_typetype_tvar));

    jl_ANY_flag = (jl_value_t*)tvar("ANY");

    call_sym = jl_symbol("call");
    call1_sym = jl_symbol("call1");
    quote_sym = jl_symbol("quote");
    top_sym = jl_symbol("top");
    dots_sym = jl_symbol("...");
    line_sym = jl_symbol("line");
    jl_continue_sym = jl_symbol("continue");
    error_sym = jl_symbol("error");
    goto_sym = jl_symbol("goto");
    goto_ifnot_sym = jl_symbol("gotoifnot");
    label_sym = jl_symbol("label");
    return_sym = jl_symbol("return");
    lambda_sym = jl_symbol("lambda");
    macro_sym = jl_symbol("macro");
    module_sym = jl_symbol("module");
    export_sym = jl_symbol("export");
    import_sym = jl_symbol("import");
    importall_sym = jl_symbol("importall");
    assign_sym = jl_symbol("=");
    null_sym = jl_symbol("null");
    body_sym = jl_symbol("body");
    colons_sym = jl_symbol("::");
    method_sym = jl_symbol("method");
    exc_sym = jl_symbol("the_exception");
    enter_sym = jl_symbol("enter");
    leave_sym = jl_symbol("leave");
    static_typeof_sym = jl_symbol("static_typeof");
    new_sym = jl_symbol("new");
    multivalue_sym = jl_symbol("multiple_value");
    const_sym = jl_symbol("const");
    global_sym = jl_symbol("global");
    thunk_sym = jl_symbol("thunk");
    anonymous_sym = jl_symbol("anonymous");
    underscore_sym = jl_symbol("_");
    amp_sym = jl_symbol("&");
    abstracttype_sym = jl_symbol("abstract_type");
    bitstype_sym = jl_symbol("bits_type");
    compositetype_sym = jl_symbol("composite_type");
    type_goto_sym = jl_symbol("type_goto");
}
Something went wrong with that request. Please try again.