1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374
|
//
// generic.cs: Generics support
//
// Authors: Martin Baulig (martin@ximian.com)
// Miguel de Icaza (miguel@ximian.com)
//
// Licensed under the terms of the GNU GPL
//
// (C) 2001, 2002, 2003 Ximian, Inc (http://www.ximian.com)
// (C) 2004 Novell, Inc
//
using System;
using System.Reflection;
using System.Reflection.Emit;
using System.Globalization;
using System.Collections;
using System.Text;
using System.Text.RegularExpressions;
namespace Mono.CSharp {
/// <summary>
/// Abstract base class for type parameter constraints.
/// The type parameter can come from a generic type definition or from reflection.
/// </summary>
public abstract class GenericConstraints {
public abstract string TypeParameter {
get;
}
public abstract GenericParameterAttributes Attributes {
get;
}
public bool HasConstructorConstraint {
get { return (Attributes & GenericParameterAttributes.DefaultConstructorConstraint) != 0; }
}
public bool HasReferenceTypeConstraint {
get { return (Attributes & GenericParameterAttributes.ReferenceTypeConstraint) != 0; }
}
public bool HasValueTypeConstraint {
get { return (Attributes & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0; }
}
public virtual bool HasClassConstraint {
get { return ClassConstraint != null; }
}
public abstract Type ClassConstraint {
get;
}
public abstract Type[] InterfaceConstraints {
get;
}
public abstract Type EffectiveBaseClass {
get;
}
// <summary>
// Returns whether the type parameter is "known to be a reference type".
// </summary>
public virtual bool IsReferenceType {
get {
if (HasReferenceTypeConstraint)
return true;
if (HasValueTypeConstraint)
return false;
if (ClassConstraint != null) {
if (ClassConstraint.IsValueType)
return false;
if (ClassConstraint != TypeManager.object_type)
return true;
}
foreach (Type t in InterfaceConstraints) {
if (!t.IsGenericParameter)
continue;
GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
if ((gc != null) && gc.IsReferenceType)
return true;
}
return false;
}
}
// <summary>
// Returns whether the type parameter is "known to be a value type".
// </summary>
public virtual bool IsValueType {
get {
if (HasValueTypeConstraint)
return true;
if (HasReferenceTypeConstraint)
return false;
if (ClassConstraint != null) {
if (!ClassConstraint.IsValueType)
return false;
if (ClassConstraint != TypeManager.value_type)
return true;
}
foreach (Type t in InterfaceConstraints) {
if (!t.IsGenericParameter)
continue;
GenericConstraints gc = TypeManager.GetTypeParameterConstraints (t);
if ((gc != null) && gc.IsValueType)
return true;
}
return false;
}
}
}
public enum SpecialConstraint
{
Constructor,
ReferenceType,
ValueType
}
/// <summary>
/// Tracks the constraints for a type parameter from a generic type definition.
/// </summary>
public class Constraints : GenericConstraints {
string name;
ArrayList constraints;
Location loc;
//
// name is the identifier, constraints is an arraylist of
// Expressions (with types) or `true' for the constructor constraint.
//
public Constraints (string name, ArrayList constraints,
Location loc)
{
this.name = name;
this.constraints = constraints;
this.loc = loc;
}
public override string TypeParameter {
get {
return name;
}
}
public Constraints Clone ()
{
return new Constraints (name, constraints, loc);
}
GenericParameterAttributes attrs;
TypeExpr class_constraint;
ArrayList iface_constraints;
ArrayList type_param_constraints;
int num_constraints;
Type class_constraint_type;
Type[] iface_constraint_types;
Type effective_base_type;
bool resolved;
bool resolved_types;
/// <summary>
/// Resolve the constraints - but only resolve things into Expression's, not
/// into actual types.
/// </summary>
public bool Resolve (IResolveContext ec)
{
if (resolved)
return true;
iface_constraints = new ArrayList ();
type_param_constraints = new ArrayList ();
foreach (object obj in constraints) {
if (HasConstructorConstraint) {
Report.Error (401, loc,
"The new() constraint must be the last constraint specified");
return false;
}
if (obj is SpecialConstraint) {
SpecialConstraint sc = (SpecialConstraint) obj;
if (sc == SpecialConstraint.Constructor) {
if (!HasValueTypeConstraint) {
attrs |= GenericParameterAttributes.DefaultConstructorConstraint;
continue;
}
Report.Error (451, loc, "The `new()' constraint " +
"cannot be used with the `struct' constraint");
return false;
}
if ((num_constraints > 0) || HasReferenceTypeConstraint || HasValueTypeConstraint) {
Report.Error (449, loc, "The `class' or `struct' " +
"constraint must be the first constraint specified");
return false;
}
if (sc == SpecialConstraint.ReferenceType)
attrs |= GenericParameterAttributes.ReferenceTypeConstraint;
else
attrs |= GenericParameterAttributes.NotNullableValueTypeConstraint;
continue;
}
int errors = Report.Errors;
FullNamedExpression fn = ((Expression) obj).ResolveAsTypeStep (ec, false);
if (fn == null) {
if (errors != Report.Errors)
return false;
NamespaceEntry.Error_NamespaceNotFound (loc, ((Expression)obj).GetSignatureForError ());
return false;
}
TypeExpr expr;
ConstructedType cexpr = fn as ConstructedType;
if (cexpr != null) {
if (!cexpr.ResolveConstructedType (ec))
return false;
expr = cexpr;
} else
expr = ((Expression) obj).ResolveAsTypeTerminal (ec, false);
if ((expr == null) || (expr.Type == null))
return false;
// TODO: It's aleady done in ResolveAsBaseTerminal
if (!ec.GenericDeclContainer.AsAccessible (fn.Type, ec.GenericDeclContainer.ModFlags)) {
Report.SymbolRelatedToPreviousError (fn.Type);
Report.Error (703, loc,
"Inconsistent accessibility: constraint type `{0}' is less accessible than `{1}'",
fn.GetSignatureForError (), ec.GenericDeclContainer.GetSignatureForError ());
return false;
}
TypeParameterExpr texpr = expr as TypeParameterExpr;
if (texpr != null)
type_param_constraints.Add (expr);
else if (expr.IsInterface)
iface_constraints.Add (expr);
else if (class_constraint != null) {
Report.Error (406, loc,
"`{0}': the class constraint for `{1}' " +
"must come before any other constraints.",
expr.Name, name);
return false;
} else if (HasReferenceTypeConstraint || HasValueTypeConstraint) {
Report.Error (450, loc, "`{0}': cannot specify both " +
"a constraint class and the `class' " +
"or `struct' constraint", expr.GetSignatureForError ());
return false;
} else
class_constraint = expr;
num_constraints++;
}
ArrayList list = new ArrayList ();
foreach (TypeExpr iface_constraint in iface_constraints) {
foreach (Type type in list) {
if (!type.Equals (iface_constraint.Type))
continue;
Report.Error (405, loc,
"Duplicate constraint `{0}' for type " +
"parameter `{1}'.", iface_constraint.GetSignatureForError (),
name);
return false;
}
list.Add (iface_constraint.Type);
}
foreach (TypeParameterExpr expr in type_param_constraints) {
foreach (Type type in list) {
if (!type.Equals (expr.Type))
continue;
Report.Error (405, loc,
"Duplicate constraint `{0}' for type " +
"parameter `{1}'.", expr.GetSignatureForError (), name);
return false;
}
list.Add (expr.Type);
}
iface_constraint_types = new Type [list.Count];
list.CopyTo (iface_constraint_types, 0);
if (class_constraint != null) {
class_constraint_type = class_constraint.Type;
if (class_constraint_type == null)
return false;
if (class_constraint_type.IsSealed) {
if (class_constraint_type.IsAbstract)
{
Report.Error (717, loc, "`{0}' is not a valid constraint. Static classes cannot be used as constraints",
TypeManager.CSharpName (class_constraint_type));
}
else
{
Report.Error (701, loc, "`{0}' is not a valid constraint. A constraint must be an interface, " +
"a non-sealed class or a type parameter", TypeManager.CSharpName(class_constraint_type));
}
return false;
}
if ((class_constraint_type == TypeManager.array_type) ||
(class_constraint_type == TypeManager.delegate_type) ||
(class_constraint_type == TypeManager.enum_type) ||
(class_constraint_type == TypeManager.value_type) ||
(class_constraint_type == TypeManager.object_type)) {
Report.Error (702, loc,
"Bound cannot be special class `{0}'",
TypeManager.CSharpName (class_constraint_type));
return false;
}
}
if (class_constraint_type != null)
effective_base_type = class_constraint_type;
else if (HasValueTypeConstraint)
effective_base_type = TypeManager.value_type;
else
effective_base_type = TypeManager.object_type;
resolved = true;
return true;
}
bool CheckTypeParameterConstraints (TypeParameter tparam, Hashtable seen)
{
seen.Add (tparam, true);
Constraints constraints = tparam.Constraints;
if (constraints == null)
return true;
if (constraints.HasValueTypeConstraint) {
Report.Error (456, loc, "Type parameter `{0}' has " +
"the `struct' constraint, so it cannot " +
"be used as a constraint for `{1}'",
tparam.Name, name);
return false;
}
if (constraints.type_param_constraints == null)
return true;
foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
if (seen.Contains (expr.TypeParameter)) {
Report.Error (454, loc, "Circular constraint " +
"dependency involving `{0}' and `{1}'",
tparam.Name, expr.Name);
return false;
}
if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
return false;
}
return true;
}
/// <summary>
/// Resolve the constraints into actual types.
/// </summary>
public bool ResolveTypes (IResolveContext ec)
{
if (resolved_types)
return true;
resolved_types = true;
foreach (object obj in constraints) {
ConstructedType cexpr = obj as ConstructedType;
if (cexpr == null)
continue;
if (!cexpr.CheckConstraints (ec))
return false;
}
foreach (TypeParameterExpr expr in type_param_constraints) {
Hashtable seen = new Hashtable ();
if (!CheckTypeParameterConstraints (expr.TypeParameter, seen))
return false;
}
for (int i = 0; i < iface_constraints.Count; ++i) {
TypeExpr iface_constraint = (TypeExpr) iface_constraints [i];
iface_constraint = iface_constraint.ResolveAsTypeTerminal (ec, false);
if (iface_constraint == null)
return false;
iface_constraints [i] = iface_constraint;
}
if (class_constraint != null) {
class_constraint = class_constraint.ResolveAsTypeTerminal (ec, false);
if (class_constraint == null)
return false;
}
return true;
}
/// <summary>
/// Check whether there are no conflicts in our type parameter constraints.
///
/// This is an example:
///
/// class Foo<T,U>
/// where T : class
/// where U : T, struct
/// </summary>
public bool CheckDependencies ()
{
foreach (TypeParameterExpr expr in type_param_constraints) {
if (!CheckDependencies (expr.TypeParameter))
return false;
}
return true;
}
bool CheckDependencies (TypeParameter tparam)
{
Constraints constraints = tparam.Constraints;
if (constraints == null)
return true;
if (HasValueTypeConstraint && constraints.HasClassConstraint) {
Report.Error (455, loc, "Type parameter `{0}' inherits " +
"conflicting constraints `{1}' and `{2}'",
name, TypeManager.CSharpName (constraints.ClassConstraint),
"System.ValueType");
return false;
}
if (HasClassConstraint && constraints.HasClassConstraint) {
Type t1 = ClassConstraint;
TypeExpr e1 = class_constraint;
Type t2 = constraints.ClassConstraint;
TypeExpr e2 = constraints.class_constraint;
if (!Convert.ImplicitReferenceConversionExists (e1, t2) &&
!Convert.ImplicitReferenceConversionExists (e2, t1)) {
Report.Error (455, loc,
"Type parameter `{0}' inherits " +
"conflicting constraints `{1}' and `{2}'",
name, TypeManager.CSharpName (t1), TypeManager.CSharpName (t2));
return false;
}
}
if (constraints.type_param_constraints == null)
return true;
foreach (TypeParameterExpr expr in constraints.type_param_constraints) {
if (!CheckDependencies (expr.TypeParameter))
return false;
}
return true;
}
public override GenericParameterAttributes Attributes {
get { return attrs; }
}
public override bool HasClassConstraint {
get { return class_constraint != null; }
}
public override Type ClassConstraint {
get { return class_constraint_type; }
}
public override Type[] InterfaceConstraints {
get { return iface_constraint_types; }
}
public override Type EffectiveBaseClass {
get { return effective_base_type; }
}
public bool IsSubclassOf (Type t)
{
if ((class_constraint_type != null) &&
class_constraint_type.IsSubclassOf (t))
return true;
if (iface_constraint_types == null)
return false;
foreach (Type iface in iface_constraint_types) {
if (TypeManager.IsSubclassOf (iface, t))
return true;
}
return false;
}
public Location Location {
get {
return loc;
}
}
/// <summary>
/// This is used when we're implementing a generic interface method.
/// Each method type parameter in implementing method must have the same
/// constraints than the corresponding type parameter in the interface
/// method. To do that, we're called on each of the implementing method's
/// type parameters.
/// </summary>
public bool CheckInterfaceMethod (GenericConstraints gc)
{
if (gc.Attributes != attrs)
return false;
if (HasClassConstraint != gc.HasClassConstraint)
return false;
if (HasClassConstraint && !TypeManager.IsEqual (gc.ClassConstraint, ClassConstraint))
return false;
int gc_icount = gc.InterfaceConstraints != null ?
gc.InterfaceConstraints.Length : 0;
int icount = InterfaceConstraints != null ?
InterfaceConstraints.Length : 0;
if (gc_icount != icount)
return false;
foreach (Type iface in gc.InterfaceConstraints) {
bool ok = false;
foreach (Type check in InterfaceConstraints) {
if (TypeManager.IsEqual (iface, check)) {
ok = true;
break;
}
}
if (!ok)
return false;
}
return true;
}
public void VerifyClsCompliance ()
{
if (class_constraint_type != null && !AttributeTester.IsClsCompliant (class_constraint_type))
Warning_ConstrainIsNotClsCompliant (class_constraint_type, class_constraint.Location);
if (iface_constraint_types != null) {
for (int i = 0; i < iface_constraint_types.Length; ++i) {
if (!AttributeTester.IsClsCompliant (iface_constraint_types [i]))
Warning_ConstrainIsNotClsCompliant (iface_constraint_types [i],
((TypeExpr)iface_constraints [i]).Location);
}
}
}
void Warning_ConstrainIsNotClsCompliant (Type t, Location loc)
{
Report.SymbolRelatedToPreviousError (t);
Report.Warning (3024, 1, loc, "Constraint type `{0}' is not CLS-compliant",
TypeManager.CSharpName (t));
}
}
/// <summary>
/// A type parameter from a generic type definition.
/// </summary>
public class TypeParameter : MemberCore, IMemberContainer {
string name;
DeclSpace decl;
GenericConstraints gc;
Constraints constraints;
Location loc;
GenericTypeParameterBuilder type;
public TypeParameter (DeclSpace parent, DeclSpace decl, string name,
Constraints constraints, Attributes attrs, Location loc)
: base (parent, new MemberName (name, loc), attrs)
{
this.name = name;
this.decl = decl;
this.constraints = constraints;
this.loc = loc;
}
public GenericConstraints GenericConstraints {
get { return gc != null ? gc : constraints; }
}
public Constraints Constraints {
get { return constraints; }
}
public bool HasConstructorConstraint {
get { return constraints != null && constraints.HasConstructorConstraint; }
}
public DeclSpace DeclSpace {
get { return decl; }
}
public Type Type {
get { return type; }
}
/// <summary>
/// This is the first method which is called during the resolving
/// process; we're called immediately after creating the type parameters
/// with SRE (by calling `DefineGenericParameters()' on the TypeBuilder /
/// MethodBuilder).
///
/// We're either called from TypeContainer.DefineType() or from
/// GenericMethod.Define() (called from Method.Define()).
/// </summary>
public void Define (GenericTypeParameterBuilder type)
{
if (this.type != null)
throw new InvalidOperationException ();
this.type = type;
TypeManager.AddTypeParameter (type, this);
}
/// <summary>
/// This is the second method which is called during the resolving
/// process - in case of class type parameters, we're called from
/// TypeContainer.ResolveType() - after it resolved the class'es
/// base class and interfaces. For method type parameters, we're
/// called immediately after Define().
///
/// We're just resolving the constraints into expressions here, we
/// don't resolve them into actual types.
///
/// Note that in the special case of partial generic classes, we may be
/// called _before_ Define() and we may also be called multiple types.
/// </summary>
public bool Resolve (DeclSpace ds)
{
if (constraints != null) {
if (!constraints.Resolve (ds)) {
constraints = null;
return false;
}
}
return true;
}
/// <summary>
/// This is the third method which is called during the resolving
/// process. We're called immediately after calling DefineConstraints()
/// on all of the current class'es type parameters.
///
/// Our job is to resolve the constraints to actual types.
///
/// Note that we may have circular dependencies on type parameters - this
/// is why Resolve() and ResolveType() are separate.
/// </summary>
public bool ResolveType (IResolveContext ec)
{
if (constraints != null) {
if (!constraints.ResolveTypes (ec)) {
constraints = null;
return false;
}
}
return true;
}
/// <summary>
/// This is the fourth and last method which is called during the resolving
/// process. We're called after everything is fully resolved and actually
/// register the constraints with SRE and the TypeManager.
/// </summary>
public bool DefineType (IResolveContext ec)
{
return DefineType (ec, null, null, false);
}
/// <summary>
/// This is the fith and last method which is called during the resolving
/// process. We're called after everything is fully resolved and actually
/// register the constraints with SRE and the TypeManager.
///
/// The `builder', `implementing' and `is_override' arguments are only
/// applicable to method type parameters.
/// </summary>
public bool DefineType (IResolveContext ec, MethodBuilder builder,
MethodInfo implementing, bool is_override)
{
if (!ResolveType (ec))
return false;
if (implementing != null) {
if (is_override && (constraints != null)) {
Report.Error (460, loc,
"`{0}': Cannot specify constraints for overrides or explicit interface implementation methods",
TypeManager.CSharpSignature (builder));
return false;
}
MethodBase mb = TypeManager.DropGenericMethodArguments (implementing);
int pos = type.GenericParameterPosition;
Type mparam = mb.GetGenericArguments () [pos];
GenericConstraints temp_gc = ReflectionConstraints.GetConstraints (mparam);
if (temp_gc != null)
gc = new InflatedConstraints (temp_gc, implementing.DeclaringType);
else if (constraints != null)
gc = new InflatedConstraints (constraints, implementing.DeclaringType);
bool ok = true;
if (constraints != null) {
if (temp_gc == null)
ok = false;
else if (!constraints.CheckInterfaceMethod (gc))
ok = false;
} else {
if (!is_override && (temp_gc != null))
ok = false;
}
if (!ok) {
Report.SymbolRelatedToPreviousError (implementing);
Report.Error (
425, loc, "The constraints for type " +
"parameter `{0}' of method `{1}' must match " +
"the constraints for type parameter `{2}' " +
"of interface method `{3}'. Consider using " +
"an explicit interface implementation instead",
Name, TypeManager.CSharpSignature (builder),
TypeManager.CSharpName (mparam), TypeManager.CSharpSignature (mb));
return false;
}
} else if (DeclSpace is CompilerGeneratedClass) {
TypeParameter[] tparams = DeclSpace.TypeParameters;
Type[] types = new Type [tparams.Length];
for (int i = 0; i < tparams.Length; i++)
types [i] = tparams [i].Type;
if (constraints != null)
gc = new InflatedConstraints (constraints, types);
} else {
gc = (GenericConstraints) constraints;
}
if (gc == null)
return true;
if (gc.HasClassConstraint)
type.SetBaseTypeConstraint (gc.ClassConstraint);
type.SetInterfaceConstraints (gc.InterfaceConstraints);
type.SetGenericParameterAttributes (gc.Attributes);
TypeManager.RegisterBuilder (type, gc.InterfaceConstraints);
return true;
}
/// <summary>
/// Check whether there are no conflicts in our type parameter constraints.
///
/// This is an example:
///
/// class Foo<T,U>
/// where T : class
/// where U : T, struct
/// </summary>
public bool CheckDependencies ()
{
if (constraints != null)
return constraints.CheckDependencies ();
return true;
}
/// <summary>
/// This is called for each part of a partial generic type definition.
///
/// If `new_constraints' is not null and we don't already have constraints,
/// they become our constraints. If we already have constraints, we must
/// check that they're the same.
/// con
/// </summary>
public bool UpdateConstraints (IResolveContext ec, Constraints new_constraints)
{
if (type == null)
throw new InvalidOperationException ();
if (new_constraints == null)
return true;
if (!new_constraints.Resolve (ec))
return false;
if (!new_constraints.ResolveTypes (ec))
return false;
if (constraints != null)
return constraints.CheckInterfaceMethod (new_constraints);
constraints = new_constraints;
return true;
}
public void EmitAttributes ()
{
if (OptAttributes != null)
OptAttributes.Emit ();
}
public override string DocCommentHeader {
get {
throw new InvalidOperationException (
"Unexpected attempt to get doc comment from " + this.GetType () + ".");
}
}
//
// MemberContainer
//
public override bool Define ()
{
return true;
}
public override void ApplyAttributeBuilder (Attribute a,
CustomAttributeBuilder cb)
{
type.SetCustomAttribute (cb);
}
public override AttributeTargets AttributeTargets {
get {
return (AttributeTargets) AttributeTargets.GenericParameter;
}
}
public override string[] ValidAttributeTargets {
get {
return new string [] { "type parameter" };
}
}
//
// IMemberContainer
//
string IMemberContainer.Name {
get { return Name; }
}
MemberCache IMemberContainer.BaseCache {
get { return null; }
}
bool IMemberContainer.IsInterface {
get { return true; }
}
MemberList IMemberContainer.GetMembers (MemberTypes mt, BindingFlags bf)
{
return FindMembers (mt, bf, null, null);
}
MemberCache IMemberContainer.MemberCache {
get { return null; }
}
public MemberList FindMembers (MemberTypes mt, BindingFlags bf,
MemberFilter filter, object criteria)
{
if (constraints == null)
return MemberList.Empty;
ArrayList members = new ArrayList ();
if (gc.HasClassConstraint) {
MemberList list = TypeManager.FindMembers (
gc.ClassConstraint, mt, bf, filter, criteria);
members.AddRange (list);
}
Type[] ifaces = TypeManager.ExpandInterfaces (gc.InterfaceConstraints);
foreach (Type t in ifaces) {
MemberList list = TypeManager.FindMembers (
t, mt, bf, filter, criteria);
members.AddRange (list);
}
return new MemberList (members);
}
public bool IsSubclassOf (Type t)
{
if (type.Equals (t))
return true;
if (constraints != null)
return constraints.IsSubclassOf (t);
return false;
}
public override string ToString ()
{
return "TypeParameter[" + name + "]";
}
public static string GetSignatureForError (TypeParameter[] tp)
{
if (tp == null || tp.Length == 0)
return "";
StringBuilder sb = new StringBuilder ("<");
for (int i = 0; i < tp.Length; ++i) {
if (i > 0)
sb.Append (",");
sb.Append (tp[i].GetSignatureForError ());
}
sb.Append ('>');
return sb.ToString ();
}
public void InflateConstraints (Type declaring)
{
if (constraints != null)
gc = new InflatedConstraints (constraints, declaring);
}
protected class InflatedConstraints : GenericConstraints
{
GenericConstraints gc;
Type base_type;
Type class_constraint;
Type[] iface_constraints;
Type[] dargs;
public InflatedConstraints (GenericConstraints gc, Type declaring)
: this (gc, TypeManager.GetTypeArguments (declaring))
{ }
public InflatedConstraints (GenericConstraints gc, Type[] dargs)
{
this.gc = gc;
this.dargs = dargs;
ArrayList list = new ArrayList ();
if (gc.HasClassConstraint)
list.Add (inflate (gc.ClassConstraint));
foreach (Type iface in gc.InterfaceConstraints)
list.Add (inflate (iface));
bool has_class_constr = false;
if (list.Count > 0) {
Type first = (Type) list [0];
has_class_constr = !first.IsInterface && !first.IsGenericParameter;
}
if ((list.Count > 0) && has_class_constr) {
class_constraint = (Type) list [0];
iface_constraints = new Type [list.Count - 1];
list.CopyTo (1, iface_constraints, 0, list.Count - 1);
} else {
iface_constraints = new Type [list.Count];
list.CopyTo (iface_constraints, 0);
}
if (HasValueTypeConstraint)
base_type = TypeManager.value_type;
else if (class_constraint != null)
base_type = class_constraint;
else
base_type = TypeManager.object_type;
}
Type inflate (Type t)
{
if (t == null)
return null;
if (t.IsGenericParameter)
return dargs [t.GenericParameterPosition];
if (t.IsGenericType) {
Type[] args = t.GetGenericArguments ();
Type[] inflated = new Type [args.Length];
for (int i = 0; i < args.Length; i++)
inflated [i] = inflate (args [i]);
t = t.GetGenericTypeDefinition ();
t = t.MakeGenericType (inflated);
}
return t;
}
public override string TypeParameter {
get { return gc.TypeParameter; }
}
public override GenericParameterAttributes Attributes {
get { return gc.Attributes; }
}
public override Type ClassConstraint {
get { return class_constraint; }
}
public override Type EffectiveBaseClass {
get { return base_type; }
}
public override Type[] InterfaceConstraints {
get { return iface_constraints; }
}
}
}
/// <summary>
/// A TypeExpr which already resolved to a type parameter.
/// </summary>
public class TypeParameterExpr : TypeExpr {
TypeParameter type_parameter;
public override string Name {
get {
return type_parameter.Name;
}
}
public override string FullName {
get {
return type_parameter.Name;
}
}
public TypeParameter TypeParameter {
get {
return type_parameter;
}
}
public TypeParameterExpr (TypeParameter type_parameter, Location loc)
{
this.type_parameter = type_parameter;
this.loc = loc;
}
protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
{
type = type_parameter.Type;
return this;
}
public override bool IsInterface {
get { return false; }
}
public override bool CheckAccessLevel (DeclSpace ds)
{
return true;
}
public void Error_CannotUseAsUnmanagedType (Location loc)
{
Report.Error (-203, loc, "Can not use type parameter as unmanaged type");
}
}
/// <summary>
/// Tracks the type arguments when instantiating a generic type. We're used in
/// ConstructedType.
/// </summary>
public class TypeArguments {
public readonly Location Location;
ArrayList args;
Type[] atypes;
int dimension;
bool has_type_args;
bool created;
public TypeArguments (Location loc)
{
args = new ArrayList ();
this.Location = loc;
}
public TypeArguments (int dimension, Location loc)
{
this.dimension = dimension;
this.Location = loc;
}
public void Add (Expression type)
{
if (created)
throw new InvalidOperationException ();
args.Add (type);
}
public void Add (TypeArguments new_args)
{
if (created)
throw new InvalidOperationException ();
args.AddRange (new_args.args);
}
/// <summary>
/// We're used during the parsing process: the parser can't distinguish
/// between type parameters and type arguments. Because of that, the
/// parser creates a `MemberName' with `TypeArguments' for both cases and
/// in case of a generic type definition, we call GetDeclarations().
/// </summary>
public TypeParameterName[] GetDeclarations ()
{
TypeParameterName[] ret = new TypeParameterName [args.Count];
for (int i = 0; i < args.Count; i++) {
TypeParameterName name = args [i] as TypeParameterName;
if (name != null) {
ret [i] = name;
continue;
}
SimpleName sn = args [i] as SimpleName;
if (sn != null) {
ret [i] = new TypeParameterName (sn.Name, null, sn.Location);
continue;
}
Report.Error (81, Location, "Type parameter declaration " +
"must be an identifier not a type");
return null;
}
return ret;
}
/// <summary>
/// We may only be used after Resolve() is called and return the fully
/// resolved types.
/// </summary>
public Type[] Arguments {
get {
return atypes;
}
}
public bool HasTypeArguments {
get {
return has_type_args;
}
}
public int Count {
get {
if (dimension > 0)
return dimension;
else
return args.Count;
}
}
public bool IsUnbound {
get {
return dimension > 0;
}
}
public override string ToString ()
{
StringBuilder s = new StringBuilder ();
int count = Count;
for (int i = 0; i < count; i++){
//
// FIXME: Use TypeManager.CSharpname once we have the type
//
if (args != null)
s.Append (args [i].ToString ());
if (i+1 < count)
s.Append (",");
}
return s.ToString ();
}
public string GetSignatureForError()
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < Count; ++i)
{
Expression expr = (Expression)args [i];
sb.Append(expr.GetSignatureForError());
if (i + 1 < Count)
sb.Append(',');
}
return sb.ToString();
}
/// <summary>
/// Resolve the type arguments.
/// </summary>
public bool Resolve (IResolveContext ec)
{
int count = args.Count;
bool ok = true;
atypes = new Type [count];
for (int i = 0; i < count; i++){
TypeExpr te = ((Expression) args [i]).ResolveAsTypeTerminal (ec, false);
if (te == null) {
ok = false;
continue;
}
if (te is TypeParameterExpr)
has_type_args = true;
#if !MS_COMPATIBLE
if (te.Type.IsSealed && te.Type.IsAbstract) {
Report.Error (718, Location, "`{0}': static classes cannot be used as generic arguments",
te.GetSignatureForError ());
return false;
}
#endif
if (te.Type.IsPointer) {
Report.Error (306, Location, "The type `{0}' may not be used " +
"as a type argument", TypeManager.CSharpName (te.Type));
return false;
}
if (te.Type == TypeManager.void_type) {
Expression.Error_VoidInvalidInTheContext (Location);
return false;
}
atypes [i] = te.Type;
}
return ok;
}
}
public class TypeParameterName : SimpleName
{
Attributes attributes;
public TypeParameterName (string name, Attributes attrs, Location loc)
: base (name, loc)
{
attributes = attrs;
}
public Attributes OptAttributes {
get {
return attributes;
}
}
}
/// <summary>
/// An instantiation of a generic type.
/// </summary>
public class ConstructedType : TypeExpr {
string full_name;
FullNamedExpression name;
TypeArguments args;
Type[] gen_params, atypes;
Type gt;
/// <summary>
/// Instantiate the generic type `fname' with the type arguments `args'.
/// </summary>
public ConstructedType (FullNamedExpression fname, TypeArguments args, Location l)
{
loc = l;
this.name = fname;
this.args = args;
eclass = ExprClass.Type;
full_name = name + "<" + args.ToString () + ">";
}
protected ConstructedType (TypeArguments args, Location l)
{
loc = l;
this.args = args;
eclass = ExprClass.Type;
}
protected ConstructedType (TypeParameter[] type_params, Location l)
{
loc = l;
args = new TypeArguments (l);
foreach (TypeParameter type_param in type_params)
args.Add (new TypeParameterExpr (type_param, l));
eclass = ExprClass.Type;
}
/// <summary>
/// This is used to construct the `this' type inside a generic type definition.
/// </summary>
public ConstructedType (Type t, TypeParameter[] type_params, Location l)
: this (type_params, l)
{
gt = t.GetGenericTypeDefinition ();
this.name = new TypeExpression (gt, l);
full_name = gt.FullName + "<" + args.ToString () + ">";
}
/// <summary>
/// Instantiate the generic type `t' with the type arguments `args'.
/// Use this constructor if you already know the fully resolved
/// generic type.
/// </summary>
public ConstructedType (Type t, TypeArguments args, Location l)
: this (args, l)
{
gt = t.GetGenericTypeDefinition ();
this.name = new TypeExpression (gt, l);
full_name = gt.FullName + "<" + args.ToString () + ">";
}
public TypeArguments TypeArguments {
get { return args; }
}
public override string GetSignatureForError ()
{
return TypeManager.RemoveGenericArity (gt.FullName) + "<" + args.GetSignatureForError () + ">";
}
protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
{
if (!ResolveConstructedType (ec))
return null;
return this;
}
/// <summary>
/// Check the constraints; we're called from ResolveAsTypeTerminal()
/// after fully resolving the constructed type.
/// </summary>
public bool CheckConstraints (IResolveContext ec)
{
return ConstraintChecker.CheckConstraints (ec, gt, gen_params, atypes, loc);
}
/// <summary>
/// Resolve the constructed type, but don't check the constraints.
/// </summary>
public bool ResolveConstructedType (IResolveContext ec)
{
if (type != null)
return true;
// If we already know the fully resolved generic type.
if (gt != null)
return DoResolveType (ec);
int num_args;
Type t = name.Type;
if (t == null) {
Report.Error (246, loc, "Cannot find type `{0}'<...>", Name);
return false;
}
num_args = TypeManager.GetNumberOfTypeArguments (t);
if (num_args == 0) {
Report.Error (308, loc,
"The non-generic type `{0}' cannot " +
"be used with type arguments.",
TypeManager.CSharpName (t));
return false;
}
gt = t.GetGenericTypeDefinition ();
return DoResolveType (ec);
}
bool DoResolveType (IResolveContext ec)
{
//
// Resolve the arguments.
//
if (args.Resolve (ec) == false)
return false;
gen_params = gt.GetGenericArguments ();
atypes = args.Arguments;
if (atypes.Length != gen_params.Length) {
Report.Error (305, loc,
"Using the generic type `{0}' " +
"requires {1} type arguments",
TypeManager.CSharpName (gt),
gen_params.Length.ToString ());
return false;
}
//
// Now bind the parameters.
//
type = gt.MakeGenericType (atypes);
return true;
}
public Expression GetSimpleName (EmitContext ec)
{
return this;
}
public override bool CheckAccessLevel (DeclSpace ds)
{
return ds.CheckAccessLevel (gt);
}
public override bool AsAccessible (DeclSpace ds, int flags)
{
foreach (Type t in atypes) {
if (!ds.AsAccessible (t, flags))
return false;
}
return ds.AsAccessible (gt, flags);
}
public override bool IsClass {
get { return gt.IsClass; }
}
public override bool IsValueType {
get { return gt.IsValueType; }
}
public override bool IsInterface {
get { return gt.IsInterface; }
}
public override bool IsSealed {
get { return gt.IsSealed; }
}
public override bool Equals (object obj)
{
ConstructedType cobj = obj as ConstructedType;
if (cobj == null)
return false;
if ((type == null) || (cobj.type == null))
return false;
return type == cobj.type;
}
public override int GetHashCode ()
{
return base.GetHashCode ();
}
public override string Name {
get {
return full_name;
}
}
public override string FullName {
get {
return full_name;
}
}
}
public abstract class ConstraintChecker
{
protected readonly Type[] gen_params;
protected readonly Type[] atypes;
protected readonly Location loc;
protected ConstraintChecker (Type[] gen_params, Type[] atypes, Location loc)
{
this.gen_params = gen_params;
this.atypes = atypes;
this.loc = loc;
}
/// <summary>
/// Check the constraints; we're called from ResolveAsTypeTerminal()
/// after fully resolving the constructed type.
/// </summary>
public bool CheckConstraints (IResolveContext ec)
{
for (int i = 0; i < gen_params.Length; i++) {
if (!CheckConstraints (ec, i))
return false;
}
return true;
}
protected bool CheckConstraints (IResolveContext ec, int index)
{
Type atype = atypes [index];
Type ptype = gen_params [index];
if (atype == ptype)
return true;
Expression aexpr = new EmptyExpression (atype);
GenericConstraints gc = TypeManager.GetTypeParameterConstraints (ptype);
if (gc == null)
return true;
bool is_class, is_struct;
if (atype.IsGenericParameter) {
GenericConstraints agc = TypeManager.GetTypeParameterConstraints (atype);
if (agc != null) {
if (agc is Constraints)
((Constraints) agc).Resolve (ec);
is_class = agc.IsReferenceType;
is_struct = agc.IsValueType;
} else {
is_class = is_struct = false;
}
} else {
#if MS_COMPATIBLE
is_class = false;
if (!atype.IsGenericType)
#endif
is_class = atype.IsClass || atype.IsInterface;
is_struct = atype.IsValueType && !TypeManager.IsNullableType (atype);
}
//
// First, check the `class' and `struct' constraints.
//
if (gc.HasReferenceTypeConstraint && !is_class) {
Report.Error (452, loc, "The type `{0}' must be " +
"a reference type in order to use it " +
"as type parameter `{1}' in the " +
"generic type or method `{2}'.",
TypeManager.CSharpName (atype),
TypeManager.CSharpName (ptype),
GetSignatureForError ());
return false;
} else if (gc.HasValueTypeConstraint && !is_struct) {
Report.Error (453, loc, "The type `{0}' must be a " +
"non-nullable value type in order to use it " +
"as type parameter `{1}' in the " +
"generic type or method `{2}'.",
TypeManager.CSharpName (atype),
TypeManager.CSharpName (ptype),
GetSignatureForError ());
return false;
}
//
// The class constraint comes next.
//
if (gc.HasClassConstraint) {
if (!CheckConstraint (ec, ptype, aexpr, gc.ClassConstraint))
return false;
}
//
// Now, check the interface constraints.
//
if (gc.InterfaceConstraints != null) {
foreach (Type it in gc.InterfaceConstraints) {
if (!CheckConstraint (ec, ptype, aexpr, it))
return false;
}
}
//
// Finally, check the constructor constraint.
//
if (!gc.HasConstructorConstraint)
return true;
if (TypeManager.IsBuiltinType (atype) || atype.IsValueType)
return true;
if (HasDefaultConstructor (ec.DeclContainer.TypeBuilder, atype))
return true;
Report_SymbolRelatedToPreviousError ();
Report.SymbolRelatedToPreviousError (atype);
Report.Error (310, loc, "The type `{0}' must have a public " +
"parameterless constructor in order to use it " +
"as parameter `{1}' in the generic type or " +
"method `{2}'",
TypeManager.CSharpName (atype),
TypeManager.CSharpName (ptype),
GetSignatureForError ());
return false;
}
protected bool CheckConstraint (IResolveContext ec, Type ptype, Expression expr,
Type ctype)
{
if (TypeManager.HasGenericArguments (ctype)) {
Type[] types = TypeManager.GetTypeArguments (ctype);
TypeArguments new_args = new TypeArguments (loc);
for (int i = 0; i < types.Length; i++) {
Type t = types [i];
if (t.IsGenericParameter) {
int pos = t.GenericParameterPosition;
t = atypes [pos];
}
new_args.Add (new TypeExpression (t, loc));
}
TypeExpr ct = new ConstructedType (ctype, new_args, loc);
if (ct.ResolveAsTypeStep (ec, false) == null)
return false;
ctype = ct.Type;
} else if (ctype.IsGenericParameter) {
int pos = ctype.GenericParameterPosition;
ctype = atypes [pos];
}
if (Convert.ImplicitStandardConversionExists (expr, ctype))
return true;
Error_TypeMustBeConvertible (expr.Type, ctype, ptype);
return false;
}
bool HasDefaultConstructor (Type containerType, Type atype)
{
if (atype.IsAbstract)
return false;
again:
atype = TypeManager.DropGenericTypeArguments (atype);
if (atype is TypeBuilder) {
TypeContainer tc = TypeManager.LookupTypeContainer (atype);
if (tc.InstanceConstructors == null) {
atype = atype.BaseType;
goto again;
}
foreach (Constructor c in tc.InstanceConstructors) {
if ((c.ModFlags & Modifiers.PUBLIC) == 0)
continue;
if ((c.Parameters.FixedParameters != null) &&
(c.Parameters.FixedParameters.Length != 0))
continue;
if (c.Parameters.HasArglist || c.Parameters.HasParams)
continue;
return true;
}
}
TypeParameter tparam = TypeManager.LookupTypeParameter (atype);
if (tparam != null)
return tparam.HasConstructorConstraint;
MemberList list = TypeManager.FindMembers (
atype, MemberTypes.Constructor,
BindingFlags.Public | BindingFlags.Instance |
BindingFlags.DeclaredOnly, null, null);
if (atype.IsAbstract || (list == null))
return false;
foreach (MethodBase mb in list) {
ParameterData pd = TypeManager.GetParameterData (mb);
if ((pd.Count == 0) && mb.IsPublic && !mb.IsStatic)
return true;
}
return false;
}
protected abstract string GetSignatureForError ();
protected abstract void Report_SymbolRelatedToPreviousError ();
void Error_TypeMustBeConvertible (Type atype, Type gc, Type ptype)
{
Report_SymbolRelatedToPreviousError ();
Report.SymbolRelatedToPreviousError (atype);
Report.Error (309, loc,
"The type `{0}' must be convertible to `{1}' in order to " +
"use it as parameter `{2}' in the generic type or method `{3}'",
TypeManager.CSharpName (atype), TypeManager.CSharpName (gc),
TypeManager.CSharpName (ptype), GetSignatureForError ());
}
public static bool CheckConstraints (EmitContext ec, MethodBase definition,
MethodBase instantiated, Location loc)
{
MethodConstraintChecker checker = new MethodConstraintChecker (
definition, definition.GetGenericArguments (),
instantiated.GetGenericArguments (), loc);
return checker.CheckConstraints (ec);
}
public static bool CheckConstraints (IResolveContext ec, Type gt, Type[] gen_params,
Type[] atypes, Location loc)
{
TypeConstraintChecker checker = new TypeConstraintChecker (
gt, gen_params, atypes, loc);
return checker.CheckConstraints (ec);
}
protected class MethodConstraintChecker : ConstraintChecker
{
MethodBase definition;
public MethodConstraintChecker (MethodBase definition, Type[] gen_params,
Type[] atypes, Location loc)
: base (gen_params, atypes, loc)
{
this.definition = definition;
}
protected override string GetSignatureForError ()
{
return TypeManager.CSharpSignature (definition);
}
protected override void Report_SymbolRelatedToPreviousError ()
{
Report.SymbolRelatedToPreviousError (definition);
}
}
protected class TypeConstraintChecker : ConstraintChecker
{
Type gt;
public TypeConstraintChecker (Type gt, Type[] gen_params, Type[] atypes,
Location loc)
: base (gen_params, atypes, loc)
{
this.gt = gt;
}
protected override string GetSignatureForError ()
{
return TypeManager.CSharpName (gt);
}
protected override void Report_SymbolRelatedToPreviousError ()
{
Report.SymbolRelatedToPreviousError (gt);
}
}
}
/// <summary>
/// A generic method definition.
/// </summary>
public class GenericMethod : DeclSpace
{
Expression return_type;
Parameters parameters;
public GenericMethod (NamespaceEntry ns, DeclSpace parent, MemberName name,
Expression return_type, Parameters parameters)
: base (ns, parent, name, null)
{
this.return_type = return_type;
this.parameters = parameters;
}
public override TypeBuilder DefineType ()
{
throw new Exception ();
}
public override bool Define ()
{
for (int i = 0; i < TypeParameters.Length; i++)
if (!TypeParameters [i].Resolve (this))
return false;
return true;
}
/// <summary>
/// Define and resolve the type parameters.
/// We're called from Method.Define().
/// </summary>
public bool Define (MethodBuilder mb, ToplevelBlock block)
{
TypeParameterName[] names = MemberName.TypeArguments.GetDeclarations ();
string[] snames = new string [names.Length];
for (int i = 0; i < names.Length; i++) {
string type_argument_name = names[i].Name;
Parameter p = parameters.GetParameterByName (type_argument_name);
if (p != null) {
Error_ParameterNameCollision (p.Location, type_argument_name, "method parameter");
return false;
}
if (block != null) {
LocalInfo li = (LocalInfo)block.Variables[type_argument_name];
if (li != null) {
Error_ParameterNameCollision (li.Location, type_argument_name, "local variable");
return false;
}
}
snames[i] = type_argument_name;
}
GenericTypeParameterBuilder[] gen_params = mb.DefineGenericParameters (snames);
for (int i = 0; i < TypeParameters.Length; i++)
TypeParameters [i].Define (gen_params [i]);
if (!Define ())
return false;
for (int i = 0; i < TypeParameters.Length; i++) {
if (!TypeParameters [i].ResolveType (this))
return false;
}
return true;
}
static void Error_ParameterNameCollision (Location loc, string name, string collisionWith)
{
Report.Error (412, loc, "The type parameter name `{0}' is the same as `{1}'",
name, collisionWith);
}
/// <summary>
/// We're called from MethodData.Define() after creating the MethodBuilder.
/// </summary>
public bool DefineType (EmitContext ec, MethodBuilder mb,
MethodInfo implementing, bool is_override)
{
for (int i = 0; i < TypeParameters.Length; i++)
if (!TypeParameters [i].DefineType (
ec, mb, implementing, is_override))
return false;
bool ok = true;
foreach (Parameter p in parameters.FixedParameters){
if (!p.Resolve (ec))
ok = false;
}
if ((return_type != null) && (return_type.ResolveAsTypeTerminal (ec, false) == null))
ok = false;
return ok;
}
public void EmitAttributes ()
{
for (int i = 0; i < TypeParameters.Length; i++)
TypeParameters [i].EmitAttributes ();
if (OptAttributes != null)
OptAttributes.Emit ();
}
public override bool DefineMembers ()
{
return true;
}
public override MemberList FindMembers (MemberTypes mt, BindingFlags bf,
MemberFilter filter, object criteria)
{
throw new Exception ();
}
public override MemberCache MemberCache {
get {
return null;
}
}
public override AttributeTargets AttributeTargets {
get {
return AttributeTargets.Method | AttributeTargets.ReturnValue;
}
}
public override string DocCommentHeader {
get { return "M:"; }
}
public new void VerifyClsCompliance ()
{
foreach (TypeParameter tp in TypeParameters) {
if (tp.Constraints == null)
continue;
tp.Constraints.VerifyClsCompliance ();
}
}
}
public class DefaultValueExpression : Expression
{
Expression expr;
public DefaultValueExpression (Expression expr, Location loc)
{
this.expr = expr;
this.loc = loc;
}
public override Expression DoResolve (EmitContext ec)
{
TypeExpr texpr = expr.ResolveAsTypeTerminal (ec, false);
if (texpr == null)
return null;
type = texpr.Type;
if (type == TypeManager.void_type) {
Error_VoidInvalidInTheContext (loc);
return null;
}
if (type.IsGenericParameter)
{
GenericConstraints constraints = TypeManager.GetTypeParameterConstraints(type);
if (constraints != null && constraints.IsReferenceType)
return new NullDefault (new NullLiteral (Location), type);
}
else
{
Constant c = New.Constantify(type);
if (c != null)
return new NullDefault (c, type);
if (!TypeManager.IsValueType (type))
return new NullDefault (new NullLiteral (Location), type);
}
eclass = ExprClass.Variable;
return this;
}
public override void Emit (EmitContext ec)
{
LocalTemporary temp_storage = new LocalTemporary(type);
temp_storage.AddressOf(ec, AddressOp.LoadStore);
ec.ig.Emit(OpCodes.Initobj, type);
temp_storage.Emit(ec);
}
}
public class NullableType : TypeExpr
{
Expression underlying;
public NullableType (Expression underlying, Location l)
{
this.underlying = underlying;
loc = l;
eclass = ExprClass.Type;
}
public NullableType (Type type, Location loc)
: this (new TypeExpression (type, loc), loc)
{ }
public override string Name {
get { return underlying.ToString () + "?"; }
}
public override string FullName {
get { return underlying.ToString () + "?"; }
}
protected override TypeExpr DoResolveAsTypeStep (IResolveContext ec)
{
TypeArguments args = new TypeArguments (loc);
args.Add (underlying);
ConstructedType ctype = new ConstructedType (TypeManager.generic_nullable_type, args, loc);
return ctype.ResolveAsTypeTerminal (ec, false);
}
}
public partial class TypeManager
{
//
// A list of core types that the compiler requires or uses
//
static public Type activator_type;
static public Type generic_ilist_type;
static public Type generic_icollection_type;
static public Type generic_ienumerator_type;
static public Type generic_ienumerable_type;
static public Type generic_nullable_type;
//
// These methods are called by code generated by the compiler
//
static public MethodInfo activator_create_instance;
static void InitGenericCoreTypes ()
{
activator_type = CoreLookupType ("System", "Activator");
generic_ilist_type = CoreLookupType (
"System.Collections.Generic", "IList", 1);
generic_icollection_type = CoreLookupType (
"System.Collections.Generic", "ICollection", 1);
generic_ienumerator_type = CoreLookupType (
"System.Collections.Generic", "IEnumerator", 1);
generic_ienumerable_type = CoreLookupType (
"System.Collections.Generic", "IEnumerable", 1);
generic_nullable_type = CoreLookupType (
"System", "Nullable", 1);
}
static void InitGenericCodeHelpers ()
{
// Activator
Type [] type_arg = { type_type };
activator_create_instance = GetMethod (
activator_type, "CreateInstance", type_arg);
}
static Type CoreLookupType (string ns, string name, int arity)
{
return CoreLookupType (ns, MemberName.MakeName (name, arity));
}
public static TypeContainer LookupGenericTypeContainer (Type t)
{
t = DropGenericTypeArguments (t);
return LookupTypeContainer (t);
}
public static GenericConstraints GetTypeParameterConstraints (Type t)
{
if (!t.IsGenericParameter)
throw new InvalidOperationException ();
TypeParameter tparam = LookupTypeParameter (t);
if (tparam != null)
return tparam.GenericConstraints;
return ReflectionConstraints.GetConstraints (t);
}
/// <summary>
/// Check whether `a' and `b' may become equal generic types.
/// The algorithm to do that is a little bit complicated.
/// </summary>
public static bool MayBecomeEqualGenericTypes (Type a, Type b, Type[] class_infered,
Type[] method_infered)
{
if (a.IsGenericParameter) {
//
// If a is an array of a's type, they may never
// become equal.
//
while (b.IsArray) {
b = b.GetElementType ();
if (a.Equals (b))
return false;
}
//
// If b is a generic parameter or an actual type,
// they may become equal:
//
// class X<T,U> : I<T>, I<U>
// class X<T> : I<T>, I<float>
//
if (b.IsGenericParameter || !b.IsGenericType) {
int pos = a.GenericParameterPosition;
Type[] args = a.DeclaringMethod != null ? method_infered : class_infered;
if (args [pos] == null) {
args [pos] = b;
return true;
}
return args [pos] == a;
}
//
// We're now comparing a type parameter with a
// generic instance. They may become equal unless
// the type parameter appears anywhere in the
// generic instance:
//
// class X<T,U> : I<T>, I<X<U>>
// -> error because you could instanciate it as
// X<X<int>,int>
//
// class X<T> : I<T>, I<X<T>> -> ok
//
Type[] bargs = GetTypeArguments (b);
for (int i = 0; i < bargs.Length; i++) {
if (a.Equals (bargs [i]))
return false;
}
return true;
}
if (b.IsGenericParameter)
return MayBecomeEqualGenericTypes (b, a, class_infered, method_infered);
//
// At this point, neither a nor b are a type parameter.
//
// If one of them is a generic instance, let
// MayBecomeEqualGenericInstances() compare them (if the
// other one is not a generic instance, they can never
// become equal).
//
if (a.IsGenericType || b.IsGenericType)
return MayBecomeEqualGenericInstances (a, b, class_infered, method_infered);
//
// If both of them are arrays.
//
if (a.IsArray && b.IsArray) {
if (a.GetArrayRank () != b.GetArrayRank ())
return false;
a = a.GetElementType ();
b = b.GetElementType ();
return MayBecomeEqualGenericTypes (a, b, class_infered, method_infered);
}
//
// Ok, two ordinary types.
//
return a.Equals (b);
}
//
// Checks whether two generic instances may become equal for some
// particular instantiation (26.3.1).
//
public static bool MayBecomeEqualGenericInstances (Type a, Type b,
Type[] class_infered,
Type[] method_infered)
{
if (!a.IsGenericType || !b.IsGenericType)
return false;
if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
return false;
return MayBecomeEqualGenericInstances (
GetTypeArguments (a), GetTypeArguments (b), class_infered, method_infered);
}
public static bool MayBecomeEqualGenericInstances (Type[] aargs, Type[] bargs,
Type[] class_infered,
Type[] method_infered)
{
if (aargs.Length != bargs.Length)
return false;
for (int i = 0; i < aargs.Length; i++) {
if (!MayBecomeEqualGenericTypes (aargs [i], bargs [i], class_infered, method_infered))
return false;
}
return true;
}
//
// Type inference.
//
static bool InferType (Type pt, Type at, Type[] infered)
{
if (pt.IsGenericParameter) {
if (pt.DeclaringMethod == null)
return pt == at;
int pos = pt.GenericParameterPosition;
if (infered [pos] == null) {
infered [pos] = at;
return true;
}
if (infered [pos] != at)
return false;
return true;
}
if (!pt.ContainsGenericParameters) {
if (at.ContainsGenericParameters)
return InferType (at, pt, infered);
else
return true;
}
if (at.IsArray) {
if (pt.IsArray) {
if (at.GetArrayRank () != pt.GetArrayRank ())
return false;
return InferType (pt.GetElementType (), at.GetElementType (), infered);
}
if (!pt.IsGenericType)
return false;
Type gt = pt.GetGenericTypeDefinition ();
if ((gt != generic_ilist_type) && (gt != generic_icollection_type) &&
(gt != generic_ienumerable_type))
return false;
Type[] args = GetTypeArguments (pt);
return InferType (args [0], at.GetElementType (), infered);
}
if (pt.IsArray) {
if (!at.IsArray ||
(pt.GetArrayRank () != at.GetArrayRank ()))
return false;
return InferType (pt.GetElementType (), at.GetElementType (), infered);
}
if (pt.IsByRef && at.IsByRef)
return InferType (pt.GetElementType (), at.GetElementType (), infered);
ArrayList list = new ArrayList ();
if (at.IsGenericType)
list.Add (at);
for (Type bt = at.BaseType; bt != null; bt = bt.BaseType)
list.Add (bt);
list.AddRange (TypeManager.GetInterfaces (at));
bool found_one = false;
foreach (Type type in list) {
if (!type.IsGenericType)
continue;
Type[] infered_types = new Type [infered.Length];
if (!InferGenericInstance (pt, type, infered_types))
continue;
for (int i = 0; i < infered_types.Length; i++) {
if (infered [i] == null) {
infered [i] = infered_types [i];
continue;
}
if (infered [i] != infered_types [i])
return false;
}
found_one = true;
}
return found_one;
}
static bool InferGenericInstance (Type pt, Type at, Type[] infered_types)
{
Type[] at_args = at.GetGenericArguments ();
Type[] pt_args = pt.GetGenericArguments ();
if (at_args.Length != pt_args.Length)
return false;
for (int i = 0; i < at_args.Length; i++) {
if (!InferType (pt_args [i], at_args [i], infered_types))
return false;
}
for (int i = 0; i < infered_types.Length; i++) {
if (infered_types [i] == null)
return false;
}
return true;
}
/// <summary>
/// Type inference. Try to infer the type arguments from the params method
/// `method', which is invoked with the arguments `arguments'. This is used
/// when resolving an Invocation or a DelegateInvocation and the user
/// did not explicitly specify type arguments.
/// </summary>
public static bool InferParamsTypeArguments (EmitContext ec, ArrayList arguments,
ref MethodBase method)
{
if (!TypeManager.IsGenericMethod (method))
return true;
// if there are no arguments, there's no way to infer the type-arguments
if (arguments == null || arguments.Count == 0)
return false;
ParameterData pd = TypeManager.GetParameterData (method);
int pd_count = pd.Count;
int arg_count = arguments.Count;
if (pd_count == 0)
return false;
if (pd.ParameterModifier (pd_count - 1) != Parameter.Modifier.PARAMS)
return false;
if (pd_count - 1 > arg_count)
return false;
Type[] method_args = method.GetGenericArguments ();
Type[] infered_types = new Type [method_args.Length];
//
// If we have come this far, the case which
// remains is when the number of parameters is
// less than or equal to the argument count.
//
for (int i = 0; i < pd_count - 1; ++i) {
Argument a = (Argument) arguments [i];
if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
continue;
Type pt = pd.ParameterType (i);
Type at = a.Type;
if (!InferType (pt, at, infered_types))
return false;
}
Type element_type = TypeManager.GetElementType (pd.ParameterType (pd_count - 1));
for (int i = pd_count - 1; i < arg_count; i++) {
Argument a = (Argument) arguments [i];
if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr))
continue;
if (!InferType (element_type, a.Type, infered_types))
return false;
}
for (int i = 0; i < infered_types.Length; i++)
if (infered_types [i] == null)
return false;
method = ((MethodInfo)method).MakeGenericMethod (infered_types);
return true;
}
static bool InferTypeArguments (Type[] param_types, Type[] arg_types,
Type[] infered_types)
{
if (infered_types == null)
return false;
for (int i = 0; i < arg_types.Length; i++) {
if (arg_types [i] == null)
continue;
if (!InferType (param_types [i], arg_types [i], infered_types))
return false;
}
for (int i = 0; i < infered_types.Length; i++)
if (infered_types [i] == null)
return false;
return true;
}
/// <summary>
/// Type inference. Try to infer the type arguments from `method',
/// which is invoked with the arguments `arguments'. This is used
/// when resolving an Invocation or a DelegateInvocation and the user
/// did not explicitly specify type arguments.
/// </summary>
public static bool InferTypeArguments (ArrayList arguments,
ref MethodBase method)
{
if (!TypeManager.IsGenericMethod (method))
return true;
int arg_count;
if (arguments != null)
arg_count = arguments.Count;
else
arg_count = 0;
ParameterData pd = TypeManager.GetParameterData (method);
if (arg_count != pd.Count)
return false;
Type[] method_args = method.GetGenericArguments ();
bool is_open = false;
for (int i = 0; i < method_args.Length; i++) {
if (method_args [i].IsGenericParameter) {
is_open = true;
break;
}
}
// If none of the method parameters mention a generic parameter, we can't infer the generic parameters
if (!is_open)
return !TypeManager.IsGenericMethodDefinition (method);
Type[] infered_types = new Type [method_args.Length];
Type[] param_types = new Type [pd.Count];
Type[] arg_types = new Type [pd.Count];
for (int i = 0; i < arg_count; i++) {
param_types [i] = pd.ParameterType (i);
Argument a = (Argument) arguments [i];
if ((a.Expr is NullLiteral) || (a.Expr is MethodGroupExpr) ||
(a.Expr is AnonymousMethodExpression))
continue;
arg_types [i] = a.Type;
}
if (!InferTypeArguments (param_types, arg_types, infered_types))
return false;
method = ((MethodInfo)method).MakeGenericMethod (infered_types);
return true;
}
/// <summary>
/// Type inference.
/// </summary>
public static bool InferTypeArguments (ParameterData apd,
ref MethodBase method)
{
if (!TypeManager.IsGenericMethod (method))
return true;
ParameterData pd = TypeManager.GetParameterData (method);
if (apd.Count != pd.Count)
return false;
Type[] method_args = method.GetGenericArguments ();
Type[] infered_types = new Type [method_args.Length];
Type[] param_types = new Type [pd.Count];
Type[] arg_types = new Type [pd.Count];
for (int i = 0; i < apd.Count; i++) {
param_types [i] = pd.ParameterType (i);
arg_types [i] = apd.ParameterType (i);
}
if (!InferTypeArguments (param_types, arg_types, infered_types))
return false;
method = ((MethodInfo)method).MakeGenericMethod (infered_types);
return true;
}
}
public abstract class Nullable
{
public sealed class NullableInfo
{
public readonly Type Type;
public readonly Type UnderlyingType;
public readonly MethodInfo HasValue;
public readonly MethodInfo Value;
public readonly ConstructorInfo Constructor;
public NullableInfo (Type type)
{
Type = type;
UnderlyingType = TypeManager.GetTypeArguments (type) [0];
PropertyInfo has_value_pi = TypeManager.GetProperty (type, "HasValue");
PropertyInfo value_pi = TypeManager.GetProperty (type, "Value");
HasValue = has_value_pi.GetGetMethod (false);
Value = value_pi.GetGetMethod (false);
Constructor = type.GetConstructor (new Type[] { UnderlyingType });
}
}
public class Unwrap : Expression, IMemoryLocation, IAssignMethod
{
Expression expr;
NullableInfo info;
LocalTemporary temp;
bool has_temp;
protected Unwrap (Expression expr)
{
this.expr = expr;
this.loc = expr.Location;
}
public static Unwrap Create (Expression expr, EmitContext ec)
{
return new Unwrap (expr).Resolve (ec) as Unwrap;
}
public override Expression DoResolve (EmitContext ec)
{
expr = expr.Resolve (ec);
if (expr == null)
return null;
temp = new LocalTemporary (expr.Type);
info = new NullableInfo (expr.Type);
type = info.UnderlyingType;
eclass = expr.eclass;
return this;
}
public override void Emit (EmitContext ec)
{
AddressOf (ec, AddressOp.LoadStore);
ec.ig.EmitCall (OpCodes.Call, info.Value, null);
}
public void EmitCheck (EmitContext ec)
{
AddressOf (ec, AddressOp.LoadStore);
ec.ig.EmitCall (OpCodes.Call, info.HasValue, null);
}
public void Store (EmitContext ec)
{
create_temp (ec);
}
void create_temp (EmitContext ec)
{
if ((temp != null) && !has_temp) {
expr.Emit (ec);
temp.Store (ec);
has_temp = true;
}
}
public void AddressOf (EmitContext ec, AddressOp mode)
{
create_temp (ec);
if (temp != null)
temp.AddressOf (ec, AddressOp.LoadStore);
else
((IMemoryLocation) expr).AddressOf (ec, AddressOp.LoadStore);
}
public void Emit (EmitContext ec, bool leave_copy)
{
create_temp (ec);
if (leave_copy) {
if (temp != null)
temp.Emit (ec);
else
expr.Emit (ec);
}
Emit (ec);
}
public void EmitAssign (EmitContext ec, Expression source,
bool leave_copy, bool prepare_for_load)
{
InternalWrap wrap = new InternalWrap (source, info, loc);
((IAssignMethod) expr).EmitAssign (ec, wrap, leave_copy, false);
}
protected class InternalWrap : Expression
{
public Expression expr;
public NullableInfo info;
public InternalWrap (Expression expr, NullableInfo info, Location loc)
{
this.expr = expr;
this.info = info;
this.loc = loc;
type = info.Type;
eclass = ExprClass.Value;
}
public override Expression DoResolve (EmitContext ec)
{
return this;
}
public override void Emit (EmitContext ec)
{
expr.Emit (ec);
ec.ig.Emit (OpCodes.Newobj, info.Constructor);
}
}
}
public class Wrap : Expression
{
Expression expr;
NullableInfo info;
protected Wrap (Expression expr)
{
this.expr = expr;
this.loc = expr.Location;
}
public static Wrap Create (Expression expr, EmitContext ec)
{
return new Wrap (expr).Resolve (ec) as Wrap;
}
public override Expression DoResolve (EmitContext ec)
{
expr = expr.Resolve (ec);
if (expr == null)
return null;
TypeExpr target_type = new NullableType (expr.Type, loc);
target_type = target_type.ResolveAsTypeTerminal (ec, false);
if (target_type == null)
return null;
type = target_type.Type;
info = new NullableInfo (type);
eclass = ExprClass.Value;
return this;
}
public override void Emit (EmitContext ec)
{
expr.Emit (ec);
ec.ig.Emit (OpCodes.Newobj, info.Constructor);
}
}
public class NullableLiteral : NullLiteral, IMemoryLocation {
public NullableLiteral (Type target_type, Location loc)
: base (loc)
{
this.type = target_type;
eclass = ExprClass.Value;
}
public override Expression DoResolve (EmitContext ec)
{
return this;
}
public override void Emit (EmitContext ec)
{
LocalTemporary value_target = new LocalTemporary (type);
value_target.AddressOf (ec, AddressOp.Store);
ec.ig.Emit (OpCodes.Initobj, type);
value_target.Emit (ec);
}
public void AddressOf (EmitContext ec, AddressOp Mode)
{
LocalTemporary value_target = new LocalTemporary (type);
value_target.AddressOf (ec, AddressOp.Store);
ec.ig.Emit (OpCodes.Initobj, type);
((IMemoryLocation) value_target).AddressOf (ec, Mode);
}
}
public abstract class Lifted : Expression, IMemoryLocation
{
Expression expr, underlying, wrap, null_value;
Unwrap unwrap;
protected Lifted (Expression expr, Location loc)
{
this.expr = expr;
this.loc = loc;
}
public override Expression DoResolve (EmitContext ec)
{
expr = expr.Resolve (ec);
if (expr == null)
return null;
unwrap = Unwrap.Create (expr, ec);
if (unwrap == null)
return null;
underlying = ResolveUnderlying (unwrap, ec);
if (underlying == null)
return null;
wrap = Wrap.Create (underlying, ec);
if (wrap == null)
return null;
null_value = new NullableLiteral (wrap.Type, loc).Resolve (ec);
if (null_value == null)
return null;
type = wrap.Type;
eclass = ExprClass.Value;
return this;
}
protected abstract Expression ResolveUnderlying (Expression unwrap, EmitContext ec);
public override void Emit (EmitContext ec)
{
ILGenerator ig = ec.ig;
Label is_null_label = ig.DefineLabel ();
Label end_label = ig.DefineLabel ();
unwrap.EmitCheck (ec);
ig.Emit (OpCodes.Brfalse, is_null_label);
wrap.Emit (ec);
ig.Emit (OpCodes.Br, end_label);
ig.MarkLabel (is_null_label);
null_value.Emit (ec);
ig.MarkLabel (end_label);
}
public void AddressOf (EmitContext ec, AddressOp mode)
{
unwrap.AddressOf (ec, mode);
}
}
public class LiftedConversion : Lifted
{
public readonly bool IsUser;
public readonly bool IsExplicit;
public readonly Type TargetType;
public LiftedConversion (Expression expr, Type target_type, bool is_user,
bool is_explicit, Location loc)
: base (expr, loc)
{
this.IsUser = is_user;
this.IsExplicit = is_explicit;
this.TargetType = target_type;
}
protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
{
Type type = TypeManager.GetTypeArguments (TargetType) [0];
if (IsUser) {
return Convert.UserDefinedConversion (ec, unwrap, type, loc, IsExplicit);
} else {
if (IsExplicit)
return Convert.ExplicitConversion (ec, unwrap, type, loc);
else
return Convert.ImplicitConversion (ec, unwrap, type, loc);
}
}
}
public class LiftedUnaryOperator : Lifted
{
public readonly Unary.Operator Oper;
public LiftedUnaryOperator (Unary.Operator op, Expression expr, Location loc)
: base (expr, loc)
{
this.Oper = op;
}
protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
{
return new Unary (Oper, unwrap, loc);
}
}
public class LiftedConditional : Lifted
{
Expression true_expr, false_expr;
public LiftedConditional (Expression expr, Expression true_expr, Expression false_expr,
Location loc)
: base (expr, loc)
{
this.true_expr = true_expr;
this.false_expr = false_expr;
}
protected override Expression ResolveUnderlying (Expression unwrap, EmitContext ec)
{
return new Conditional (unwrap, true_expr, false_expr);
}
}
public class LiftedBinaryOperator : Expression
{
public readonly Binary.Operator Oper;
Expression left, right, original_left, original_right;
Expression underlying, null_value, bool_wrap;
Unwrap left_unwrap, right_unwrap;
bool is_equality, is_comparision, is_boolean;
public LiftedBinaryOperator (Binary.Operator op, Expression left, Expression right,
Location loc)
{
this.Oper = op;
this.left = original_left = left;
this.right = original_right = right;
this.loc = loc;
}
public override Expression DoResolve (EmitContext ec)
{
if (TypeManager.IsNullableType (left.Type)) {
left = left_unwrap = Unwrap.Create (left, ec);
if (left == null)
return null;
}
if (TypeManager.IsNullableType (right.Type)) {
right = right_unwrap = Unwrap.Create (right, ec);
if (right == null)
return null;
}
if ((Oper == Binary.Operator.LogicalAnd) ||
(Oper == Binary.Operator.LogicalOr)) {
Binary.Error_OperatorCannotBeApplied (
loc, Binary.OperName (Oper),
original_left.GetSignatureForError (),
original_right.GetSignatureForError ());
return null;
}
if (((Oper == Binary.Operator.BitwiseAnd) || (Oper == Binary.Operator.BitwiseOr)) &&
((left.Type == TypeManager.bool_type) && (right.Type == TypeManager.bool_type))) {
Expression empty = new EmptyExpression (TypeManager.bool_type);
bool_wrap = Wrap.Create (empty, ec);
null_value = new NullableLiteral (bool_wrap.Type, loc).Resolve (ec);
type = bool_wrap.Type;
is_boolean = true;
} else if ((Oper == Binary.Operator.Equality) || (Oper == Binary.Operator.Inequality)) {
if (!(left is NullLiteral) && !(right is NullLiteral)) {
underlying = new Binary (Oper, left, right).Resolve (ec);
if (underlying == null)
return null;
}
type = TypeManager.bool_type;
is_equality = true;
} else if ((Oper == Binary.Operator.LessThan) ||
(Oper == Binary.Operator.GreaterThan) ||
(Oper == Binary.Operator.LessThanOrEqual) ||
(Oper == Binary.Operator.GreaterThanOrEqual)) {
underlying = new Binary (Oper, left, right).Resolve (ec);
if (underlying == null)
return null;
type = TypeManager.bool_type;
is_comparision = true;
} else {
underlying = new Binary (Oper, left, right).Resolve (ec);
if (underlying == null)
return null;
underlying = Wrap.Create (underlying, ec);
if (underlying == null)
return null;
type = underlying.Type;
null_value = new NullableLiteral (type, loc).Resolve (ec);
}
eclass = ExprClass.Value;
return this;
}
void EmitBoolean (EmitContext ec)
{
ILGenerator ig = ec.ig;
Label left_is_null_label = ig.DefineLabel ();
Label right_is_null_label = ig.DefineLabel ();
Label is_null_label = ig.DefineLabel ();
Label wrap_label = ig.DefineLabel ();
Label end_label = ig.DefineLabel ();
if (left_unwrap != null) {
left_unwrap.EmitCheck (ec);
ig.Emit (OpCodes.Brfalse, left_is_null_label);
}
left.Emit (ec);
ig.Emit (OpCodes.Dup);
if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
ig.Emit (OpCodes.Brtrue, wrap_label);
else
ig.Emit (OpCodes.Brfalse, wrap_label);
if (right_unwrap != null) {
right_unwrap.EmitCheck (ec);
ig.Emit (OpCodes.Brfalse, right_is_null_label);
}
if ((Oper == Binary.Operator.LogicalAnd) || (Oper == Binary.Operator.LogicalOr))
ig.Emit (OpCodes.Pop);
right.Emit (ec);
if (Oper == Binary.Operator.BitwiseOr)
ig.Emit (OpCodes.Or);
else if (Oper == Binary.Operator.BitwiseAnd)
ig.Emit (OpCodes.And);
ig.Emit (OpCodes.Br, wrap_label);
ig.MarkLabel (left_is_null_label);
if (right_unwrap != null) {
right_unwrap.EmitCheck (ec);
ig.Emit (OpCodes.Brfalse, is_null_label);
}
right.Emit (ec);
ig.Emit (OpCodes.Dup);
if ((Oper == Binary.Operator.BitwiseOr) || (Oper == Binary.Operator.LogicalOr))
ig.Emit (OpCodes.Brtrue, wrap_label);
else
ig.Emit (OpCodes.Brfalse, wrap_label);
ig.MarkLabel (right_is_null_label);
ig.Emit (OpCodes.Pop);
ig.MarkLabel (is_null_label);
null_value.Emit (ec);
ig.Emit (OpCodes.Br, end_label);
ig.MarkLabel (wrap_label);
ig.Emit (OpCodes.Nop);
bool_wrap.Emit (ec);
ig.Emit (OpCodes.Nop);
ig.MarkLabel (end_label);
}
void EmitEquality (EmitContext ec)
{
ILGenerator ig = ec.ig;
// Given 'X? x;' for any value type X: 'x != null' is the same as 'x.HasValue'
if (left is NullLiteral) {
if (right_unwrap == null)
throw new InternalErrorException ();
right_unwrap.EmitCheck (ec);
if (Oper == Binary.Operator.Equality) {
ig.Emit (OpCodes.Ldc_I4_0);
ig.Emit (OpCodes.Ceq);
}
return;
}
if (right is NullLiteral) {
if (left_unwrap == null)
throw new InternalErrorException ();
left_unwrap.EmitCheck (ec);
if (Oper == Binary.Operator.Equality) {
ig.Emit (OpCodes.Ldc_I4_0);
ig.Emit (OpCodes.Ceq);
}
return;
}
Label both_have_value_label = ig.DefineLabel ();
Label end_label = ig.DefineLabel ();
if (left_unwrap != null && right_unwrap != null) {
Label dissimilar_label = ig.DefineLabel ();
left_unwrap.EmitCheck (ec);
ig.Emit (OpCodes.Dup);
right_unwrap.EmitCheck (ec);
ig.Emit (OpCodes.Bne_Un, dissimilar_label);
ig.Emit (OpCodes.Brtrue, both_have_value_label);
// both are null
if (Oper == Binary.Operator.Equality)
ig.Emit (OpCodes.Ldc_I4_1);
else
ig.Emit (OpCodes.Ldc_I4_0);
ig.Emit (OpCodes.Br, end_label);
ig.MarkLabel (dissimilar_label);
ig.Emit (OpCodes.Pop);
} else if (left_unwrap != null) {
left_unwrap.EmitCheck (ec);
ig.Emit (OpCodes.Brtrue, both_have_value_label);
} else if (right_unwrap != null) {
right_unwrap.EmitCheck (ec);
ig.Emit (OpCodes.Brtrue, both_have_value_label);
} else {
throw new InternalErrorException ("shouldn't get here");
}
// one is null while the other isn't
if (Oper == Binary.Operator.Equality)
ig.Emit (OpCodes.Ldc_I4_0);
else
ig.Emit (OpCodes.Ldc_I4_1);
ig.Emit (OpCodes.Br, end_label);
ig.MarkLabel (both_have_value_label);
underlying.Emit (ec);
ig.MarkLabel (end_label);
}
void EmitComparision (EmitContext ec)
{
ILGenerator ig = ec.ig;
Label is_null_label = ig.DefineLabel ();
Label end_label = ig.DefineLabel ();
if (left_unwrap != null) {
left_unwrap.EmitCheck (ec);
ig.Emit (OpCodes.Brfalse, is_null_label);
}
if (right_unwrap != null) {
right_unwrap.EmitCheck (ec);
ig.Emit (OpCodes.Brfalse, is_null_label);
}
underlying.Emit (ec);
ig.Emit (OpCodes.Br, end_label);
ig.MarkLabel (is_null_label);
ig.Emit (OpCodes.Ldc_I4_0);
ig.MarkLabel (end_label);
}
public override void Emit (EmitContext ec)
{
if (left_unwrap != null)
left_unwrap.Store (ec);
if (right_unwrap != null)
right_unwrap.Store (ec);
if (is_boolean) {
EmitBoolean (ec);
return;
} else if (is_equality) {
EmitEquality (ec);
return;
} else if (is_comparision) {
EmitComparision (ec);
return;
}
ILGenerator ig = ec.ig;
Label is_null_label = ig.DefineLabel ();
Label end_label = ig.DefineLabel ();
if (left_unwrap != null) {
left_unwrap.EmitCheck (ec);
ig.Emit (OpCodes.Brfalse, is_null_label);
}
if (right_unwrap != null) {
right_unwrap.EmitCheck (ec);
ig.Emit (OpCodes.Brfalse, is_null_label);
}
underlying.Emit (ec);
ig.Emit (OpCodes.Br, end_label);
ig.MarkLabel (is_null_label);
null_value.Emit (ec);
ig.MarkLabel (end_label);
}
}
public class OperatorTrueOrFalse : Expression
{
public readonly bool IsTrue;
Expression expr;
Unwrap unwrap;
public OperatorTrueOrFalse (Expression expr, bool is_true, Location loc)
{
this.IsTrue = is_true;
this.expr = expr;
this.loc = loc;
}
public override Expression DoResolve (EmitContext ec)
{
unwrap = Unwrap.Create (expr, ec);
if (unwrap == null)
return null;
if (unwrap.Type != TypeManager.bool_type)
return null;
type = TypeManager.bool_type;
eclass = ExprClass.Value;
return this;
}
public override void Emit (EmitContext ec)
{
ILGenerator ig = ec.ig;
Label is_null_label = ig.DefineLabel ();
Label end_label = ig.DefineLabel ();
unwrap.EmitCheck (ec);
ig.Emit (OpCodes.Brfalse, is_null_label);
unwrap.Emit (ec);
if (!IsTrue) {
ig.Emit (OpCodes.Ldc_I4_0);
ig.Emit (OpCodes.Ceq);
}
ig.Emit (OpCodes.Br, end_label);
ig.MarkLabel (is_null_label);
ig.Emit (OpCodes.Ldc_I4_0);
ig.MarkLabel (end_label);
}
}
public class NullCoalescingOperator : Expression
{
Expression left, right;
Expression expr;
Unwrap unwrap;
public NullCoalescingOperator (Expression left, Expression right, Location loc)
{
this.left = left;
this.right = right;
this.loc = loc;
eclass = ExprClass.Value;
}
public override Expression DoResolve (EmitContext ec)
{
if (type != null)
return this;
left = left.Resolve (ec);
if (left == null)
return null;
right = right.Resolve (ec);
if (right == null)
return null;
Type ltype = left.Type, rtype = right.Type;
if (!TypeManager.IsNullableType (ltype) && ltype.IsValueType) {
Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
return null;
}
if (TypeManager.IsNullableType (ltype)) {
NullableInfo info = new NullableInfo (ltype);
unwrap = Unwrap.Create (left, ec);
if (unwrap == null)
return null;
expr = Convert.ImplicitConversion (ec, right, info.UnderlyingType, loc);
if (expr != null) {
left = unwrap;
type = expr.Type;
return this;
}
}
expr = Convert.ImplicitConversion (ec, right, ltype, loc);
if (expr != null) {
type = expr.Type;
return this;
}
Expression left_null = unwrap != null ? unwrap : left;
expr = Convert.ImplicitConversion (ec, left_null, rtype, loc);
if (expr != null) {
left = expr;
expr = right;
type = rtype;
return this;
}
Binary.Error_OperatorCannotBeApplied (loc, "??", ltype, rtype);
return null;
}
public override void Emit (EmitContext ec)
{
ILGenerator ig = ec.ig;
Label is_null_label = ig.DefineLabel ();
Label end_label = ig.DefineLabel ();
if (unwrap != null) {
unwrap.EmitCheck (ec);
ig.Emit (OpCodes.Brfalse, is_null_label);
left.Emit (ec);
ig.Emit (OpCodes.Br, end_label);
ig.MarkLabel (is_null_label);
expr.Emit (ec);
ig.MarkLabel (end_label);
} else {
left.Emit (ec);
ig.Emit (OpCodes.Dup);
ig.Emit (OpCodes.Brtrue, end_label);
ig.MarkLabel (is_null_label);
ig.Emit (OpCodes.Pop);
expr.Emit (ec);
ig.MarkLabel (end_label);
}
}
}
public class LiftedUnaryMutator : ExpressionStatement
{
public readonly UnaryMutator.Mode Mode;
Expression expr, null_value;
UnaryMutator underlying;
Unwrap unwrap;
public LiftedUnaryMutator (UnaryMutator.Mode mode, Expression expr, Location loc)
{
this.expr = expr;
this.Mode = mode;
this.loc = loc;
eclass = ExprClass.Value;
}
public override Expression DoResolve (EmitContext ec)
{
expr = expr.Resolve (ec);
if (expr == null)
return null;
unwrap = Unwrap.Create (expr, ec);
if (unwrap == null)
return null;
underlying = (UnaryMutator) new UnaryMutator (Mode, unwrap, loc).Resolve (ec);
if (underlying == null)
return null;
null_value = new NullableLiteral (expr.Type, loc).Resolve (ec);
if (null_value == null)
return null;
type = expr.Type;
return this;
}
void DoEmit (EmitContext ec, bool is_expr)
{
ILGenerator ig = ec.ig;
Label is_null_label = ig.DefineLabel ();
Label end_label = ig.DefineLabel ();
unwrap.EmitCheck (ec);
ig.Emit (OpCodes.Brfalse, is_null_label);
if (is_expr)
underlying.Emit (ec);
else
underlying.EmitStatement (ec);
ig.Emit (OpCodes.Br, end_label);
ig.MarkLabel (is_null_label);
if (is_expr)
null_value.Emit (ec);
ig.MarkLabel (end_label);
}
public override void Emit (EmitContext ec)
{
DoEmit (ec, true);
}
public override void EmitStatement (EmitContext ec)
{
DoEmit (ec, false);
}
}
}
}
|