1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856
|
//
// ecore.cs: Core of the Expression representation for the intermediate tree.
//
// Author:
// Miguel de Icaza (miguel@ximian.com)
// Marek Safar (marek.safar@gmail.com)
//
// Copyright 2001, 2002, 2003 Ximian, Inc.
// Copyright 2003-2008 Novell, Inc.
// Copyright 2011-2012 Xamarin Inc.
//
//
using System;
using System.Collections.Generic;
using System.Text;
using SLE = System.Linq.Expressions;
using System.Linq;
#if STATIC
using IKVM.Reflection;
using IKVM.Reflection.Emit;
#else
using System.Reflection;
using System.Reflection.Emit;
#endif
namespace Mono.CSharp {
/// <remarks>
/// The ExprClass class contains the is used to pass the
/// classification of an expression (value, variable, namespace,
/// type, method group, property access, event access, indexer access,
/// nothing).
/// </remarks>
public enum ExprClass : byte {
Unresolved = 0,
Value,
Variable,
Namespace,
Type,
TypeParameter,
MethodGroup,
PropertyAccess,
EventAccess,
IndexerAccess,
Nothing,
}
/// <remarks>
/// This is used to tell Resolve in which types of expressions we're
/// interested.
/// </remarks>
[Flags]
public enum ResolveFlags {
// Returns Value, Variable, PropertyAccess, EventAccess or IndexerAccess.
VariableOrValue = 1,
// Returns a type expression.
Type = 1 << 1,
// Returns a method group.
MethodGroup = 1 << 2,
TypeParameter = 1 << 3,
// Mask of all the expression class flags.
MaskExprClass = VariableOrValue | Type | MethodGroup | TypeParameter,
}
//
// This is just as a hint to AddressOf of what will be done with the
// address.
[Flags]
public enum AddressOp {
Store = 1,
Load = 2,
LoadStore = 3
};
/// <summary>
/// This interface is implemented by variables
/// </summary>
public interface IMemoryLocation {
/// <summary>
/// The AddressOf method should generate code that loads
/// the address of the object and leaves it on the stack.
///
/// The `mode' argument is used to notify the expression
/// of whether this will be used to read from the address or
/// write to the address.
///
/// This is just a hint that can be used to provide good error
/// reporting, and should have no other side effects.
/// </summary>
void AddressOf (EmitContext ec, AddressOp mode);
}
//
// An expressions resolved as a direct variable reference
//
public interface IVariableReference : IFixedExpression
{
bool IsHoisted { get; }
string Name { get; }
VariableInfo VariableInfo { get; }
void SetHasAddressTaken ();
}
//
// Implemented by an expression which could be or is always
// fixed
//
public interface IFixedExpression
{
bool IsFixed { get; }
}
public interface IExpressionCleanup
{
void EmitCleanup (EmitContext ec);
}
/// <remarks>
/// Base class for expressions
/// </remarks>
public abstract class Expression {
public ExprClass eclass;
protected TypeSpec type;
protected Location loc;
public TypeSpec Type {
get { return type; }
set { type = value; }
}
public virtual bool IsSideEffectFree {
get {
return false;
}
}
public Location Location {
get { return loc; }
}
public virtual bool IsNull {
get {
return false;
}
}
//
// Used to workaround parser limitation where we cannot get
// start of statement expression location
//
public virtual Location StartLocation {
get {
return loc;
}
}
public virtual MethodGroupExpr CanReduceLambda (AnonymousMethodBody body)
{
//
// Return method-group expression when the expression can be used as
// lambda replacement. A good example is array sorting where instead of
// code like
//
// Array.Sort (s, (a, b) => String.Compare (a, b));
//
// we can use method group directly
//
// Array.Sort (s, String.Compare);
//
// Correct overload will be used because we do the reduction after
// best candidate was found.
//
return null;
}
//
// Returns true when the expression during Emit phase breaks stack
// by using await expression
//
public virtual bool ContainsEmitWithAwait ()
{
return false;
}
/// <summary>
/// Performs semantic analysis on the Expression
/// </summary>
///
/// <remarks>
/// The Resolve method is invoked to perform the semantic analysis
/// on the node.
///
/// The return value is an expression (it can be the
/// same expression in some cases) or a new
/// expression that better represents this node.
///
/// For example, optimizations of Unary (LiteralInt)
/// would return a new LiteralInt with a negated
/// value.
///
/// If there is an error during semantic analysis,
/// then an error should be reported (using Report)
/// and a null value should be returned.
///
/// There are two side effects expected from calling
/// Resolve(): the the field variable "eclass" should
/// be set to any value of the enumeration
/// `ExprClass' and the type variable should be set
/// to a valid type (this is the type of the
/// expression).
/// </remarks>
protected abstract Expression DoResolve (ResolveContext rc);
public virtual Expression DoResolveLValue (ResolveContext rc, Expression right_side)
{
return null;
}
//
// This is used if the expression should be resolved as a type or namespace name.
// the default implementation fails.
//
public virtual TypeSpec ResolveAsType (IMemberContext mc)
{
ResolveContext ec = new ResolveContext (mc);
Expression e = Resolve (ec);
if (e != null)
e.Error_UnexpectedKind (ec, ResolveFlags.Type, loc);
return null;
}
public static void ErrorIsInaccesible (IMemberContext rc, string member, Location loc)
{
rc.Module.Compiler.Report.Error (122, loc, "`{0}' is inaccessible due to its protection level", member);
}
public void Error_ExpressionMustBeConstant (ResolveContext rc, Location loc, string e_name)
{
rc.Report.Error (133, loc, "The expression being assigned to `{0}' must be constant", e_name);
}
public void Error_ConstantCanBeInitializedWithNullOnly (ResolveContext rc, TypeSpec type, Location loc, string name)
{
rc.Report.Error (134, loc, "A constant `{0}' of reference type `{1}' can only be initialized with null",
name, type.GetSignatureForError ());
}
protected virtual void Error_InvalidExpressionStatement (Report report, Location loc)
{
report.Error (201, loc, "Only assignment, call, increment, decrement, await, and new object expressions can be used as a statement");
}
public void Error_InvalidExpressionStatement (BlockContext bc)
{
Error_InvalidExpressionStatement (bc.Report, loc);
}
public void Error_InvalidExpressionStatement (Report report)
{
Error_InvalidExpressionStatement (report, loc);
}
public static void Error_VoidInvalidInTheContext (Location loc, Report Report)
{
Report.Error (1547, loc, "Keyword `void' cannot be used in this context");
}
public virtual void Error_ValueCannotBeConverted (ResolveContext ec, TypeSpec target, bool expl)
{
Error_ValueCannotBeConvertedCore (ec, loc, target, expl);
}
protected void Error_ValueCannotBeConvertedCore (ResolveContext ec, Location loc, TypeSpec target, bool expl)
{
// The error was already reported as CS1660
if (type == InternalType.AnonymousMethod)
return;
if (type == InternalType.ErrorType || target == InternalType.ErrorType)
return;
string from_type = type.GetSignatureForError ();
string to_type = target.GetSignatureForError ();
if (from_type == to_type) {
from_type = type.GetSignatureForErrorIncludingAssemblyName ();
to_type = target.GetSignatureForErrorIncludingAssemblyName ();
}
if (expl) {
ec.Report.Error (30, loc, "Cannot convert type `{0}' to `{1}'",
from_type, to_type);
return;
}
ec.Report.DisableReporting ();
bool expl_exists = Convert.ExplicitConversion (ec, this, target, Location.Null) != null;
ec.Report.EnableReporting ();
if (expl_exists) {
ec.Report.Error (266, loc,
"Cannot implicitly convert type `{0}' to `{1}'. An explicit conversion exists (are you missing a cast?)",
from_type, to_type);
} else {
ec.Report.Error (29, loc, "Cannot implicitly convert type `{0}' to `{1}'",
from_type, to_type);
}
}
public void Error_TypeArgumentsCannotBeUsed (IMemberContext context, MemberSpec member, int arity, Location loc)
{
// Better message for possible generic expressions
if (member != null && (member.Kind & MemberKind.GenericMask) != 0) {
var report = context.Module.Compiler.Report;
report.SymbolRelatedToPreviousError (member);
if (member is TypeSpec)
member = ((TypeSpec) member).GetDefinition ();
else
member = ((MethodSpec) member).GetGenericMethodDefinition ();
string name = member.Kind == MemberKind.Method ? "method" : "type";
if (member.IsGeneric) {
report.Error (305, loc, "Using the generic {0} `{1}' requires `{2}' type argument(s)",
name, member.GetSignatureForError (), member.Arity.ToString ());
} else {
report.Error (308, loc, "The non-generic {0} `{1}' cannot be used with the type arguments",
name, member.GetSignatureForError ());
}
} else {
Error_TypeArgumentsCannotBeUsed (context, ExprClassName, GetSignatureForError (), loc);
}
}
public void Error_TypeArgumentsCannotBeUsed (IMemberContext context, string exprType, string name, Location loc)
{
context.Module.Compiler.Report.Error (307, loc, "The {0} `{1}' cannot be used with type arguments",
exprType, name);
}
protected virtual void Error_TypeDoesNotContainDefinition (ResolveContext ec, TypeSpec type, string name)
{
Error_TypeDoesNotContainDefinition (ec, loc, type, name);
}
public static void Error_TypeDoesNotContainDefinition (ResolveContext ec, Location loc, TypeSpec type, string name)
{
ec.Report.SymbolRelatedToPreviousError (type);
ec.Report.Error (117, loc, "`{0}' does not contain a definition for `{1}'",
type.GetSignatureForError (), name);
}
public virtual void Error_ValueAssignment (ResolveContext rc, Expression rhs)
{
if (rhs == EmptyExpression.LValueMemberAccess || rhs == EmptyExpression.LValueMemberOutAccess) {
// Already reported as CS1612
} else if (rhs == EmptyExpression.OutAccess) {
rc.Report.Error (1510, loc, "A ref or out argument must be an assignable variable");
} else {
rc.Report.Error (131, loc, "The left-hand side of an assignment must be a variable, a property or an indexer");
}
}
protected void Error_VoidPointerOperation (ResolveContext rc)
{
rc.Report.Error (242, loc, "The operation in question is undefined on void pointers");
}
public ResolveFlags ExprClassToResolveFlags {
get {
switch (eclass) {
case ExprClass.Type:
case ExprClass.Namespace:
return ResolveFlags.Type;
case ExprClass.MethodGroup:
return ResolveFlags.MethodGroup;
case ExprClass.TypeParameter:
return ResolveFlags.TypeParameter;
case ExprClass.Value:
case ExprClass.Variable:
case ExprClass.PropertyAccess:
case ExprClass.EventAccess:
case ExprClass.IndexerAccess:
return ResolveFlags.VariableOrValue;
default:
throw new InternalErrorException (loc.ToString () + " " + GetType () + " ExprClass is Invalid after resolve");
}
}
}
//
// Implements identical simple name and type-name resolution
//
public Expression ProbeIdenticalTypeName (ResolveContext rc, Expression left, SimpleName name)
{
var t = left.Type;
if (t.Kind == MemberKind.InternalCompilerType || t is ElementTypeSpec || t.Arity > 0)
return left;
// In a member access of the form E.I, if E is a single identifier, and if the meaning of E as a simple-name is
// a constant, field, property, local variable, or parameter with the same type as the meaning of E as a type-name
if (left is MemberExpr || left is VariableReference) {
var identical_type = rc.LookupNamespaceOrType (name.Name, 0, LookupMode.Probing, loc) as TypeExpr;
if (identical_type != null && identical_type.Type == left.Type)
return identical_type;
}
return left;
}
public virtual string GetSignatureForError ()
{
return type.GetDefinition ().GetSignatureForError ();
}
/// <summary>
/// Resolves an expression and performs semantic analysis on it.
/// </summary>
///
/// <remarks>
/// Currently Resolve wraps DoResolve to perform sanity
/// checking and assertion checking on what we expect from Resolve.
/// </remarks>
public Expression Resolve (ResolveContext ec, ResolveFlags flags)
{
if (eclass != ExprClass.Unresolved) {
if ((flags & ExprClassToResolveFlags) == 0) {
Error_UnexpectedKind (ec, flags, loc);
return null;
}
return this;
}
Expression e;
try {
e = DoResolve (ec);
if (e == null)
return null;
if ((flags & e.ExprClassToResolveFlags) == 0) {
e.Error_UnexpectedKind (ec, flags, loc);
return null;
}
if (e.type == null)
throw new InternalErrorException ("Expression `{0}' didn't set its type in DoResolve", e.GetType ());
return e;
} catch (Exception ex) {
if (loc.IsNull || ec.Module.Compiler.Settings.DebugFlags > 0 || ex is CompletionResult || ec.Report.IsDisabled || ex is FatalException)
throw;
ec.Report.Error (584, loc, "Internal compiler error: {0}", ex.Message);
return ErrorExpression.Instance; // TODO: Add location
}
}
/// <summary>
/// Resolves an expression and performs semantic analysis on it.
/// </summary>
public Expression Resolve (ResolveContext rc)
{
return Resolve (rc, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup);
}
/// <summary>
/// Resolves an expression for LValue assignment
/// </summary>
///
/// <remarks>
/// Currently ResolveLValue wraps DoResolveLValue to perform sanity
/// checking and assertion checking on what we expect from Resolve
/// </remarks>
public Expression ResolveLValue (ResolveContext ec, Expression right_side)
{
int errors = ec.Report.Errors;
bool out_access = right_side == EmptyExpression.OutAccess;
Expression e = DoResolveLValue (ec, right_side);
if (e != null && out_access && !(e is IMemoryLocation)) {
// FIXME: There's no problem with correctness, the 'Expr = null' handles that.
// Enabling this 'throw' will "only" result in deleting useless code elsewhere,
//throw new InternalErrorException ("ResolveLValue didn't return an IMemoryLocation: " +
// e.GetType () + " " + e.GetSignatureForError ());
e = null;
}
if (e == null) {
if (errors == ec.Report.Errors) {
Error_ValueAssignment (ec, right_side);
}
return null;
}
if (e.eclass == ExprClass.Unresolved)
throw new Exception ("Expression " + e + " ExprClass is Invalid after resolve");
if ((e.type == null) && !(e is GenericTypeExpr))
throw new Exception ("Expression " + e + " did not set its type after Resolve");
return e;
}
public Constant ResolveLabelConstant (ResolveContext rc)
{
var expr = Resolve (rc);
if (expr == null)
return null;
Constant c = expr as Constant;
if (c == null) {
if (c.type != InternalType.ErrorType)
rc.Report.Error (150, StartLocation, "A constant value is expected");
return null;
}
return c;
}
public virtual void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
{
rc.Module.Compiler.Report.Error (182, loc,
"An attribute argument must be a constant expression, typeof expression or array creation expression");
}
/// <summary>
/// Emits the code for the expression
/// </summary>
///
/// <remarks>
/// The Emit method is invoked to generate the code
/// for the expression.
/// </remarks>
public abstract void Emit (EmitContext ec);
// Emit code to branch to @target if this expression is equivalent to @on_true.
// The default implementation is to emit the value, and then emit a brtrue or brfalse.
// Subclasses can provide more efficient implementations, but those MUST be equivalent,
// including the use of conditional branches. Note also that a branch MUST be emitted
public virtual void EmitBranchable (EmitContext ec, Label target, bool on_true)
{
Emit (ec);
ec.Emit (on_true ? OpCodes.Brtrue : OpCodes.Brfalse, target);
}
// Emit this expression for its side effects, not for its value.
// The default implementation is to emit the value, and then throw it away.
// Subclasses can provide more efficient implementations, but those MUST be equivalent
public virtual void EmitSideEffect (EmitContext ec)
{
Emit (ec);
ec.Emit (OpCodes.Pop);
}
//
// Emits the expression into temporary field variable. The method
// should be used for await expressions only
//
public virtual Expression EmitToField (EmitContext ec)
{
//
// This is the await prepare Emit method. When emitting code like
// a + b we emit code like
//
// a.Emit ()
// b.Emit ()
// Opcodes.Add
//
// For await a + await b we have to interfere the flow to keep the
// stack clean because await yields from the expression. The emit
// then changes to
//
// a = a.EmitToField () // a is changed to temporary field access
// b = b.EmitToField ()
// a.Emit ()
// b.Emit ()
// Opcodes.Add
//
//
// The idea is to emit expression and leave the stack empty with
// result value still available.
//
// Expressions should override this default implementation when
// optimized version can be provided (e.g. FieldExpr)
//
//
// We can optimize for side-effect free expressions, they can be
// emitted out of order
//
if (IsSideEffectFree)
return this;
bool needs_temporary = ContainsEmitWithAwait ();
if (!needs_temporary)
ec.EmitThis ();
// Emit original code
var field = EmitToFieldSource (ec);
if (field == null) {
//
// Store the result to temporary field when we
// cannot load `this' directly
//
field = ec.GetTemporaryField (type);
if (needs_temporary) {
//
// Create temporary local (we cannot load `this' before Emit)
//
var temp = ec.GetTemporaryLocal (type);
ec.Emit (OpCodes.Stloc, temp);
ec.EmitThis ();
ec.Emit (OpCodes.Ldloc, temp);
field.EmitAssignFromStack (ec);
ec.FreeTemporaryLocal (temp, type);
} else {
field.EmitAssignFromStack (ec);
}
}
return field;
}
protected virtual FieldExpr EmitToFieldSource (EmitContext ec)
{
//
// Default implementation calls Emit method
//
Emit (ec);
return null;
}
protected static void EmitExpressionsList (EmitContext ec, List<Expression> expressions)
{
if (ec.HasSet (BuilderContext.Options.AsyncBody)) {
bool contains_await = false;
for (int i = 1; i < expressions.Count; ++i) {
if (expressions[i].ContainsEmitWithAwait ()) {
contains_await = true;
break;
}
}
if (contains_await) {
for (int i = 0; i < expressions.Count; ++i) {
expressions[i] = expressions[i].EmitToField (ec);
}
}
}
for (int i = 0; i < expressions.Count; ++i) {
expressions[i].Emit (ec);
}
}
/// <summary>
/// Protected constructor. Only derivate types should
/// be able to be created
/// </summary>
protected Expression ()
{
}
/// <summary>
/// Returns a fully formed expression after a MemberLookup
/// </summary>
///
static Expression ExprClassFromMemberInfo (MemberSpec spec, Location loc)
{
if (spec is EventSpec)
return new EventExpr ((EventSpec) spec, loc);
if (spec is ConstSpec)
return new ConstantExpr ((ConstSpec) spec, loc);
if (spec is FieldSpec)
return new FieldExpr ((FieldSpec) spec, loc);
if (spec is PropertySpec)
return new PropertyExpr ((PropertySpec) spec, loc);
if (spec is TypeSpec)
return new TypeExpression (((TypeSpec) spec), loc);
return null;
}
public static MethodSpec ConstructorLookup (ResolveContext rc, TypeSpec type, ref Arguments args, Location loc)
{
var ctors = MemberCache.FindMembers (type, Constructor.ConstructorName, true);
if (ctors == null) {
rc.Report.SymbolRelatedToPreviousError (type);
if (type.IsStruct) {
// Report meaningful error for struct as they always have default ctor in C# context
OverloadResolver.Error_ConstructorMismatch (rc, type, args == null ? 0 : args.Count, loc);
} else {
rc.Report.Error (143, loc, "The class `{0}' has no constructors defined",
type.GetSignatureForError ());
}
return null;
}
var r = new OverloadResolver (ctors, OverloadResolver.Restrictions.NoBaseMembers, loc);
if (!rc.HasSet (ResolveContext.Options.BaseInitializer)) {
r.InstanceQualifier = new ConstructorInstanceQualifier (type);
}
return r.ResolveMember<MethodSpec> (rc, ref args);
}
[Flags]
public enum MemberLookupRestrictions
{
None = 0,
InvocableOnly = 1,
ExactArity = 1 << 2,
ReadAccess = 1 << 3
}
//
// Lookup type `queried_type' for code in class `container_type' with a qualifier of
// `qualifier_type' or null to lookup members in the current class.
//
public static Expression MemberLookup (IMemberContext rc, bool errorMode, TypeSpec queried_type, string name, int arity, MemberLookupRestrictions restrictions, Location loc)
{
var members = MemberCache.FindMembers (queried_type, name, false);
if (members == null)
return null;
MemberSpec non_method = null;
MemberSpec ambig_non_method = null;
do {
for (int i = 0; i < members.Count; ++i) {
var member = members[i];
// HACK: for events because +=/-= can appear at same class only, should use OverrideToBase there
if ((member.Modifiers & Modifiers.OVERRIDE) != 0 && member.Kind != MemberKind.Event)
continue;
if ((member.Modifiers & Modifiers.BACKING_FIELD) != 0 || member.Kind == MemberKind.Operator)
continue;
if ((arity > 0 || (restrictions & MemberLookupRestrictions.ExactArity) != 0) && member.Arity != arity)
continue;
if (!errorMode) {
if (!member.IsAccessible (rc))
continue;
//
// With runtime binder we can have a situation where queried type is inaccessible
// because it came via dynamic object, the check about inconsisted accessibility
// had no effect as the type was unknown during compilation
//
// class A {
// private class N { }
//
// public dynamic Foo ()
// {
// return new N ();
// }
// }
//
if (rc.Module.Compiler.IsRuntimeBinder && !member.DeclaringType.IsAccessible (rc))
continue;
}
if ((restrictions & MemberLookupRestrictions.InvocableOnly) != 0) {
if (member is MethodSpec) {
//
// Interface members that are hidden by class members are removed from the set. This
// step only has an effect if T is a type parameter and T has both an effective base
// class other than object and a non-empty effective interface set
//
var tps = queried_type as TypeParameterSpec;
if (tps != null && tps.HasTypeConstraint)
members = RemoveHiddenTypeParameterMethods (members);
return new MethodGroupExpr (members, queried_type, loc);
}
if (!Invocation.IsMemberInvocable (member))
continue;
}
if (non_method == null || member is MethodSpec || non_method.IsNotCSharpCompatible) {
non_method = member;
} else if (!errorMode && !member.IsNotCSharpCompatible) {
//
// Interface members that are hidden by class members are removed from the set when T is a type parameter and
// T has both an effective base class other than object and a non-empty effective interface set.
//
// The spec has more complex rules but we simply remove all members declared in an interface declaration.
//
var tps = queried_type as TypeParameterSpec;
if (tps != null && tps.HasTypeConstraint) {
if (non_method.DeclaringType.IsClass && member.DeclaringType.IsInterface)
continue;
if (non_method.DeclaringType.IsInterface && member.DeclaringType.IsInterface) {
non_method = member;
continue;
}
}
ambig_non_method = member;
}
}
if (non_method != null) {
if (ambig_non_method != null && rc != null) {
var report = rc.Module.Compiler.Report;
report.SymbolRelatedToPreviousError (non_method);
report.SymbolRelatedToPreviousError (ambig_non_method);
report.Error (229, loc, "Ambiguity between `{0}' and `{1}'",
non_method.GetSignatureForError (), ambig_non_method.GetSignatureForError ());
}
if (non_method is MethodSpec)
return new MethodGroupExpr (members, queried_type, loc);
return ExprClassFromMemberInfo (non_method, loc);
}
if (members[0].DeclaringType.BaseType == null)
members = null;
else
members = MemberCache.FindMembers (members[0].DeclaringType.BaseType, name, false);
} while (members != null);
return null;
}
static IList<MemberSpec> RemoveHiddenTypeParameterMethods (IList<MemberSpec> members)
{
if (members.Count < 2)
return members;
//
// If M is a method, then all non-method members declared in an interface declaration
// are removed from the set, and all methods with the same signature as M declared in
// an interface declaration are removed from the set
//
bool copied = false;
for (int i = 0; i < members.Count; ++i) {
var method = members[i] as MethodSpec;
if (method == null) {
if (!copied) {
copied = true;
members = new List<MemberSpec> (members);
}
members.RemoveAt (i--);
continue;
}
if (!method.DeclaringType.IsInterface)
continue;
for (int ii = 0; ii < members.Count; ++ii) {
var candidate = members[ii] as MethodSpec;
if (candidate == null || !candidate.DeclaringType.IsClass)
continue;
if (!TypeSpecComparer.Override.IsEqual (candidate.Parameters, method.Parameters))
continue;
if (!copied) {
copied = true;
members = new List<MemberSpec> (members);
}
members.RemoveAt (i--);
break;
}
}
return members;
}
protected virtual void Error_NegativeArrayIndex (ResolveContext ec, Location loc)
{
throw new NotImplementedException ();
}
public virtual void Error_OperatorCannotBeApplied (ResolveContext rc, Location loc, string oper, TypeSpec t)
{
if (t == InternalType.ErrorType)
return;
rc.Report.Error (23, loc, "The `{0}' operator cannot be applied to operand of type `{1}'",
oper, t.GetSignatureForError ());
}
protected void Error_PointerInsideExpressionTree (ResolveContext ec)
{
ec.Report.Error (1944, loc, "An expression tree cannot contain an unsafe pointer operation");
}
/// <summary>
/// Returns an expression that can be used to invoke operator true
/// on the expression if it exists.
/// </summary>
protected static Expression GetOperatorTrue (ResolveContext ec, Expression e, Location loc)
{
return GetOperatorTrueOrFalse (ec, e, true, loc);
}
/// <summary>
/// Returns an expression that can be used to invoke operator false
/// on the expression if it exists.
/// </summary>
protected static Expression GetOperatorFalse (ResolveContext ec, Expression e, Location loc)
{
return GetOperatorTrueOrFalse (ec, e, false, loc);
}
static Expression GetOperatorTrueOrFalse (ResolveContext ec, Expression e, bool is_true, Location loc)
{
var op = is_true ? Operator.OpType.True : Operator.OpType.False;
var methods = MemberCache.GetUserOperator (e.type, op, false);
if (methods == null)
return null;
Arguments arguments = new Arguments (1);
arguments.Add (new Argument (e));
var res = new OverloadResolver (methods, OverloadResolver.Restrictions.BaseMembersIncluded | OverloadResolver.Restrictions.NoBaseMembers, loc);
var oper = res.ResolveOperator (ec, ref arguments);
if (oper == null)
return null;
return new UserOperatorCall (oper, arguments, null, loc);
}
public virtual string ExprClassName
{
get {
switch (eclass){
case ExprClass.Unresolved:
return "Unresolved";
case ExprClass.Value:
return "value";
case ExprClass.Variable:
return "variable";
case ExprClass.Namespace:
return "namespace";
case ExprClass.Type:
return "type";
case ExprClass.MethodGroup:
return "method group";
case ExprClass.PropertyAccess:
return "property access";
case ExprClass.EventAccess:
return "event access";
case ExprClass.IndexerAccess:
return "indexer access";
case ExprClass.Nothing:
return "null";
case ExprClass.TypeParameter:
return "type parameter";
}
throw new Exception ("Should not happen");
}
}
/// <summary>
/// Reports that we were expecting `expr' to be of class `expected'
/// </summary>
public void Error_UnexpectedKind (IMemberContext ctx, Expression memberExpr, string expected, string was, Location loc)
{
var name = memberExpr.GetSignatureForError ();
ctx.Module.Compiler.Report.Error (118, loc, "`{0}' is a `{1}' but a `{2}' was expected", name, was, expected);
}
public virtual void Error_UnexpectedKind (ResolveContext ec, ResolveFlags flags, Location loc)
{
string [] valid = new string [4];
int count = 0;
if ((flags & ResolveFlags.VariableOrValue) != 0) {
valid [count++] = "variable";
valid [count++] = "value";
}
if ((flags & ResolveFlags.Type) != 0)
valid [count++] = "type";
if ((flags & ResolveFlags.MethodGroup) != 0)
valid [count++] = "method group";
if (count == 0)
valid [count++] = "unknown";
StringBuilder sb = new StringBuilder (valid [0]);
for (int i = 1; i < count - 1; i++) {
sb.Append ("', `");
sb.Append (valid [i]);
}
if (count > 1) {
sb.Append ("' or `");
sb.Append (valid [count - 1]);
}
ec.Report.Error (119, loc,
"Expression denotes a `{0}', where a `{1}' was expected", ExprClassName, sb.ToString ());
}
public static void UnsafeError (ResolveContext ec, Location loc)
{
UnsafeError (ec.Report, loc);
}
public static void UnsafeError (Report Report, Location loc)
{
Report.Error (214, loc, "Pointers and fixed size buffers may only be used in an unsafe context");
}
//
// Converts `source' to an int, uint, long or ulong.
//
protected Expression ConvertExpressionToArrayIndex (ResolveContext ec, Expression source)
{
var btypes = ec.BuiltinTypes;
if (source.type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
Arguments args = new Arguments (1);
args.Add (new Argument (source));
return new DynamicConversion (btypes.Int, CSharpBinderFlags.ConvertArrayIndex, args, loc).Resolve (ec);
}
Expression converted;
using (ec.Set (ResolveContext.Options.CheckedScope)) {
converted = Convert.ImplicitConversion (ec, source, btypes.Int, source.loc);
if (converted == null)
converted = Convert.ImplicitConversion (ec, source, btypes.UInt, source.loc);
if (converted == null)
converted = Convert.ImplicitConversion (ec, source, btypes.Long, source.loc);
if (converted == null)
converted = Convert.ImplicitConversion (ec, source, btypes.ULong, source.loc);
if (converted == null) {
source.Error_ValueCannotBeConverted (ec, btypes.Int, false);
return null;
}
}
//
// Only positive constants are allowed at compile time
//
Constant c = converted as Constant;
if (c != null && c.IsNegative)
Error_NegativeArrayIndex (ec, source.loc);
// No conversion needed to array index
if (converted.Type.BuiltinType == BuiltinTypeSpec.Type.Int)
return converted;
return new ArrayIndexCast (converted, btypes.Int).Resolve (ec);
}
//
// Derived classes implement this method by cloning the fields that
// could become altered during the Resolve stage
//
// Only expressions that are created for the parser need to implement
// this.
//
protected virtual void CloneTo (CloneContext clonectx, Expression target)
{
throw new NotImplementedException (
String.Format (
"CloneTo not implemented for expression {0}", this.GetType ()));
}
//
// Clones an expression created by the parser.
//
// We only support expressions created by the parser so far, not
// expressions that have been resolved (many more classes would need
// to implement CloneTo).
//
// This infrastructure is here merely for Lambda expressions which
// compile the same code using different type values for the same
// arguments to find the correct overload
//
public virtual Expression Clone (CloneContext clonectx)
{
Expression cloned = (Expression) MemberwiseClone ();
CloneTo (clonectx, cloned);
return cloned;
}
//
// Implementation of expression to expression tree conversion
//
public abstract Expression CreateExpressionTree (ResolveContext ec);
protected Expression CreateExpressionFactoryCall (ResolveContext ec, string name, Arguments args)
{
return CreateExpressionFactoryCall (ec, name, null, args, loc);
}
protected Expression CreateExpressionFactoryCall (ResolveContext ec, string name, TypeArguments typeArguments, Arguments args)
{
return CreateExpressionFactoryCall (ec, name, typeArguments, args, loc);
}
public static Expression CreateExpressionFactoryCall (ResolveContext ec, string name, TypeArguments typeArguments, Arguments args, Location loc)
{
return new Invocation (new MemberAccess (CreateExpressionTypeExpression (ec, loc), name, typeArguments, loc), args);
}
protected static TypeExpr CreateExpressionTypeExpression (ResolveContext ec, Location loc)
{
var t = ec.Module.PredefinedTypes.Expression.Resolve ();
if (t == null)
return null;
return new TypeExpression (t, loc);
}
//
// Implemented by all expressions which support conversion from
// compiler expression to invokable runtime expression. Used by
// dynamic C# binder.
//
public virtual SLE.Expression MakeExpression (BuilderContext ctx)
{
throw new NotImplementedException ("MakeExpression for " + GetType ());
}
public virtual object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
/// <summary>
/// This is just a base class for expressions that can
/// appear on statements (invocations, object creation,
/// assignments, post/pre increment and decrement). The idea
/// being that they would support an extra Emition interface that
/// does not leave a result on the stack.
/// </summary>
public abstract class ExpressionStatement : Expression
{
public ExpressionStatement ResolveStatement (BlockContext ec)
{
Expression e = Resolve (ec);
if (e == null)
return null;
ExpressionStatement es = e as ExpressionStatement;
if (es == null)
Error_InvalidExpressionStatement (ec);
//
// This is quite expensive warning, try to limit the damage
//
if (MemberAccess.IsValidDotExpression (e.Type) && !(e is Assign || e is Await)) {
WarningAsyncWithoutWait (ec, e);
}
return es;
}
static void WarningAsyncWithoutWait (BlockContext bc, Expression e)
{
if (bc.CurrentAnonymousMethod is AsyncInitializer) {
var awaiter = new AwaitStatement.AwaitableMemberAccess (e) {
ProbingMode = true
};
//
// Need to do full resolve because GetAwaiter can be extension method
// available only in this context
//
var mg = awaiter.Resolve (bc) as MethodGroupExpr;
if (mg == null)
return;
var arguments = new Arguments (0);
mg = mg.OverloadResolve (bc, ref arguments, null, OverloadResolver.Restrictions.ProbingOnly);
if (mg == null)
return;
//
// Use same check rules as for real await
//
var awaiter_definition = bc.Module.GetAwaiter (mg.BestCandidateReturnType);
if (!awaiter_definition.IsValidPattern || !awaiter_definition.INotifyCompletion)
return;
bc.Report.Warning (4014, 1, e.Location,
"The statement is not awaited and execution of current method continues before the call is completed. Consider using `await' operator");
return;
}
var inv = e as Invocation;
if (inv != null && inv.MethodGroup != null && inv.MethodGroup.BestCandidate.IsAsync) {
// The warning won't be reported for imported methods to maintain warning compatiblity with csc
bc.Report.Warning (4014, 1, e.Location,
"The statement is not awaited and execution of current method continues before the call is completed. Consider using `await' operator or calling `Wait' method");
return;
}
}
/// <summary>
/// Requests the expression to be emitted in a `statement'
/// context. This means that no new value is left on the
/// stack after invoking this method (constrasted with
/// Emit that will always leave a value on the stack).
/// </summary>
public abstract void EmitStatement (EmitContext ec);
public override void EmitSideEffect (EmitContext ec)
{
EmitStatement (ec);
}
}
/// <summary>
/// This kind of cast is used to encapsulate the child
/// whose type is child.Type into an expression that is
/// reported to return "return_type". This is used to encapsulate
/// expressions which have compatible types, but need to be dealt
/// at higher levels with.
///
/// For example, a "byte" expression could be encapsulated in one
/// of these as an "unsigned int". The type for the expression
/// would be "unsigned int".
///
/// </summary>
public abstract class TypeCast : Expression
{
protected readonly Expression child;
protected TypeCast (Expression child, TypeSpec return_type)
{
eclass = child.eclass;
loc = child.Location;
type = return_type;
this.child = child;
}
public Expression Child {
get {
return child;
}
}
public override bool ContainsEmitWithAwait ()
{
return child.ContainsEmitWithAwait ();
}
public override Expression CreateExpressionTree (ResolveContext ec)
{
Arguments args = new Arguments (2);
args.Add (new Argument (child.CreateExpressionTree (ec)));
args.Add (new Argument (new TypeOf (type, loc)));
if (type.IsPointer || child.Type.IsPointer)
Error_PointerInsideExpressionTree (ec);
return CreateExpressionFactoryCall (ec, ec.HasSet (ResolveContext.Options.CheckedScope) ? "ConvertChecked" : "Convert", args);
}
protected override Expression DoResolve (ResolveContext ec)
{
// This should never be invoked, we are born in fully
// initialized state.
return this;
}
public override void Emit (EmitContext ec)
{
child.Emit (ec);
}
public override SLE.Expression MakeExpression (BuilderContext ctx)
{
#if STATIC
return base.MakeExpression (ctx);
#else
return ctx.HasSet (BuilderContext.Options.CheckedScope) ?
SLE.Expression.ConvertChecked (child.MakeExpression (ctx), type.GetMetaInfo ()) :
SLE.Expression.Convert (child.MakeExpression (ctx), type.GetMetaInfo ());
#endif
}
protected override void CloneTo (CloneContext clonectx, Expression t)
{
// Nothing to clone
}
public override bool IsNull {
get { return child.IsNull; }
}
}
public class EmptyCast : TypeCast {
EmptyCast (Expression child, TypeSpec target_type)
: base (child, target_type)
{
}
public static Expression Create (Expression child, TypeSpec type)
{
Constant c = child as Constant;
if (c != null) {
var enum_constant = c as EnumConstant;
if (enum_constant != null)
c = enum_constant.Child;
if (!(c is ReducedExpression.ReducedConstantExpression)) {
if (c.Type == type)
return c;
var res = c.ConvertImplicitly (type);
if (res != null)
return res;
}
}
EmptyCast e = child as EmptyCast;
if (e != null)
return new EmptyCast (e.child, type);
return new EmptyCast (child, type);
}
public override void EmitBranchable (EmitContext ec, Label label, bool on_true)
{
child.EmitBranchable (ec, label, on_true);
}
public override void EmitSideEffect (EmitContext ec)
{
child.EmitSideEffect (ec);
}
}
//
// Used for predefined type user operator (no obsolete check, etc.)
//
public class OperatorCast : TypeCast
{
readonly MethodSpec conversion_operator;
public OperatorCast (Expression expr, TypeSpec target_type)
: this (expr, target_type, target_type, false)
{
}
public OperatorCast (Expression expr, TypeSpec target_type, bool find_explicit)
: this (expr, target_type, target_type, find_explicit)
{
}
public OperatorCast (Expression expr, TypeSpec declaringType, TypeSpec returnType, bool isExplicit)
: base (expr, returnType)
{
var op = isExplicit ? Operator.OpType.Explicit : Operator.OpType.Implicit;
var mi = MemberCache.GetUserOperator (declaringType, op, true);
if (mi != null) {
foreach (MethodSpec oper in mi) {
if (oper.ReturnType != returnType)
continue;
if (oper.Parameters.Types[0] == expr.Type) {
conversion_operator = oper;
return;
}
}
}
throw new InternalErrorException ("Missing predefined user operator between `{0}' and `{1}'",
returnType.GetSignatureForError (), expr.Type.GetSignatureForError ());
}
public override void Emit (EmitContext ec)
{
child.Emit (ec);
ec.Emit (OpCodes.Call, conversion_operator);
}
}
//
// Constant specialization of EmptyCast.
// We need to special case this since an empty cast of
// a constant is still a constant.
//
public class EmptyConstantCast : Constant
{
public readonly Constant child;
public EmptyConstantCast (Constant child, TypeSpec type)
: base (child.Location)
{
if (child == null)
throw new ArgumentNullException ("child");
this.child = child;
this.eclass = child.eclass;
this.type = type;
}
public override Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type)
{
if (child.Type == target_type)
return child;
// FIXME: check that 'type' can be converted to 'target_type' first
return child.ConvertExplicitly (in_checked_context, target_type);
}
public override Expression CreateExpressionTree (ResolveContext ec)
{
Arguments args = Arguments.CreateForExpressionTree (ec, null,
child.CreateExpressionTree (ec),
new TypeOf (type, loc));
if (type.IsPointer)
Error_PointerInsideExpressionTree (ec);
return CreateExpressionFactoryCall (ec, "Convert", args);
}
public override bool IsDefaultValue {
get { return child.IsDefaultValue; }
}
public override bool IsNegative {
get { return child.IsNegative; }
}
public override bool IsNull {
get { return child.IsNull; }
}
public override bool IsOneInteger {
get { return child.IsOneInteger; }
}
public override bool IsSideEffectFree {
get {
return child.IsSideEffectFree;
}
}
public override bool IsZeroInteger {
get { return child.IsZeroInteger; }
}
public override void Emit (EmitContext ec)
{
child.Emit (ec);
}
public override void EmitBranchable (EmitContext ec, Label label, bool on_true)
{
child.EmitBranchable (ec, label, on_true);
// Only to make verifier happy
if (TypeManager.IsGenericParameter (type) && child.IsNull)
ec.Emit (OpCodes.Unbox_Any, type);
}
public override void EmitSideEffect (EmitContext ec)
{
child.EmitSideEffect (ec);
}
public override object GetValue ()
{
return child.GetValue ();
}
public override string GetValueAsLiteral ()
{
return child.GetValueAsLiteral ();
}
public override long GetValueAsLong ()
{
return child.GetValueAsLong ();
}
public override Constant ConvertImplicitly (TypeSpec target_type)
{
if (type == target_type)
return this;
// FIXME: Do we need to check user conversions?
if (!Convert.ImplicitStandardConversionExists (this, target_type))
return null;
return child.ConvertImplicitly (target_type);
}
}
/// <summary>
/// This class is used to wrap literals which belong inside Enums
/// </summary>
public class EnumConstant : Constant
{
public Constant Child;
public EnumConstant (Constant child, TypeSpec enum_type)
: base (child.Location)
{
this.Child = child;
this.eclass = ExprClass.Value;
this.type = enum_type;
}
protected EnumConstant (Location loc)
: base (loc)
{
}
public override void Emit (EmitContext ec)
{
Child.Emit (ec);
}
public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
{
Child.EncodeAttributeValue (rc, enc, Child.Type);
}
public override void EmitBranchable (EmitContext ec, Label label, bool on_true)
{
Child.EmitBranchable (ec, label, on_true);
}
public override void EmitSideEffect (EmitContext ec)
{
Child.EmitSideEffect (ec);
}
public override string GetSignatureForError()
{
return Type.GetSignatureForError ();
}
public override object GetValue ()
{
return Child.GetValue ();
}
#if !STATIC
public override object GetTypedValue ()
{
//
// The method can be used in dynamic context only (on closed types)
//
// System.Enum.ToObject cannot be called on dynamic types
// EnumBuilder has to be used, but we cannot use EnumBuilder
// because it does not properly support generics
//
return System.Enum.ToObject (type.GetMetaInfo (), Child.GetValue ());
}
#endif
public override string GetValueAsLiteral ()
{
return Child.GetValueAsLiteral ();
}
public override long GetValueAsLong ()
{
return Child.GetValueAsLong ();
}
public EnumConstant Increment()
{
return new EnumConstant (((IntegralConstant) Child).Increment (), type);
}
public override bool IsDefaultValue {
get {
return Child.IsDefaultValue;
}
}
public override bool IsSideEffectFree {
get {
return Child.IsSideEffectFree;
}
}
public override bool IsZeroInteger {
get { return Child.IsZeroInteger; }
}
public override bool IsNegative {
get {
return Child.IsNegative;
}
}
public override Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type)
{
if (Child.Type == target_type)
return Child;
return Child.ConvertExplicitly (in_checked_context, target_type);
}
public override Constant ConvertImplicitly (TypeSpec type)
{
if (this.type == type) {
return this;
}
if (!Convert.ImplicitStandardConversionExists (this, type)){
return null;
}
return Child.ConvertImplicitly (type);
}
}
/// <summary>
/// This kind of cast is used to encapsulate Value Types in objects.
///
/// The effect of it is to box the value type emitted by the previous
/// operation.
/// </summary>
public class BoxedCast : TypeCast {
public BoxedCast (Expression expr, TypeSpec target_type)
: base (expr, target_type)
{
eclass = ExprClass.Value;
}
protected override Expression DoResolve (ResolveContext ec)
{
// This should never be invoked, we are born in fully
// initialized state.
return this;
}
public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
{
// Only boxing to object type is supported
if (targetType.BuiltinType != BuiltinTypeSpec.Type.Object) {
base.EncodeAttributeValue (rc, enc, targetType);
return;
}
enc.Encode (child.Type);
child.EncodeAttributeValue (rc, enc, child.Type);
}
public override void Emit (EmitContext ec)
{
base.Emit (ec);
ec.Emit (OpCodes.Box, child.Type);
}
public override void EmitSideEffect (EmitContext ec)
{
// boxing is side-effectful, since it involves runtime checks, except when boxing to Object or ValueType
// so, we need to emit the box+pop instructions in most cases
if (child.Type.IsStruct &&
(type.BuiltinType == BuiltinTypeSpec.Type.Object || type.BuiltinType == BuiltinTypeSpec.Type.ValueType))
child.EmitSideEffect (ec);
else
base.EmitSideEffect (ec);
}
}
public class UnboxCast : TypeCast {
public UnboxCast (Expression expr, TypeSpec return_type)
: base (expr, return_type)
{
}
protected override Expression DoResolve (ResolveContext ec)
{
// This should never be invoked, we are born in fully
// initialized state.
return this;
}
public override void Emit (EmitContext ec)
{
base.Emit (ec);
ec.Emit (OpCodes.Unbox_Any, type);
}
}
/// <summary>
/// This is used to perform explicit numeric conversions.
///
/// Explicit numeric conversions might trigger exceptions in a checked
/// context, so they should generate the conv.ovf opcodes instead of
/// conv opcodes.
/// </summary>
public class ConvCast : TypeCast {
public enum Mode : byte {
I1_U1, I1_U2, I1_U4, I1_U8, I1_CH,
U1_I1, U1_CH,
I2_I1, I2_U1, I2_U2, I2_U4, I2_U8, I2_CH,
U2_I1, U2_U1, U2_I2, U2_CH,
I4_I1, I4_U1, I4_I2, I4_U2, I4_U4, I4_U8, I4_CH,
U4_I1, U4_U1, U4_I2, U4_U2, U4_I4, U4_CH,
I8_I1, I8_U1, I8_I2, I8_U2, I8_I4, I8_U4, I8_U8, I8_CH, I8_I,
U8_I1, U8_U1, U8_I2, U8_U2, U8_I4, U8_U4, U8_I8, U8_CH, U8_I,
CH_I1, CH_U1, CH_I2,
R4_I1, R4_U1, R4_I2, R4_U2, R4_I4, R4_U4, R4_I8, R4_U8, R4_CH,
R8_I1, R8_U1, R8_I2, R8_U2, R8_I4, R8_U4, R8_I8, R8_U8, R8_CH, R8_R4,
I_I8,
}
Mode mode;
public ConvCast (Expression child, TypeSpec return_type, Mode m)
: base (child, return_type)
{
mode = m;
}
protected override Expression DoResolve (ResolveContext ec)
{
// This should never be invoked, we are born in fully
// initialized state.
return this;
}
public override string ToString ()
{
return String.Format ("ConvCast ({0}, {1})", mode, child);
}
public override void Emit (EmitContext ec)
{
base.Emit (ec);
Emit (ec, mode);
}
public static void Emit (EmitContext ec, Mode mode)
{
if (ec.HasSet (EmitContext.Options.CheckedScope)) {
switch (mode){
case Mode.I1_U1: ec.Emit (OpCodes.Conv_Ovf_U1); break;
case Mode.I1_U2: ec.Emit (OpCodes.Conv_Ovf_U2); break;
case Mode.I1_U4: ec.Emit (OpCodes.Conv_Ovf_U4); break;
case Mode.I1_U8: ec.Emit (OpCodes.Conv_Ovf_U8); break;
case Mode.I1_CH: ec.Emit (OpCodes.Conv_Ovf_U2); break;
case Mode.U1_I1: ec.Emit (OpCodes.Conv_Ovf_I1_Un); break;
case Mode.U1_CH: /* nothing */ break;
case Mode.I2_I1: ec.Emit (OpCodes.Conv_Ovf_I1); break;
case Mode.I2_U1: ec.Emit (OpCodes.Conv_Ovf_U1); break;
case Mode.I2_U2: ec.Emit (OpCodes.Conv_Ovf_U2); break;
case Mode.I2_U4: ec.Emit (OpCodes.Conv_Ovf_U4); break;
case Mode.I2_U8: ec.Emit (OpCodes.Conv_Ovf_U8); break;
case Mode.I2_CH: ec.Emit (OpCodes.Conv_Ovf_U2); break;
case Mode.U2_I1: ec.Emit (OpCodes.Conv_Ovf_I1_Un); break;
case Mode.U2_U1: ec.Emit (OpCodes.Conv_Ovf_U1_Un); break;
case Mode.U2_I2: ec.Emit (OpCodes.Conv_Ovf_I2_Un); break;
case Mode.U2_CH: /* nothing */ break;
case Mode.I4_I1: ec.Emit (OpCodes.Conv_Ovf_I1); break;
case Mode.I4_U1: ec.Emit (OpCodes.Conv_Ovf_U1); break;
case Mode.I4_I2: ec.Emit (OpCodes.Conv_Ovf_I2); break;
case Mode.I4_U4: ec.Emit (OpCodes.Conv_Ovf_U4); break;
case Mode.I4_U2: ec.Emit (OpCodes.Conv_Ovf_U2); break;
case Mode.I4_U8: ec.Emit (OpCodes.Conv_Ovf_U8); break;
case Mode.I4_CH: ec.Emit (OpCodes.Conv_Ovf_U2); break;
case Mode.U4_I1: ec.Emit (OpCodes.Conv_Ovf_I1_Un); break;
case Mode.U4_U1: ec.Emit (OpCodes.Conv_Ovf_U1_Un); break;
case Mode.U4_I2: ec.Emit (OpCodes.Conv_Ovf_I2_Un); break;
case Mode.U4_U2: ec.Emit (OpCodes.Conv_Ovf_U2_Un); break;
case Mode.U4_I4: ec.Emit (OpCodes.Conv_Ovf_I4_Un); break;
case Mode.U4_CH: ec.Emit (OpCodes.Conv_Ovf_U2_Un); break;
case Mode.I8_I1: ec.Emit (OpCodes.Conv_Ovf_I1); break;
case Mode.I8_U1: ec.Emit (OpCodes.Conv_Ovf_U1); break;
case Mode.I8_I2: ec.Emit (OpCodes.Conv_Ovf_I2); break;
case Mode.I8_U2: ec.Emit (OpCodes.Conv_Ovf_U2); break;
case Mode.I8_I4: ec.Emit (OpCodes.Conv_Ovf_I4); break;
case Mode.I8_U4: ec.Emit (OpCodes.Conv_Ovf_U4); break;
case Mode.I8_U8: ec.Emit (OpCodes.Conv_Ovf_U8); break;
case Mode.I8_CH: ec.Emit (OpCodes.Conv_Ovf_U2); break;
case Mode.I8_I: ec.Emit (OpCodes.Conv_Ovf_U); break;
case Mode.U8_I1: ec.Emit (OpCodes.Conv_Ovf_I1_Un); break;
case Mode.U8_U1: ec.Emit (OpCodes.Conv_Ovf_U1_Un); break;
case Mode.U8_I2: ec.Emit (OpCodes.Conv_Ovf_I2_Un); break;
case Mode.U8_U2: ec.Emit (OpCodes.Conv_Ovf_U2_Un); break;
case Mode.U8_I4: ec.Emit (OpCodes.Conv_Ovf_I4_Un); break;
case Mode.U8_U4: ec.Emit (OpCodes.Conv_Ovf_U4_Un); break;
case Mode.U8_I8: ec.Emit (OpCodes.Conv_Ovf_I8_Un); break;
case Mode.U8_CH: ec.Emit (OpCodes.Conv_Ovf_U2_Un); break;
case Mode.U8_I: ec.Emit (OpCodes.Conv_Ovf_U_Un); break;
case Mode.CH_I1: ec.Emit (OpCodes.Conv_Ovf_I1_Un); break;
case Mode.CH_U1: ec.Emit (OpCodes.Conv_Ovf_U1_Un); break;
case Mode.CH_I2: ec.Emit (OpCodes.Conv_Ovf_I2_Un); break;
case Mode.R4_I1: ec.Emit (OpCodes.Conv_Ovf_I1); break;
case Mode.R4_U1: ec.Emit (OpCodes.Conv_Ovf_U1); break;
case Mode.R4_I2: ec.Emit (OpCodes.Conv_Ovf_I2); break;
case Mode.R4_U2: ec.Emit (OpCodes.Conv_Ovf_U2); break;
case Mode.R4_I4: ec.Emit (OpCodes.Conv_Ovf_I4); break;
case Mode.R4_U4: ec.Emit (OpCodes.Conv_Ovf_U4); break;
case Mode.R4_I8: ec.Emit (OpCodes.Conv_Ovf_I8); break;
case Mode.R4_U8: ec.Emit (OpCodes.Conv_Ovf_U8); break;
case Mode.R4_CH: ec.Emit (OpCodes.Conv_Ovf_U2); break;
case Mode.R8_I1: ec.Emit (OpCodes.Conv_Ovf_I1); break;
case Mode.R8_U1: ec.Emit (OpCodes.Conv_Ovf_U1); break;
case Mode.R8_I2: ec.Emit (OpCodes.Conv_Ovf_I2); break;
case Mode.R8_U2: ec.Emit (OpCodes.Conv_Ovf_U2); break;
case Mode.R8_I4: ec.Emit (OpCodes.Conv_Ovf_I4); break;
case Mode.R8_U4: ec.Emit (OpCodes.Conv_Ovf_U4); break;
case Mode.R8_I8: ec.Emit (OpCodes.Conv_Ovf_I8); break;
case Mode.R8_U8: ec.Emit (OpCodes.Conv_Ovf_U8); break;
case Mode.R8_CH: ec.Emit (OpCodes.Conv_Ovf_U2); break;
case Mode.R8_R4: ec.Emit (OpCodes.Conv_R4); break;
case Mode.I_I8: ec.Emit (OpCodes.Conv_Ovf_I8_Un); break;
}
} else {
switch (mode){
case Mode.I1_U1: ec.Emit (OpCodes.Conv_U1); break;
case Mode.I1_U2: ec.Emit (OpCodes.Conv_U2); break;
case Mode.I1_U4: ec.Emit (OpCodes.Conv_U4); break;
case Mode.I1_U8: ec.Emit (OpCodes.Conv_I8); break;
case Mode.I1_CH: ec.Emit (OpCodes.Conv_U2); break;
case Mode.U1_I1: ec.Emit (OpCodes.Conv_I1); break;
case Mode.U1_CH: ec.Emit (OpCodes.Conv_U2); break;
case Mode.I2_I1: ec.Emit (OpCodes.Conv_I1); break;
case Mode.I2_U1: ec.Emit (OpCodes.Conv_U1); break;
case Mode.I2_U2: ec.Emit (OpCodes.Conv_U2); break;
case Mode.I2_U4: ec.Emit (OpCodes.Conv_U4); break;
case Mode.I2_U8: ec.Emit (OpCodes.Conv_I8); break;
case Mode.I2_CH: ec.Emit (OpCodes.Conv_U2); break;
case Mode.U2_I1: ec.Emit (OpCodes.Conv_I1); break;
case Mode.U2_U1: ec.Emit (OpCodes.Conv_U1); break;
case Mode.U2_I2: ec.Emit (OpCodes.Conv_I2); break;
case Mode.U2_CH: /* nothing */ break;
case Mode.I4_I1: ec.Emit (OpCodes.Conv_I1); break;
case Mode.I4_U1: ec.Emit (OpCodes.Conv_U1); break;
case Mode.I4_I2: ec.Emit (OpCodes.Conv_I2); break;
case Mode.I4_U4: /* nothing */ break;
case Mode.I4_U2: ec.Emit (OpCodes.Conv_U2); break;
case Mode.I4_U8: ec.Emit (OpCodes.Conv_I8); break;
case Mode.I4_CH: ec.Emit (OpCodes.Conv_U2); break;
case Mode.U4_I1: ec.Emit (OpCodes.Conv_I1); break;
case Mode.U4_U1: ec.Emit (OpCodes.Conv_U1); break;
case Mode.U4_I2: ec.Emit (OpCodes.Conv_I2); break;
case Mode.U4_U2: ec.Emit (OpCodes.Conv_U2); break;
case Mode.U4_I4: /* nothing */ break;
case Mode.U4_CH: ec.Emit (OpCodes.Conv_U2); break;
case Mode.I8_I1: ec.Emit (OpCodes.Conv_I1); break;
case Mode.I8_U1: ec.Emit (OpCodes.Conv_U1); break;
case Mode.I8_I2: ec.Emit (OpCodes.Conv_I2); break;
case Mode.I8_U2: ec.Emit (OpCodes.Conv_U2); break;
case Mode.I8_I4: ec.Emit (OpCodes.Conv_I4); break;
case Mode.I8_U4: ec.Emit (OpCodes.Conv_U4); break;
case Mode.I8_U8: /* nothing */ break;
case Mode.I8_CH: ec.Emit (OpCodes.Conv_U2); break;
case Mode.I8_I: ec.Emit (OpCodes.Conv_U); break;
case Mode.U8_I1: ec.Emit (OpCodes.Conv_I1); break;
case Mode.U8_U1: ec.Emit (OpCodes.Conv_U1); break;
case Mode.U8_I2: ec.Emit (OpCodes.Conv_I2); break;
case Mode.U8_U2: ec.Emit (OpCodes.Conv_U2); break;
case Mode.U8_I4: ec.Emit (OpCodes.Conv_I4); break;
case Mode.U8_U4: ec.Emit (OpCodes.Conv_U4); break;
case Mode.U8_I8: /* nothing */ break;
case Mode.U8_CH: ec.Emit (OpCodes.Conv_U2); break;
case Mode.U8_I: ec.Emit (OpCodes.Conv_U); break;
case Mode.CH_I1: ec.Emit (OpCodes.Conv_I1); break;
case Mode.CH_U1: ec.Emit (OpCodes.Conv_U1); break;
case Mode.CH_I2: ec.Emit (OpCodes.Conv_I2); break;
case Mode.R4_I1: ec.Emit (OpCodes.Conv_I1); break;
case Mode.R4_U1: ec.Emit (OpCodes.Conv_U1); break;
case Mode.R4_I2: ec.Emit (OpCodes.Conv_I2); break;
case Mode.R4_U2: ec.Emit (OpCodes.Conv_U2); break;
case Mode.R4_I4: ec.Emit (OpCodes.Conv_I4); break;
case Mode.R4_U4: ec.Emit (OpCodes.Conv_U4); break;
case Mode.R4_I8: ec.Emit (OpCodes.Conv_I8); break;
case Mode.R4_U8: ec.Emit (OpCodes.Conv_U8); break;
case Mode.R4_CH: ec.Emit (OpCodes.Conv_U2); break;
case Mode.R8_I1: ec.Emit (OpCodes.Conv_I1); break;
case Mode.R8_U1: ec.Emit (OpCodes.Conv_U1); break;
case Mode.R8_I2: ec.Emit (OpCodes.Conv_I2); break;
case Mode.R8_U2: ec.Emit (OpCodes.Conv_U2); break;
case Mode.R8_I4: ec.Emit (OpCodes.Conv_I4); break;
case Mode.R8_U4: ec.Emit (OpCodes.Conv_U4); break;
case Mode.R8_I8: ec.Emit (OpCodes.Conv_I8); break;
case Mode.R8_U8: ec.Emit (OpCodes.Conv_U8); break;
case Mode.R8_CH: ec.Emit (OpCodes.Conv_U2); break;
case Mode.R8_R4: ec.Emit (OpCodes.Conv_R4); break;
case Mode.I_I8: ec.Emit (OpCodes.Conv_U8); break;
}
}
}
}
class OpcodeCast : TypeCast
{
readonly OpCode op;
public OpcodeCast (Expression child, TypeSpec return_type, OpCode op)
: base (child, return_type)
{
this.op = op;
}
protected override Expression DoResolve (ResolveContext ec)
{
// This should never be invoked, we are born in fully
// initialized state.
return this;
}
public override void Emit (EmitContext ec)
{
base.Emit (ec);
ec.Emit (op);
}
public TypeSpec UnderlyingType {
get { return child.Type; }
}
}
//
// Opcode casts expression with 2 opcodes but only
// single expression tree node
//
class OpcodeCastDuplex : OpcodeCast
{
readonly OpCode second;
public OpcodeCastDuplex (Expression child, TypeSpec returnType, OpCode first, OpCode second)
: base (child, returnType, first)
{
this.second = second;
}
public override void Emit (EmitContext ec)
{
base.Emit (ec);
ec.Emit (second);
}
}
/// <summary>
/// This kind of cast is used to encapsulate a child and cast it
/// to the class requested
/// </summary>
public sealed class ClassCast : TypeCast {
readonly bool forced;
public ClassCast (Expression child, TypeSpec return_type)
: base (child, return_type)
{
}
public ClassCast (Expression child, TypeSpec return_type, bool forced)
: base (child, return_type)
{
this.forced = forced;
}
public override void Emit (EmitContext ec)
{
base.Emit (ec);
bool gen = TypeManager.IsGenericParameter (child.Type);
if (gen)
ec.Emit (OpCodes.Box, child.Type);
if (type.IsGenericParameter) {
ec.Emit (OpCodes.Unbox_Any, type);
return;
}
if (gen && !forced)
return;
ec.Emit (OpCodes.Castclass, type);
}
}
//
// Created during resolving pahse when an expression is wrapped or constantified
// and original expression can be used later (e.g. for expression trees)
//
public class ReducedExpression : Expression
{
public sealed class ReducedConstantExpression : EmptyConstantCast
{
readonly Expression orig_expr;
public ReducedConstantExpression (Constant expr, Expression orig_expr)
: base (expr, expr.Type)
{
this.orig_expr = orig_expr;
}
public override Constant ConvertImplicitly (TypeSpec target_type)
{
Constant c = base.ConvertImplicitly (target_type);
if (c != null)
c = new ReducedConstantExpression (c, orig_expr);
return c;
}
public override Expression CreateExpressionTree (ResolveContext ec)
{
return orig_expr.CreateExpressionTree (ec);
}
public override Constant ConvertExplicitly (bool in_checked_context, TypeSpec target_type)
{
Constant c = base.ConvertExplicitly (in_checked_context, target_type);
if (c != null)
c = new ReducedConstantExpression (c, orig_expr);
return c;
}
public override void EncodeAttributeValue (IMemberContext rc, AttributeEncoder enc, TypeSpec targetType)
{
//
// LAMESPEC: Reduced conditional expression is allowed as an attribute argument
//
if (orig_expr is Conditional)
child.EncodeAttributeValue (rc, enc, targetType);
else
base.EncodeAttributeValue (rc, enc, targetType);
}
}
sealed class ReducedExpressionStatement : ExpressionStatement
{
readonly Expression orig_expr;
readonly ExpressionStatement stm;
public ReducedExpressionStatement (ExpressionStatement stm, Expression orig)
{
this.orig_expr = orig;
this.stm = stm;
this.eclass = stm.eclass;
this.type = stm.Type;
this.loc = orig.Location;
}
public override bool ContainsEmitWithAwait ()
{
return stm.ContainsEmitWithAwait ();
}
public override Expression CreateExpressionTree (ResolveContext ec)
{
return orig_expr.CreateExpressionTree (ec);
}
protected override Expression DoResolve (ResolveContext ec)
{
return this;
}
public override void Emit (EmitContext ec)
{
stm.Emit (ec);
}
public override void EmitStatement (EmitContext ec)
{
stm.EmitStatement (ec);
}
}
readonly Expression expr, orig_expr;
private ReducedExpression (Expression expr, Expression orig_expr)
{
this.expr = expr;
this.eclass = expr.eclass;
this.type = expr.Type;
this.orig_expr = orig_expr;
this.loc = orig_expr.Location;
}
#region Properties
public override bool IsSideEffectFree {
get {
return expr.IsSideEffectFree;
}
}
public Expression OriginalExpression {
get {
return orig_expr;
}
}
#endregion
public override bool ContainsEmitWithAwait ()
{
return expr.ContainsEmitWithAwait ();
}
//
// Creates fully resolved expression switcher
//
public static Constant Create (Constant expr, Expression original_expr)
{
if (expr.eclass == ExprClass.Unresolved)
throw new ArgumentException ("Unresolved expression");
return new ReducedConstantExpression (expr, original_expr);
}
public static ExpressionStatement Create (ExpressionStatement s, Expression orig)
{
return new ReducedExpressionStatement (s, orig);
}
public static Expression Create (Expression expr, Expression original_expr)
{
return Create (expr, original_expr, true);
}
//
// Creates unresolved reduce expression. The original expression has to be
// already resolved. Created expression is constant based based on `expr'
// value unless canBeConstant is used
//
public static Expression Create (Expression expr, Expression original_expr, bool canBeConstant)
{
if (canBeConstant) {
Constant c = expr as Constant;
if (c != null)
return Create (c, original_expr);
}
ExpressionStatement s = expr as ExpressionStatement;
if (s != null)
return Create (s, original_expr);
if (expr.eclass == ExprClass.Unresolved)
throw new ArgumentException ("Unresolved expression");
return new ReducedExpression (expr, original_expr);
}
public override Expression CreateExpressionTree (ResolveContext ec)
{
return orig_expr.CreateExpressionTree (ec);
}
protected override Expression DoResolve (ResolveContext ec)
{
return this;
}
public override void Emit (EmitContext ec)
{
expr.Emit (ec);
}
public override Expression EmitToField (EmitContext ec)
{
return expr.EmitToField(ec);
}
public override void EmitBranchable (EmitContext ec, Label target, bool on_true)
{
expr.EmitBranchable (ec, target, on_true);
}
public override SLE.Expression MakeExpression (BuilderContext ctx)
{
return orig_expr.MakeExpression (ctx);
}
}
//
// Standard composite pattern
//
public abstract class CompositeExpression : Expression
{
protected Expression expr;
protected CompositeExpression (Expression expr)
{
this.expr = expr;
this.loc = expr.Location;
}
public override bool ContainsEmitWithAwait ()
{
return expr.ContainsEmitWithAwait ();
}
public override Expression CreateExpressionTree (ResolveContext rc)
{
return expr.CreateExpressionTree (rc);
}
public Expression Child {
get { return expr; }
}
protected override Expression DoResolve (ResolveContext rc)
{
expr = expr.Resolve (rc);
if (expr != null) {
type = expr.Type;
eclass = expr.eclass;
}
return this;
}
public override void Emit (EmitContext ec)
{
expr.Emit (ec);
}
public override bool IsNull {
get { return expr.IsNull; }
}
}
//
// Base of expressions used only to narrow resolve flow
//
public abstract class ShimExpression : Expression
{
protected Expression expr;
protected ShimExpression (Expression expr)
{
this.expr = expr;
}
public Expression Expr {
get {
return expr;
}
}
protected override void CloneTo (CloneContext clonectx, Expression t)
{
if (expr == null)
return;
ShimExpression target = (ShimExpression) t;
target.expr = expr.Clone (clonectx);
}
public override bool ContainsEmitWithAwait ()
{
return expr.ContainsEmitWithAwait ();
}
public override Expression CreateExpressionTree (ResolveContext ec)
{
throw new NotSupportedException ("ET");
}
public override void Emit (EmitContext ec)
{
throw new InternalErrorException ("Missing Resolve call");
}
}
//
// Unresolved type name expressions
//
public abstract class ATypeNameExpression : FullNamedExpression
{
string name;
protected TypeArguments targs;
protected ATypeNameExpression (string name, Location l)
{
this.name = name;
loc = l;
}
protected ATypeNameExpression (string name, TypeArguments targs, Location l)
{
this.name = name;
this.targs = targs;
loc = l;
}
protected ATypeNameExpression (string name, int arity, Location l)
: this (name, new UnboundTypeArguments (arity), l)
{
}
#region Properties
protected int Arity {
get {
return targs == null ? 0 : targs.Count;
}
}
public bool HasTypeArguments {
get {
return targs != null && !targs.IsEmpty;
}
}
public string Name {
get {
return name;
}
set {
name = value;
}
}
public TypeArguments TypeArguments {
get {
return targs;
}
}
#endregion
public override bool Equals (object obj)
{
ATypeNameExpression atne = obj as ATypeNameExpression;
return atne != null && atne.Name == Name &&
(targs == null || targs.Equals (atne.targs));
}
public override int GetHashCode ()
{
return Name.GetHashCode ();
}
// TODO: Move it to MemberCore
public static string GetMemberType (MemberCore mc)
{
if (mc is Property)
return "property";
if (mc is Indexer)
return "indexer";
if (mc is FieldBase)
return "field";
if (mc is MethodCore)
return "method";
if (mc is EnumMember)
return "enum";
if (mc is Event)
return "event";
return "type";
}
public override string GetSignatureForError ()
{
if (targs != null) {
return Name + "<" + targs.GetSignatureForError () + ">";
}
return Name;
}
public abstract Expression LookupNameExpression (ResolveContext rc, MemberLookupRestrictions restriction);
}
/// <summary>
/// SimpleName expressions are formed of a single word and only happen at the beginning
/// of a dotted-name.
/// </summary>
public class SimpleName : ATypeNameExpression
{
public SimpleName (string name, Location l)
: base (name, l)
{
}
public SimpleName (string name, TypeArguments args, Location l)
: base (name, args, l)
{
}
public SimpleName (string name, int arity, Location l)
: base (name, arity, l)
{
}
public SimpleName GetMethodGroup ()
{
return new SimpleName (Name, targs, loc);
}
protected override Expression DoResolve (ResolveContext rc)
{
var e = SimpleNameResolve (rc, null);
var fe = e as FieldExpr;
if (fe != null) {
fe.VerifyAssignedStructField (rc, null);
}
return e;
}
public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
{
return SimpleNameResolve (ec, right_side);
}
protected virtual void Error_TypeOrNamespaceNotFound (IMemberContext ctx)
{
if (ctx.CurrentType != null) {
var member = MemberLookup (ctx, false, ctx.CurrentType, Name, 0, MemberLookupRestrictions.ExactArity, loc) as MemberExpr;
if (member != null) {
member.Error_UnexpectedKind (ctx, member, "type", member.KindName, loc);
return;
}
}
var report = ctx.Module.Compiler.Report;
var retval = ctx.LookupNamespaceOrType (Name, Arity, LookupMode.IgnoreAccessibility, loc);
if (retval != null) {
report.SymbolRelatedToPreviousError (retval.Type);
ErrorIsInaccesible (ctx, retval.GetSignatureForError (), loc);
return;
}
retval = ctx.LookupNamespaceOrType (Name, -System.Math.Max (1, Arity), LookupMode.Probing, loc);
if (retval != null) {
Error_TypeArgumentsCannotBeUsed (ctx, retval.Type, Arity, loc);
return;
}
var ns_candidates = ctx.Module.GlobalRootNamespace.FindTypeNamespaces (ctx, Name, Arity);
if (ns_candidates != null) {
if (ctx is UsingAliasNamespace.AliasContext) {
report.Error (246, loc,
"The type or namespace name `{1}' could not be found. Consider using fully qualified name `{0}.{1}'",
ns_candidates[0], Name);
} else {
string usings = string.Join ("' or `", ns_candidates.ToArray ());
report.Error (246, loc,
"The type or namespace name `{0}' could not be found. Are you missing `{1}' using directive?",
Name, usings);
}
} else {
report.Error (246, loc,
"The type or namespace name `{0}' could not be found. Are you missing an assembly reference?",
Name);
}
}
public override FullNamedExpression ResolveAsTypeOrNamespace (IMemberContext mc)
{
FullNamedExpression fne = mc.LookupNamespaceOrType (Name, Arity, LookupMode.Normal, loc);
if (fne != null) {
if (fne.Type != null && Arity > 0) {
if (HasTypeArguments) {
GenericTypeExpr ct = new GenericTypeExpr (fne.Type, targs, loc);
if (ct.ResolveAsType (mc) == null)
return null;
return ct;
}
return new GenericOpenTypeExpr (fne.Type, loc);
}
//
// dynamic namespace is ignored when dynamic is allowed (does not apply to types)
//
if (!(fne is Namespace))
return fne;
}
if (Arity == 0 && Name == "dynamic" && mc.Module.Compiler.Settings.Version > LanguageVersion.V_3) {
if (!mc.Module.PredefinedAttributes.Dynamic.IsDefined) {
mc.Module.Compiler.Report.Error (1980, Location,
"Dynamic keyword requires `{0}' to be defined. Are you missing System.Core.dll assembly reference?",
mc.Module.PredefinedAttributes.Dynamic.GetSignatureForError ());
}
fne = new DynamicTypeExpr (loc);
fne.ResolveAsType (mc);
}
if (fne != null)
return fne;
Error_TypeOrNamespaceNotFound (mc);
return null;
}
public bool IsPossibleTypeOrNamespace (IMemberContext mc)
{
return mc.LookupNamespaceOrType (Name, Arity, LookupMode.Probing, loc) != null;
}
public override Expression LookupNameExpression (ResolveContext rc, MemberLookupRestrictions restrictions)
{
int lookup_arity = Arity;
bool errorMode = false;
Expression e;
Block current_block = rc.CurrentBlock;
INamedBlockVariable variable = null;
bool variable_found = false;
while (true) {
//
// Stage 1: binding to local variables or parameters
//
// LAMESPEC: It should take invocableOnly into account but that would break csc compatibility
//
if (current_block != null && lookup_arity == 0) {
if (current_block.ParametersBlock.TopBlock.GetLocalName (Name, current_block.Original, ref variable)) {
if (!variable.IsDeclared) {
// We found local name in accessible block but it's not
// initialized yet, maybe the user wanted to bind to something else
errorMode = true;
variable_found = true;
} else {
e = variable.CreateReferenceExpression (rc, loc);
if (e != null) {
if (Arity > 0)
Error_TypeArgumentsCannotBeUsed (rc, "variable", Name, loc);
return e;
}
}
}
}
//
// Stage 2: Lookup members if we are inside a type up to top level type for nested types
//
TypeSpec member_type = rc.CurrentType;
for (; member_type != null; member_type = member_type.DeclaringType) {
e = MemberLookup (rc, errorMode, member_type, Name, lookup_arity, restrictions, loc);
if (e == null)
continue;
var me = e as MemberExpr;
if (me == null) {
// The name matches a type, defer to ResolveAsTypeStep
if (e is TypeExpr)
break;
continue;
}
if (errorMode) {
if (variable != null) {
if (me is FieldExpr || me is ConstantExpr || me is EventExpr || me is PropertyExpr) {
rc.Report.Error (844, loc,
"A local variable `{0}' cannot be used before it is declared. Consider renaming the local variable when it hides the member `{1}'",
Name, me.GetSignatureForError ());
} else {
break;
}
} else if (me is MethodGroupExpr || me is PropertyExpr || me is IndexerExpr) {
// Leave it to overload resolution to report correct error
} else {
// TODO: rc.Report.SymbolRelatedToPreviousError ()
ErrorIsInaccesible (rc, me.GetSignatureForError (), loc);
}
} else {
// LAMESPEC: again, ignores InvocableOnly
if (variable != null) {
rc.Report.SymbolRelatedToPreviousError (variable.Location, Name);
rc.Report.Error (135, loc, "`{0}' conflicts with a declaration in a child block", Name);
}
//
// MemberLookup does not check accessors availability, this is actually needed for properties only
//
var pe = me as PropertyExpr;
if (pe != null) {
// Break as there is no other overload available anyway
if ((restrictions & MemberLookupRestrictions.ReadAccess) != 0) {
if (!pe.PropertyInfo.HasGet || !pe.PropertyInfo.Get.IsAccessible (rc))
break;
pe.Getter = pe.PropertyInfo.Get;
} else {
if (!pe.PropertyInfo.HasSet || !pe.PropertyInfo.Set.IsAccessible (rc))
break;
pe.Setter = pe.PropertyInfo.Set;
}
}
}
// TODO: It's used by EventExpr -> FieldExpr transformation only
// TODO: Should go to MemberAccess
me = me.ResolveMemberAccess (rc, null, null);
if (Arity > 0) {
targs.Resolve (rc);
me.SetTypeArguments (rc, targs);
}
return me;
}
//
// Stage 3: Lookup nested types, namespaces and type parameters in the context
//
if ((restrictions & MemberLookupRestrictions.InvocableOnly) == 0 && !variable_found) {
if (IsPossibleTypeOrNamespace (rc)) {
if (variable != null) {
rc.Report.SymbolRelatedToPreviousError (variable.Location, Name);
rc.Report.Error (135, loc, "`{0}' conflicts with a declaration in a child block", Name);
}
return ResolveAsTypeOrNamespace (rc);
}
}
if (errorMode) {
if (variable_found) {
rc.Report.Error (841, loc, "A local variable `{0}' cannot be used before it is declared", Name);
} else {
if (Arity > 0) {
var tparams = rc.CurrentTypeParameters;
if (tparams != null) {
if (tparams.Find (Name) != null) {
Error_TypeArgumentsCannotBeUsed (rc, "type parameter", Name, loc);
return null;
}
}
var ct = rc.CurrentType;
do {
if (ct.MemberDefinition.TypeParametersCount > 0) {
foreach (var ctp in ct.MemberDefinition.TypeParameters) {
if (ctp.Name == Name) {
Error_TypeArgumentsCannotBeUsed (rc, "type parameter", Name, loc);
return null;
}
}
}
ct = ct.DeclaringType;
} while (ct != null);
}
if ((restrictions & MemberLookupRestrictions.InvocableOnly) == 0) {
e = rc.LookupNamespaceOrType (Name, Arity, LookupMode.IgnoreAccessibility, loc);
if (e != null) {
rc.Report.SymbolRelatedToPreviousError (e.Type);
ErrorIsInaccesible (rc, e.GetSignatureForError (), loc);
return e;
}
} else {
var me = MemberLookup (rc, false, rc.CurrentType, Name, Arity, restrictions & ~MemberLookupRestrictions.InvocableOnly, loc) as MemberExpr;
if (me != null) {
me.Error_UnexpectedKind (rc, me, "method group", me.KindName, loc);
return ErrorExpression.Instance;
}
}
e = rc.LookupNamespaceOrType (Name, -System.Math.Max (1, Arity), LookupMode.Probing, loc);
if (e != null) {
if (e.Type.Arity != Arity) {
Error_TypeArgumentsCannotBeUsed (rc, e.Type, Arity, loc);
return e;
}
if (e is TypeExpr) {
// TypeExpression does not have correct location
if (e is TypeExpression)
e = new TypeExpression (e.Type, loc);
return e;
}
}
rc.Report.Error (103, loc, "The name `{0}' does not exist in the current context", Name);
}
return ErrorExpression.Instance;
}
if (rc.Module.Evaluator != null) {
var fi = rc.Module.Evaluator.LookupField (Name);
if (fi != null)
return new FieldExpr (fi.Item1, loc);
}
lookup_arity = 0;
errorMode = true;
}
}
Expression SimpleNameResolve (ResolveContext ec, Expression right_side)
{
Expression e = LookupNameExpression (ec, right_side == null ? MemberLookupRestrictions.ReadAccess : MemberLookupRestrictions.None);
if (e == null)
return null;
if (e is FullNamedExpression && e.eclass != ExprClass.Unresolved) {
e.Error_UnexpectedKind (ec, e, "variable", e.ExprClassName, loc);
return e;
}
if (right_side != null) {
e = e.ResolveLValue (ec, right_side);
} else {
e = e.Resolve (ec);
}
return e;
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
/// <summary>
/// Represents a namespace or a type. The name of the class was inspired by
/// section 10.8.1 (Fully Qualified Names).
/// </summary>
public abstract class FullNamedExpression : Expression
{
protected override void CloneTo (CloneContext clonectx, Expression target)
{
// Do nothing, most unresolved type expressions cannot be
// resolved to different type
}
public override bool ContainsEmitWithAwait ()
{
return false;
}
public override Expression CreateExpressionTree (ResolveContext ec)
{
throw new NotSupportedException ("ET");
}
public abstract FullNamedExpression ResolveAsTypeOrNamespace (IMemberContext mc);
//
// This is used to resolve the expression as a type, a null
// value will be returned if the expression is not a type
// reference
//
public override TypeSpec ResolveAsType (IMemberContext mc)
{
FullNamedExpression fne = ResolveAsTypeOrNamespace (mc);
if (fne == null)
return null;
TypeExpr te = fne as TypeExpr;
if (te == null) {
fne.Error_UnexpectedKind (mc, fne, "type", fne.ExprClassName, loc);
return null;
}
te.loc = loc;
type = te.Type;
var dep = type.GetMissingDependencies ();
if (dep != null) {
ImportedTypeDefinition.Error_MissingDependency (mc, dep, loc);
}
if (type.Kind == MemberKind.Void) {
mc.Module.Compiler.Report.Error (673, loc, "System.Void cannot be used from C#. Consider using `void'");
}
//
// Obsolete checks cannot be done when resolving base context as they
// require type dependencies to be set but we are in process of resolving them
//
if (!(mc is TypeDefinition.BaseContext) && !(mc is UsingAliasNamespace.AliasContext)) {
ObsoleteAttribute obsolete_attr = type.GetAttributeObsolete ();
if (obsolete_attr != null && !mc.IsObsolete) {
AttributeTester.Report_ObsoleteMessage (obsolete_attr, te.GetSignatureForError (), Location, mc.Module.Compiler.Report);
}
}
return type;
}
public override void Emit (EmitContext ec)
{
throw new InternalErrorException ("FullNamedExpression `{0}' found in resolved tree",
GetSignatureForError ());
}
}
/// <summary>
/// Expression that evaluates to a type
/// </summary>
public abstract class TypeExpr : FullNamedExpression
{
public sealed override FullNamedExpression ResolveAsTypeOrNamespace (IMemberContext mc)
{
ResolveAsType (mc);
return this;
}
protected sealed override Expression DoResolve (ResolveContext ec)
{
ResolveAsType (ec);
return this;
}
public override bool Equals (object obj)
{
TypeExpr tobj = obj as TypeExpr;
if (tobj == null)
return false;
return Type == tobj.Type;
}
public override int GetHashCode ()
{
return Type.GetHashCode ();
}
}
/// <summary>
/// Fully resolved Expression that already evaluated to a type
/// </summary>
public class TypeExpression : TypeExpr
{
public TypeExpression (TypeSpec t, Location l)
{
Type = t;
eclass = ExprClass.Type;
loc = l;
}
public sealed override TypeSpec ResolveAsType (IMemberContext ec)
{
return type;
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
/// <summary>
/// This class denotes an expression which evaluates to a member
/// of a struct or a class.
/// </summary>
public abstract class MemberExpr : Expression, OverloadResolver.IInstanceQualifier
{
//
// An instance expression associated with this member, if it's a
// non-static member
//
public Expression InstanceExpression;
/// <summary>
/// The name of this member.
/// </summary>
public abstract string Name {
get;
}
//
// When base.member is used
//
public bool IsBase {
get { return InstanceExpression is BaseThis; }
}
/// <summary>
/// Whether this is an instance member.
/// </summary>
public abstract bool IsInstance {
get;
}
/// <summary>
/// Whether this is a static member.
/// </summary>
public abstract bool IsStatic {
get;
}
public abstract string KindName {
get;
}
protected abstract TypeSpec DeclaringType {
get;
}
TypeSpec OverloadResolver.IInstanceQualifier.InstanceType {
get {
return InstanceExpression.Type;
}
}
//
// Converts best base candidate for virtual method starting from QueriedBaseType
//
protected MethodSpec CandidateToBaseOverride (ResolveContext rc, MethodSpec method)
{
//
// Only when base.member is used and method is virtual
//
if (!IsBase)
return method;
//
// Overload resulution works on virtual or non-virtual members only (no overrides). That
// means for base.member access we have to find the closest match after we found best candidate
//
if ((method.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL | Modifiers.OVERRIDE)) != 0) {
//
// The method could already be what we are looking for
//
TypeSpec[] targs = null;
if (method.DeclaringType != InstanceExpression.Type) {
var base_override = MemberCache.FindMember (InstanceExpression.Type, new MemberFilter (method), BindingRestriction.InstanceOnly | BindingRestriction.OverrideOnly) as MethodSpec;
if (base_override != null && base_override.DeclaringType != method.DeclaringType) {
if (base_override.IsGeneric)
targs = method.TypeArguments;
method = base_override;
}
}
//
// When base access is used inside anonymous method/iterator/etc we need to
// get back to the context of original type. We do it by emiting proxy
// method in original class and rewriting base call to this compiler
// generated method call which does the actual base invocation. This may
// introduce redundant storey but with `this' only but it's tricky to avoid
// at this stage as we don't know what expressions follow base
//
if (rc.CurrentAnonymousMethod != null) {
if (targs == null && method.IsGeneric) {
targs = method.TypeArguments;
method = method.GetGenericMethodDefinition ();
}
if (method.Parameters.HasArglist)
throw new NotImplementedException ("__arglist base call proxy");
method = rc.CurrentMemberDefinition.Parent.PartialContainer.CreateHoistedBaseCallProxy (rc, method);
// Ideally this should apply to any proxy rewrite but in the case of unary mutators on
// get/set member expressions second call would fail to proxy because left expression
// would be of 'this' and not 'base' because we share InstanceExpression for get/set
// FIXME: The async check is another hack but will probably fail with mutators
if (rc.CurrentType.IsStruct || rc.CurrentAnonymousMethod.Storey is AsyncTaskStorey)
InstanceExpression = new This (loc).Resolve (rc);
}
if (targs != null)
method = method.MakeGenericMethod (rc, targs);
}
//
// Only base will allow this invocation to happen.
//
if (method.IsAbstract) {
Error_CannotCallAbstractBase (rc, method.GetSignatureForError ());
}
return method;
}
protected void CheckProtectedMemberAccess (ResolveContext rc, MemberSpec member)
{
if (InstanceExpression == null)
return;
if ((member.Modifiers & Modifiers.PROTECTED) != 0 && !(InstanceExpression is This)) {
if (!CheckProtectedMemberAccess (rc, member, InstanceExpression.Type)) {
Error_ProtectedMemberAccess (rc, member, InstanceExpression.Type, loc);
}
}
}
bool OverloadResolver.IInstanceQualifier.CheckProtectedMemberAccess (ResolveContext rc, MemberSpec member)
{
if (InstanceExpression == null)
return true;
return InstanceExpression is This || CheckProtectedMemberAccess (rc, member, InstanceExpression.Type);
}
public static bool CheckProtectedMemberAccess<T> (ResolveContext rc, T member, TypeSpec qualifier) where T : MemberSpec
{
var ct = rc.CurrentType;
if (ct == qualifier)
return true;
if ((member.Modifiers & Modifiers.INTERNAL) != 0 && member.DeclaringType.MemberDefinition.IsInternalAsPublic (ct.MemberDefinition.DeclaringAssembly))
return true;
qualifier = qualifier.GetDefinition ();
if (ct != qualifier && !IsSameOrBaseQualifier (ct, qualifier)) {
return false;
}
return true;
}
public override bool ContainsEmitWithAwait ()
{
return InstanceExpression != null && InstanceExpression.ContainsEmitWithAwait ();
}
static bool IsSameOrBaseQualifier (TypeSpec type, TypeSpec qtype)
{
do {
type = type.GetDefinition ();
if (type == qtype || TypeManager.IsFamilyAccessible (qtype, type))
return true;
type = type.DeclaringType;
} while (type != null);
return false;
}
protected void DoBestMemberChecks<T> (ResolveContext rc, T member) where T : MemberSpec, IInterfaceMemberSpec
{
if (InstanceExpression != null) {
InstanceExpression = InstanceExpression.Resolve (rc);
CheckProtectedMemberAccess (rc, member);
}
if (member.MemberType.IsPointer && !rc.IsUnsafe) {
UnsafeError (rc, loc);
}
var dep = member.GetMissingDependencies ();
if (dep != null) {
ImportedTypeDefinition.Error_MissingDependency (rc, dep, loc);
}
if (!rc.IsObsolete) {
ObsoleteAttribute oa = member.GetAttributeObsolete ();
if (oa != null)
AttributeTester.Report_ObsoleteMessage (oa, member.GetSignatureForError (), loc, rc.Report);
}
if (!(member is FieldSpec))
member.MemberDefinition.SetIsUsed ();
}
protected virtual void Error_CannotCallAbstractBase (ResolveContext rc, string name)
{
rc.Report.Error (205, loc, "Cannot call an abstract base member `{0}'", name);
}
public static void Error_ProtectedMemberAccess (ResolveContext rc, MemberSpec member, TypeSpec qualifier, Location loc)
{
rc.Report.SymbolRelatedToPreviousError (member);
rc.Report.Error (1540, loc,
"Cannot access protected member `{0}' via a qualifier of type `{1}'. The qualifier must be of type `{2}' or derived from it",
member.GetSignatureForError (), qualifier.GetSignatureForError (), rc.CurrentType.GetSignatureForError ());
}
public bool ResolveInstanceExpression (ResolveContext rc, Expression rhs)
{
if (!ResolveInstanceExpressionCore (rc, rhs))
return false;
//
// Check intermediate value modification which won't have any effect
//
if (rhs != null && InstanceExpression.Type.IsStruct &&
(InstanceExpression is PropertyExpr || InstanceExpression is IndexerExpr || InstanceExpression is Invocation)) {
if (rc.CurrentInitializerVariable != null) {
rc.Report.Error (1918, loc, "Members of value type `{0}' cannot be assigned using a property `{1}' object initializer",
InstanceExpression.Type.GetSignatureForError (), InstanceExpression.GetSignatureForError ());
} else {
rc.Report.Error (1612, loc,
"Cannot modify a value type return value of `{0}'. Consider storing the value in a temporary variable",
InstanceExpression.GetSignatureForError ());
}
}
return true;
}
bool ResolveInstanceExpressionCore (ResolveContext rc, Expression rhs)
{
if (IsStatic) {
if (InstanceExpression != null) {
if (InstanceExpression is TypeExpr) {
var t = InstanceExpression.Type;
do {
ObsoleteAttribute oa = t.GetAttributeObsolete ();
if (oa != null && !rc.IsObsolete) {
AttributeTester.Report_ObsoleteMessage (oa, t.GetSignatureForError (), loc, rc.Report);
}
t = t.DeclaringType;
} while (t != null);
} else {
var runtime_expr = InstanceExpression as RuntimeValueExpression;
if (runtime_expr == null || !runtime_expr.IsSuggestionOnly) {
rc.Report.Error (176, loc,
"Static member `{0}' cannot be accessed with an instance reference, qualify it with a type name instead",
GetSignatureForError ());
}
}
InstanceExpression = null;
}
return false;
}
if (InstanceExpression == null || InstanceExpression is TypeExpr) {
if (InstanceExpression != null || !This.IsThisAvailable (rc, true)) {
if (rc.HasSet (ResolveContext.Options.FieldInitializerScope))
rc.Report.Error (236, loc,
"A field initializer cannot reference the nonstatic field, method, or property `{0}'",
GetSignatureForError ());
else
rc.Report.Error (120, loc,
"An object reference is required to access non-static member `{0}'",
GetSignatureForError ());
InstanceExpression = new CompilerGeneratedThis (rc.CurrentType, loc).Resolve (rc);
return false;
}
if (!TypeManager.IsFamilyAccessible (rc.CurrentType, DeclaringType)) {
rc.Report.Error (38, loc,
"Cannot access a nonstatic member of outer type `{0}' via nested type `{1}'",
DeclaringType.GetSignatureForError (), rc.CurrentType.GetSignatureForError ());
}
InstanceExpression = new This (loc);
if (this is FieldExpr && rc.CurrentBlock.ParametersBlock.TopBlock.ThisVariable != null) {
using (rc.Set (ResolveContext.Options.OmitStructFlowAnalysis)) {
InstanceExpression = InstanceExpression.Resolve (rc);
}
} else {
InstanceExpression = InstanceExpression.Resolve (rc);
}
return false;
}
var me = InstanceExpression as MemberExpr;
if (me != null) {
me.ResolveInstanceExpressionCore (rc, rhs);
// Using this check to detect probing instance expression resolve
if (!rc.OmitStructFlowAnalysis) {
var fe = me as FieldExpr;
if (fe != null && fe.IsMarshalByRefAccess (rc)) {
rc.Report.SymbolRelatedToPreviousError (me.DeclaringType);
rc.Report.Warning (1690, 1, loc,
"Cannot call methods, properties, or indexers on `{0}' because it is a value type member of a marshal-by-reference class",
me.GetSignatureForError ());
}
}
return true;
}
//
// Run member-access postponed check once we know that
// the expression is not field expression which is the only
// expression which can use uninitialized this
//
if (InstanceExpression is This && !(this is FieldExpr) && rc.CurrentBlock.ParametersBlock.TopBlock.ThisVariable != null) {
((This)InstanceExpression).CheckStructThisDefiniteAssignment (rc);
}
//
// Additional checks for l-value member access
//
if (rhs != null) {
if (InstanceExpression is UnboxCast) {
rc.Report.Error (445, InstanceExpression.Location, "Cannot modify the result of an unboxing conversion");
}
}
return true;
}
public virtual MemberExpr ResolveMemberAccess (ResolveContext ec, Expression left, SimpleName original)
{
if (left != null && left.IsNull && TypeSpec.IsReferenceType (left.Type)) {
ec.Report.Warning (1720, 1, left.Location,
"Expression will always cause a `{0}'", "System.NullReferenceException");
}
InstanceExpression = left;
return this;
}
protected void EmitInstance (EmitContext ec, bool prepare_for_load)
{
TypeSpec instance_type = InstanceExpression.Type;
if (TypeSpec.IsValueType (instance_type)) {
if (InstanceExpression is IMemoryLocation) {
((IMemoryLocation) InstanceExpression).AddressOf (ec, AddressOp.Load);
} else {
// Cannot release the temporary variable when its address
// is required to be on stack for any parent
LocalTemporary t = new LocalTemporary (instance_type);
InstanceExpression.Emit (ec);
t.Store (ec);
t.AddressOf (ec, AddressOp.Store);
}
} else {
InstanceExpression.Emit (ec);
// Only to make verifier happy
if (instance_type.IsGenericParameter && !(InstanceExpression is This) && TypeSpec.IsReferenceType (instance_type))
ec.Emit (OpCodes.Box, instance_type);
}
if (prepare_for_load)
ec.Emit (OpCodes.Dup);
}
public abstract void SetTypeArguments (ResolveContext ec, TypeArguments ta);
}
public class ExtensionMethodCandidates
{
readonly NamespaceContainer container;
readonly IList<MethodSpec> methods;
readonly int index;
readonly IMemberContext context;
public ExtensionMethodCandidates (IMemberContext context, IList<MethodSpec> methods, NamespaceContainer nsContainer, int lookupIndex)
{
this.context = context;
this.methods = methods;
this.container = nsContainer;
this.index = lookupIndex;
}
public NamespaceContainer Container {
get {
return container;
}
}
public IMemberContext Context {
get {
return context;
}
}
public int LookupIndex {
get {
return index;
}
}
public IList<MethodSpec> Methods {
get {
return methods;
}
}
}
//
// Represents a group of extension method candidates for whole namespace
//
class ExtensionMethodGroupExpr : MethodGroupExpr, OverloadResolver.IErrorHandler
{
ExtensionMethodCandidates candidates;
public Expression ExtensionExpression;
public ExtensionMethodGroupExpr (ExtensionMethodCandidates candidates, Expression extensionExpr, Location loc)
: base (candidates.Methods.Cast<MemberSpec>().ToList (), extensionExpr.Type, loc)
{
this.candidates = candidates;
this.ExtensionExpression = extensionExpr;
}
public override bool IsStatic {
get { return true; }
}
//
// For extension methodgroup we are not looking for base members but parent
// namespace extension methods
//
public override IList<MemberSpec> GetBaseMembers (TypeSpec baseType)
{
// TODO: candidates are null only when doing error reporting, that's
// incorrect. We have to discover same extension methods in error mode
if (candidates == null)
return null;
int arity = type_arguments == null ? 0 : type_arguments.Count;
candidates = candidates.Container.LookupExtensionMethod (candidates.Context, ExtensionExpression.Type, Name, arity, candidates.LookupIndex);
if (candidates == null)
return null;
return candidates.Methods.Cast<MemberSpec> ().ToList ();
}
public override MethodGroupExpr LookupExtensionMethod (ResolveContext rc)
{
// We are already here
return null;
}
public override MethodGroupExpr OverloadResolve (ResolveContext ec, ref Arguments arguments, OverloadResolver.IErrorHandler ehandler, OverloadResolver.Restrictions restr)
{
if (arguments == null)
arguments = new Arguments (1);
ExtensionExpression = ExtensionExpression.Resolve (ec);
if (ExtensionExpression == null)
return null;
var cand = candidates;
arguments.Insert (0, new Argument (ExtensionExpression, Argument.AType.ExtensionType));
var res = base.OverloadResolve (ec, ref arguments, ehandler ?? this, restr);
// Restore candidates in case we are running in probing mode
candidates = cand;
// Store resolved argument and restore original arguments
if (res == null) {
// Clean-up modified arguments for error reporting
arguments.RemoveAt (0);
return null;
}
var me = ExtensionExpression as MemberExpr;
if (me != null) {
me.ResolveInstanceExpression (ec, null);
var fe = me as FieldExpr;
if (fe != null)
fe.Spec.MemberDefinition.SetIsUsed ();
}
InstanceExpression = null;
return this;
}
#region IErrorHandler Members
bool OverloadResolver.IErrorHandler.AmbiguousCandidates (ResolveContext rc, MemberSpec best, MemberSpec ambiguous)
{
return false;
}
bool OverloadResolver.IErrorHandler.ArgumentMismatch (ResolveContext rc, MemberSpec best, Argument arg, int index)
{
rc.Report.SymbolRelatedToPreviousError (best);
rc.Report.Error (1928, loc,
"Type `{0}' does not contain a member `{1}' and the best extension method overload `{2}' has some invalid arguments",
queried_type.GetSignatureForError (), Name, best.GetSignatureForError ());
if (index == 0) {
rc.Report.Error (1929, loc,
"Extension method instance type `{0}' cannot be converted to `{1}'",
arg.Type.GetSignatureForError (), ((MethodSpec)best).Parameters.ExtensionMethodType.GetSignatureForError ());
}
return true;
}
bool OverloadResolver.IErrorHandler.NoArgumentMatch (ResolveContext rc, MemberSpec best)
{
return false;
}
bool OverloadResolver.IErrorHandler.TypeInferenceFailed (ResolveContext rc, MemberSpec best)
{
return false;
}
#endregion
}
/// <summary>
/// MethodGroupExpr represents a group of method candidates which
/// can be resolved to the best method overload
/// </summary>
public class MethodGroupExpr : MemberExpr, OverloadResolver.IBaseMembersProvider
{
protected IList<MemberSpec> Methods;
MethodSpec best_candidate;
TypeSpec best_candidate_return;
protected TypeArguments type_arguments;
SimpleName simple_name;
protected TypeSpec queried_type;
public MethodGroupExpr (IList<MemberSpec> mi, TypeSpec type, Location loc)
{
Methods = mi;
this.loc = loc;
this.type = InternalType.MethodGroup;
eclass = ExprClass.MethodGroup;
queried_type = type;
}
public MethodGroupExpr (MethodSpec m, TypeSpec type, Location loc)
: this (new MemberSpec[] { m }, type, loc)
{
}
#region Properties
public MethodSpec BestCandidate {
get {
return best_candidate;
}
}
public TypeSpec BestCandidateReturnType {
get {
return best_candidate_return;
}
}
public IList<MemberSpec> Candidates {
get {
return Methods;
}
}
protected override TypeSpec DeclaringType {
get {
return queried_type;
}
}
public override bool IsInstance {
get {
if (best_candidate != null)
return !best_candidate.IsStatic;
return false;
}
}
public override bool IsStatic {
get {
if (best_candidate != null)
return best_candidate.IsStatic;
return false;
}
}
public override string KindName {
get { return "method"; }
}
public override string Name {
get {
if (best_candidate != null)
return best_candidate.Name;
// TODO: throw ?
return Methods.First ().Name;
}
}
#endregion
//
// When best candidate is already know this factory can be used
// to avoid expensive overload resolution to be called
//
// NOTE: InstanceExpression has to be set manually
//
public static MethodGroupExpr CreatePredefined (MethodSpec best, TypeSpec queriedType, Location loc)
{
return new MethodGroupExpr (best, queriedType, loc) {
best_candidate = best,
best_candidate_return = best.ReturnType
};
}
public override string GetSignatureForError ()
{
if (best_candidate != null)
return best_candidate.GetSignatureForError ();
return Methods.First ().GetSignatureForError ();
}
public override Expression CreateExpressionTree (ResolveContext ec)
{
if (best_candidate == null) {
ec.Report.Error (1953, loc, "An expression tree cannot contain an expression with method group");
return null;
}
if (best_candidate.IsConditionallyExcluded (ec, loc))
ec.Report.Error (765, loc,
"Partial methods with only a defining declaration or removed conditional methods cannot be used in an expression tree");
return new TypeOfMethod (best_candidate, loc);
}
protected override Expression DoResolve (ResolveContext ec)
{
this.eclass = ExprClass.MethodGroup;
if (InstanceExpression != null) {
InstanceExpression = InstanceExpression.Resolve (ec);
if (InstanceExpression == null)
return null;
}
return this;
}
public override void Emit (EmitContext ec)
{
throw new NotSupportedException ();
}
public void EmitCall (EmitContext ec, Arguments arguments)
{
var call = new CallEmitter ();
call.InstanceExpression = InstanceExpression;
call.Emit (ec, best_candidate, arguments, loc);
}
public override void Error_ValueCannotBeConverted (ResolveContext ec, TypeSpec target, bool expl)
{
ec.Report.Error (428, loc, "Cannot convert method group `{0}' to non-delegate type `{1}'. Consider using parentheses to invoke the method",
Name, target.GetSignatureForError ());
}
public static bool IsExtensionMethodArgument (Expression expr)
{
//
// LAMESPEC: No details about which expressions are not allowed
//
return !(expr is TypeExpr) && !(expr is BaseThis);
}
/// <summary>
/// Find the Applicable Function Members (7.4.2.1)
///
/// me: Method Group expression with the members to select.
/// it might contain constructors or methods (or anything
/// that maps to a method).
///
/// Arguments: ArrayList containing resolved Argument objects.
///
/// loc: The location if we want an error to be reported, or a Null
/// location for "probing" purposes.
///
/// Returns: The MethodBase (either a ConstructorInfo or a MethodInfo)
/// that is the best match of me on Arguments.
///
/// </summary>
public virtual MethodGroupExpr OverloadResolve (ResolveContext ec, ref Arguments args, OverloadResolver.IErrorHandler cerrors, OverloadResolver.Restrictions restr)
{
// TODO: causes issues with probing mode, remove explicit Kind check
if (best_candidate != null && best_candidate.Kind == MemberKind.Destructor)
return this;
var r = new OverloadResolver (Methods, type_arguments, restr, loc);
if ((restr & OverloadResolver.Restrictions.NoBaseMembers) == 0) {
r.BaseMembersProvider = this;
r.InstanceQualifier = this;
}
if (cerrors != null)
r.CustomErrors = cerrors;
// TODO: When in probing mode do IsApplicable only and when called again do VerifyArguments for full error reporting
best_candidate = r.ResolveMember<MethodSpec> (ec, ref args);
if (best_candidate == null)
return r.BestCandidateIsDynamic ? this : null;
// Overload resolver had to create a new method group, all checks bellow have already been executed
if (r.BestCandidateNewMethodGroup != null)
return r.BestCandidateNewMethodGroup;
if (best_candidate.Kind == MemberKind.Method && (restr & OverloadResolver.Restrictions.ProbingOnly) == 0) {
if (InstanceExpression != null) {
if (best_candidate.IsExtensionMethod && args[0].Expr == InstanceExpression) {
InstanceExpression = null;
} else {
if (best_candidate.IsStatic && simple_name != null) {
InstanceExpression = ProbeIdenticalTypeName (ec, InstanceExpression, simple_name);
}
InstanceExpression.Resolve (ec, ResolveFlags.VariableOrValue | ResolveFlags.MethodGroup | ResolveFlags.Type);
}
}
ResolveInstanceExpression (ec, null);
}
var base_override = CandidateToBaseOverride (ec, best_candidate);
if (base_override == best_candidate) {
best_candidate_return = r.BestCandidateReturnType;
} else {
best_candidate = base_override;
best_candidate_return = best_candidate.ReturnType;
}
if (best_candidate.IsGeneric && (restr & OverloadResolver.Restrictions.ProbingOnly) == 0 && TypeParameterSpec.HasAnyTypeParameterConstrained (best_candidate.GenericDefinition)) {
ConstraintChecker cc = new ConstraintChecker (ec);
cc.CheckAll (best_candidate.GetGenericMethodDefinition (), best_candidate.TypeArguments, best_candidate.Constraints, loc);
}
//
// Additional check for possible imported base override method which
// could not be done during IsOverrideMethodBaseTypeAccessible
//
if (best_candidate.IsVirtual && (best_candidate.DeclaringType.Modifiers & Modifiers.PROTECTED) != 0 &&
best_candidate.MemberDefinition.IsImported && !best_candidate.DeclaringType.IsAccessible (ec)) {
ec.Report.SymbolRelatedToPreviousError (best_candidate);
ErrorIsInaccesible (ec, best_candidate.GetSignatureForError (), loc);
}
return this;
}
public override MemberExpr ResolveMemberAccess (ResolveContext ec, Expression left, SimpleName original)
{
var fe = left as FieldExpr;
if (fe != null) {
//
// Using method-group on struct fields makes the struct assigned. I am not sure
// why but that's what .net does
//
fe.Spec.MemberDefinition.SetIsAssigned ();
}
simple_name = original;
return base.ResolveMemberAccess (ec, left, original);
}
public override void SetTypeArguments (ResolveContext ec, TypeArguments ta)
{
type_arguments = ta;
}
#region IBaseMembersProvider Members
public virtual IList<MemberSpec> GetBaseMembers (TypeSpec baseType)
{
return baseType == null ? null : MemberCache.FindMembers (baseType, Methods [0].Name, false);
}
public IParametersMember GetOverrideMemberParameters (MemberSpec member)
{
if (queried_type == member.DeclaringType)
return null;
return MemberCache.FindMember (queried_type, new MemberFilter ((MethodSpec) member),
BindingRestriction.InstanceOnly | BindingRestriction.OverrideOnly) as IParametersMember;
}
//
// Extension methods lookup after ordinary methods candidates failed to apply
//
public virtual MethodGroupExpr LookupExtensionMethod (ResolveContext rc)
{
if (InstanceExpression == null || InstanceExpression.eclass == ExprClass.Type)
return null;
InstanceExpression = InstanceExpression.Resolve (rc);
if (!IsExtensionMethodArgument (InstanceExpression))
return null;
int arity = type_arguments == null ? 0 : type_arguments.Count;
var methods = rc.LookupExtensionMethod (InstanceExpression.Type, Methods[0].Name, arity);
if (methods == null)
return null;
var emg = new ExtensionMethodGroupExpr (methods, InstanceExpression, loc);
emg.SetTypeArguments (rc, type_arguments);
return emg;
}
#endregion
}
struct ConstructorInstanceQualifier : OverloadResolver.IInstanceQualifier
{
public ConstructorInstanceQualifier (TypeSpec type)
: this ()
{
InstanceType = type;
}
public TypeSpec InstanceType { get; private set; }
public bool CheckProtectedMemberAccess (ResolveContext rc, MemberSpec member)
{
return MemberExpr.CheckProtectedMemberAccess (rc, member, InstanceType);
}
}
public struct OverloadResolver
{
[Flags]
public enum Restrictions
{
None = 0,
DelegateInvoke = 1,
ProbingOnly = 1 << 1,
CovariantDelegate = 1 << 2,
NoBaseMembers = 1 << 3,
BaseMembersIncluded = 1 << 4
}
public interface IBaseMembersProvider
{
IList<MemberSpec> GetBaseMembers (TypeSpec baseType);
IParametersMember GetOverrideMemberParameters (MemberSpec member);
MethodGroupExpr LookupExtensionMethod (ResolveContext rc);
}
public interface IErrorHandler
{
bool AmbiguousCandidates (ResolveContext rc, MemberSpec best, MemberSpec ambiguous);
bool ArgumentMismatch (ResolveContext rc, MemberSpec best, Argument a, int index);
bool NoArgumentMatch (ResolveContext rc, MemberSpec best);
bool TypeInferenceFailed (ResolveContext rc, MemberSpec best);
}
public interface IInstanceQualifier
{
TypeSpec InstanceType { get; }
bool CheckProtectedMemberAccess (ResolveContext rc, MemberSpec member);
}
sealed class NoBaseMembers : IBaseMembersProvider
{
public static readonly IBaseMembersProvider Instance = new NoBaseMembers ();
public IList<MemberSpec> GetBaseMembers (TypeSpec baseType)
{
return null;
}
public IParametersMember GetOverrideMemberParameters (MemberSpec member)
{
return null;
}
public MethodGroupExpr LookupExtensionMethod (ResolveContext rc)
{
return null;
}
}
struct AmbiguousCandidate
{
public readonly MemberSpec Member;
public readonly bool Expanded;
public readonly AParametersCollection Parameters;
public AmbiguousCandidate (MemberSpec member, AParametersCollection parameters, bool expanded)
{
Member = member;
Parameters = parameters;
Expanded = expanded;
}
}
Location loc;
IList<MemberSpec> members;
TypeArguments type_arguments;
IBaseMembersProvider base_provider;
IErrorHandler custom_errors;
IInstanceQualifier instance_qualifier;
Restrictions restrictions;
MethodGroupExpr best_candidate_extension_group;
TypeSpec best_candidate_return_type;
SessionReportPrinter lambda_conv_msgs;
public OverloadResolver (IList<MemberSpec> members, Restrictions restrictions, Location loc)
: this (members, null, restrictions, loc)
{
}
public OverloadResolver (IList<MemberSpec> members, TypeArguments targs, Restrictions restrictions, Location loc)
: this ()
{
if (members == null || members.Count == 0)
throw new ArgumentException ("empty members set");
this.members = members;
this.loc = loc;
type_arguments = targs;
this.restrictions = restrictions;
if (IsDelegateInvoke)
this.restrictions |= Restrictions.NoBaseMembers;
base_provider = NoBaseMembers.Instance;
}
#region Properties
public IBaseMembersProvider BaseMembersProvider {
get {
return base_provider;
}
set {
base_provider = value;
}
}
public bool BestCandidateIsDynamic { get; set; }
//
// Best candidate was found in newly created MethodGroupExpr, used by extension methods
//
public MethodGroupExpr BestCandidateNewMethodGroup {
get {
return best_candidate_extension_group;
}
}
//
// Return type can be different between best candidate and closest override
//
public TypeSpec BestCandidateReturnType {
get {
return best_candidate_return_type;
}
}
public IErrorHandler CustomErrors {
get {
return custom_errors;
}
set {
custom_errors = value;
}
}
TypeSpec DelegateType {
get {
if ((restrictions & Restrictions.DelegateInvoke) == 0)
throw new InternalErrorException ("Not running in delegate mode", loc);
return members [0].DeclaringType;
}
}
public IInstanceQualifier InstanceQualifier {
get {
return instance_qualifier;
}
set {
instance_qualifier = value;
}
}
bool IsProbingOnly {
get {
return (restrictions & Restrictions.ProbingOnly) != 0;
}
}
bool IsDelegateInvoke {
get {
return (restrictions & Restrictions.DelegateInvoke) != 0;
}
}
#endregion
//
// 7.4.3.3 Better conversion from expression
// Returns : 1 if a->p is better,
// 2 if a->q is better,
// 0 if neither is better
//
static int BetterExpressionConversion (ResolveContext ec, Argument a, TypeSpec p, TypeSpec q)
{
TypeSpec argument_type = a.Type;
//
// If argument is an anonymous function
//
if (argument_type == InternalType.AnonymousMethod && ec.Module.Compiler.Settings.Version > LanguageVersion.ISO_2) {
//
// p and q are delegate types or expression tree types
//
if (p.IsExpressionTreeType || q.IsExpressionTreeType) {
if (q.MemberDefinition != p.MemberDefinition) {
return 0;
}
//
// Uwrap delegate from Expression<T>
//
q = TypeManager.GetTypeArguments (q)[0];
p = TypeManager.GetTypeArguments (p)[0];
}
var p_m = Delegate.GetInvokeMethod (p);
var q_m = Delegate.GetInvokeMethod (q);
//
// With identical parameter lists
//
if (!TypeSpecComparer.Equals (p_m.Parameters.Types, q_m.Parameters.Types))
return 0;
var orig_p = p;
p = p_m.ReturnType;
var orig_q = q;
q = q_m.ReturnType;
//
// if p is void returning, and q has a return type Y, then C2 is the better conversion.
//
if (p.Kind == MemberKind.Void) {
return q.Kind != MemberKind.Void ? 2 : 0;
}
//
// if p has a return type Y, and q is void returning, then C1 is the better conversion.
//
if (q.Kind == MemberKind.Void) {
return p.Kind != MemberKind.Void ? 1: 0;
}
var am = (AnonymousMethodExpression) a.Expr;
//
// When anonymous method is an asynchronous, and P has a return type Task<Y1>, and Q has a return type Task<Y2>
// better conversion is performed between underlying types Y1 and Y2
//
if (p.IsGenericTask || q.IsGenericTask) {
if (am.Block.IsAsync && p.IsGenericTask && q.IsGenericTask) {
q = q.TypeArguments[0];
p = p.TypeArguments[0];
}
} else if (q != p) {
//
// LAMESPEC: Lambda expression returning dynamic type has identity (better) conversion to delegate returning object type
//
if (q.BuiltinType == BuiltinTypeSpec.Type.Object) {
var am_rt = am.InferReturnType (ec, null, orig_q);
if (am_rt != null && am_rt.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
return 2;
} else if (p.BuiltinType == BuiltinTypeSpec.Type.Object) {
var am_rt = am.InferReturnType (ec, null, orig_p);
if (am_rt != null && am_rt.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
return 1;
}
}
//
// The parameters are identicial and return type is not void, use better type conversion
// on return type to determine better one
//
} else {
if (argument_type == p)
return 1;
if (argument_type == q)
return 2;
}
return BetterTypeConversion (ec, p, q);
}
//
// 7.4.3.4 Better conversion from type
//
public static int BetterTypeConversion (ResolveContext ec, TypeSpec p, TypeSpec q)
{
if (p == null || q == null)
throw new InternalErrorException ("BetterTypeConversion got a null conversion");
switch (p.BuiltinType) {
case BuiltinTypeSpec.Type.Int:
if (q.BuiltinType == BuiltinTypeSpec.Type.UInt || q.BuiltinType == BuiltinTypeSpec.Type.ULong)
return 1;
break;
case BuiltinTypeSpec.Type.Long:
if (q.BuiltinType == BuiltinTypeSpec.Type.ULong)
return 1;
break;
case BuiltinTypeSpec.Type.SByte:
switch (q.BuiltinType) {
case BuiltinTypeSpec.Type.Byte:
case BuiltinTypeSpec.Type.UShort:
case BuiltinTypeSpec.Type.UInt:
case BuiltinTypeSpec.Type.ULong:
return 1;
}
break;
case BuiltinTypeSpec.Type.Short:
switch (q.BuiltinType) {
case BuiltinTypeSpec.Type.UShort:
case BuiltinTypeSpec.Type.UInt:
case BuiltinTypeSpec.Type.ULong:
return 1;
}
break;
case BuiltinTypeSpec.Type.Dynamic:
// Dynamic is never better
return 2;
}
switch (q.BuiltinType) {
case BuiltinTypeSpec.Type.Int:
if (p.BuiltinType == BuiltinTypeSpec.Type.UInt || p.BuiltinType == BuiltinTypeSpec.Type.ULong)
return 2;
break;
case BuiltinTypeSpec.Type.Long:
if (p.BuiltinType == BuiltinTypeSpec.Type.ULong)
return 2;
break;
case BuiltinTypeSpec.Type.SByte:
switch (p.BuiltinType) {
case BuiltinTypeSpec.Type.Byte:
case BuiltinTypeSpec.Type.UShort:
case BuiltinTypeSpec.Type.UInt:
case BuiltinTypeSpec.Type.ULong:
return 2;
}
break;
case BuiltinTypeSpec.Type.Short:
switch (p.BuiltinType) {
case BuiltinTypeSpec.Type.UShort:
case BuiltinTypeSpec.Type.UInt:
case BuiltinTypeSpec.Type.ULong:
return 2;
}
break;
case BuiltinTypeSpec.Type.Dynamic:
// Dynamic is never better
return 1;
}
// FIXME: handle lifted operators
// TODO: this is expensive
Expression p_tmp = new EmptyExpression (p);
Expression q_tmp = new EmptyExpression (q);
bool p_to_q = Convert.ImplicitConversionExists (ec, p_tmp, q);
bool q_to_p = Convert.ImplicitConversionExists (ec, q_tmp, p);
if (p_to_q && !q_to_p)
return 1;
if (q_to_p && !p_to_q)
return 2;
return 0;
}
/// <summary>
/// Determines "Better function" between candidate
/// and the current best match
/// </summary>
/// <remarks>
/// Returns a boolean indicating :
/// false if candidate ain't better
/// true if candidate is better than the current best match
/// </remarks>
static bool BetterFunction (ResolveContext ec, Arguments args, MemberSpec candidate, AParametersCollection cparam, bool candidate_params,
MemberSpec best, AParametersCollection bparam, bool best_params)
{
AParametersCollection candidate_pd = ((IParametersMember) candidate).Parameters;
AParametersCollection best_pd = ((IParametersMember) best).Parameters;
bool better_at_least_one = false;
bool same = true;
int args_count = args == null ? 0 : args.Count;
int j = 0;
Argument a = null;
TypeSpec ct, bt;
for (int c_idx = 0, b_idx = 0; j < args_count; ++j, ++c_idx, ++b_idx) {
a = args[j];
// Default arguments are ignored for better decision
if (a.IsDefaultArgument)
break;
//
// When comparing named argument the parameter type index has to be looked up
// in original parameter set (override version for virtual members)
//
NamedArgument na = a as NamedArgument;
if (na != null) {
int idx = cparam.GetParameterIndexByName (na.Name);
ct = candidate_pd.Types[idx];
if (candidate_params && candidate_pd.FixedParameters[idx].ModFlags == Parameter.Modifier.PARAMS)
ct = TypeManager.GetElementType (ct);
idx = bparam.GetParameterIndexByName (na.Name);
bt = best_pd.Types[idx];
if (best_params && best_pd.FixedParameters[idx].ModFlags == Parameter.Modifier.PARAMS)
bt = TypeManager.GetElementType (bt);
} else {
ct = candidate_pd.Types[c_idx];
bt = best_pd.Types[b_idx];
if (candidate_params && candidate_pd.FixedParameters[c_idx].ModFlags == Parameter.Modifier.PARAMS) {
ct = TypeManager.GetElementType (ct);
--c_idx;
}
if (best_params && best_pd.FixedParameters[b_idx].ModFlags == Parameter.Modifier.PARAMS) {
bt = TypeManager.GetElementType (bt);
--b_idx;
}
}
if (TypeSpecComparer.IsEqual (ct, bt))
continue;
same = false;
int result = BetterExpressionConversion (ec, a, ct, bt);
// for each argument, the conversion to 'ct' should be no worse than
// the conversion to 'bt'.
if (result == 2)
return false;
// for at least one argument, the conversion to 'ct' should be better than
// the conversion to 'bt'.
if (result != 0)
better_at_least_one = true;
}
if (better_at_least_one)
return true;
//
// This handles the case
//
// Add (float f1, float f2, float f3);
// Add (params decimal [] foo);
//
// The call Add (3, 4, 5) should be ambiguous. Without this check, the
// first candidate would've chosen as better.
//
if (!same && !a.IsDefaultArgument)
return false;
//
// The two methods have equal non-optional parameter types, apply tie-breaking rules
//
//
// This handles the following cases:
//
// Foo (int i) is better than Foo (int i, long l = 0)
// Foo (params int[] args) is better than Foo (int i = 0, params int[] args)
// Foo (string s, params string[] args) is better than Foo (params string[] args)
//
// Prefer non-optional version
//
// LAMESPEC: Specification claims this should be done at last but the opposite is true
//
if (candidate_params == best_params && candidate_pd.Count != best_pd.Count) {
if (j < candidate_pd.Count && candidate_pd.FixedParameters[j].HasDefaultValue)
return false;
if (j < best_pd.Count && best_pd.FixedParameters[j].HasDefaultValue)
return true;
return candidate_pd.Count >= best_pd.Count;
}
//
// One is a non-generic method and second is a generic method, then non-generic is better
//
if (best.IsGeneric != candidate.IsGeneric)
return best.IsGeneric;
//
// This handles the following cases:
//
// Trim () is better than Trim (params char[] chars)
// Concat (string s1, string s2, string s3) is better than
// Concat (string s1, params string [] srest)
// Foo (int, params int [] rest) is better than Foo (params int [] rest)
//
// Prefer non-expanded version
//
if (candidate_params != best_params)
return best_params;
int candidate_param_count = candidate_pd.Count;
int best_param_count = best_pd.Count;
if (candidate_param_count != best_param_count)
// can only happen if (candidate_params && best_params)
return candidate_param_count > best_param_count && best_pd.HasParams;
//
// Both methods have the same number of parameters, and the parameters have equal types
// Pick the "more specific" signature using rules over original (non-inflated) types
//
var candidate_def_pd = ((IParametersMember) candidate.MemberDefinition).Parameters;
var best_def_pd = ((IParametersMember) best.MemberDefinition).Parameters;
bool specific_at_least_once = false;
for (j = 0; j < args_count; ++j) {
NamedArgument na = args_count == 0 ? null : args [j] as NamedArgument;
if (na != null) {
ct = candidate_def_pd.Types[cparam.GetParameterIndexByName (na.Name)];
bt = best_def_pd.Types[bparam.GetParameterIndexByName (na.Name)];
} else {
ct = candidate_def_pd.Types[j];
bt = best_def_pd.Types[j];
}
if (ct == bt)
continue;
TypeSpec specific = MoreSpecific (ct, bt);
if (specific == bt)
return false;
if (specific == ct)
specific_at_least_once = true;
}
if (specific_at_least_once)
return true;
return false;
}
static bool CheckInflatedArguments (MethodSpec ms)
{
if (!TypeParameterSpec.HasAnyTypeParameterTypeConstrained (ms.GenericDefinition))
return true;
// Setup constraint checker for probing only
ConstraintChecker cc = new ConstraintChecker (null);
var mp = ms.Parameters.Types;
for (int i = 0; i < mp.Length; ++i) {
var type = mp[i] as InflatedTypeSpec;
if (type == null)
continue;
var targs = type.TypeArguments;
if (targs.Length == 0)
continue;
// TODO: Checking inflated MVAR arguments should be enough
if (!cc.CheckAll (type.GetDefinition (), targs, type.Constraints, Location.Null))
return false;
}
return true;
}
public static void Error_ConstructorMismatch (ResolveContext rc, TypeSpec type, int argCount, Location loc)
{
rc.Report.Error (1729, loc,
"The type `{0}' does not contain a constructor that takes `{1}' arguments",
type.GetSignatureForError (), argCount.ToString ());
}
//
// Determines if the candidate method is applicable to the given set of arguments
// There could be two different set of parameters for same candidate where one
// is the closest override for default values and named arguments checks and second
// one being the virtual base for the parameter types and modifiers.
//
// A return value rates candidate method compatibility,
// 0 = the best, int.MaxValue = the worst
// -1 = fatal error
//
int IsApplicable (ResolveContext ec, ref Arguments arguments, int arg_count, ref MemberSpec candidate, IParametersMember pm, ref bool params_expanded_form, ref bool dynamicArgument, ref TypeSpec returnType)
{
// Parameters of most-derived type used mainly for named and optional parameters
var pd = pm.Parameters;
// Used for params modifier only, that's legacy of C# 1.0 which uses base type for
// params modifier instead of most-derived type
var cpd = ((IParametersMember) candidate).Parameters;
int param_count = pd.Count;
int optional_count = 0;
int score;
Arguments orig_args = arguments;
if (arg_count != param_count) {
//
// No arguments expansion when doing exact match for delegates
//
if ((restrictions & Restrictions.CovariantDelegate) == 0) {
for (int i = 0; i < pd.Count; ++i) {
if (pd.FixedParameters[i].HasDefaultValue) {
optional_count = pd.Count - i;
break;
}
}
}
if (optional_count != 0) {
// Readjust expected number when params used
if (cpd.HasParams) {
optional_count--;
if (arg_count < param_count)
param_count--;
} else if (arg_count > param_count) {
int args_gap = System.Math.Abs (arg_count - param_count);
return int.MaxValue - 10000 + args_gap;
} else if (arg_count < param_count - optional_count) {
int args_gap = System.Math.Abs (param_count - optional_count - arg_count);
return int.MaxValue - 10000 + args_gap;
}
} else if (arg_count != param_count) {
int args_gap = System.Math.Abs (arg_count - param_count);
if (!cpd.HasParams)
return int.MaxValue - 10000 + args_gap;
if (arg_count < param_count - 1)
return int.MaxValue - 10000 + args_gap;
}
// Resize to fit optional arguments
if (optional_count != 0) {
if (arguments == null) {
arguments = new Arguments (optional_count);
} else {
// Have to create a new container, so the next run can do same
var resized = new Arguments (param_count);
resized.AddRange (arguments);
arguments = resized;
}
for (int i = arg_count; i < param_count; ++i)
arguments.Add (null);
}
}
if (arg_count > 0) {
//
// Shuffle named arguments to the right positions if there are any
//
if (arguments[arg_count - 1] is NamedArgument) {
arg_count = arguments.Count;
for (int i = 0; i < arg_count; ++i) {
bool arg_moved = false;
while (true) {
NamedArgument na = arguments[i] as NamedArgument;
if (na == null)
break;
int index = pd.GetParameterIndexByName (na.Name);
// Named parameter not found
if (index < 0)
return (i + 1) * 3;
// already reordered
if (index == i)
break;
Argument temp;
if (index >= param_count) {
// When using parameters which should not be available to the user
if ((cpd.FixedParameters[index].ModFlags & Parameter.Modifier.PARAMS) == 0)
break;
arguments.Add (null);
++arg_count;
temp = null;
} else {
temp = arguments[index];
// The slot has been taken by positional argument
if (temp != null && !(temp is NamedArgument))
break;
}
if (!arg_moved) {
arguments = arguments.MarkOrderedArgument (na);
arg_moved = true;
}
arguments[index] = arguments[i];
arguments[i] = temp;
if (temp == null)
break;
}
}
} else {
arg_count = arguments.Count;
}
} else if (arguments != null) {
arg_count = arguments.Count;
}
//
// Don't do any expensive checks when the candidate cannot succeed
//
if (arg_count != param_count && !cpd.HasParams)
return (param_count - arg_count) * 2 + 1;
var dep = candidate.GetMissingDependencies ();
if (dep != null) {
ImportedTypeDefinition.Error_MissingDependency (ec, dep, loc);
return -1;
}
//
// 1. Handle generic method using type arguments when specified or type inference
//
TypeSpec[] ptypes;
var ms = candidate as MethodSpec;
if (ms != null && ms.IsGeneric) {
if (type_arguments != null) {
var g_args_count = ms.Arity;
if (g_args_count != type_arguments.Count)
return int.MaxValue - 20000 + System.Math.Abs (type_arguments.Count - g_args_count);
ms = ms.MakeGenericMethod (ec, type_arguments.Arguments);
} else {
//
// Deploy custom error reporting for infered anonymous expression or lambda methods. When
// probing lambda methods keep all errors reported in separate set and once we are done and no best
// candidate was found use the set to report more details about what was wrong with lambda body.
// The general idea is to distinguish between code errors and errors caused by
// trial-and-error type inference
//
if (lambda_conv_msgs == null) {
for (int i = 0; i < arg_count; i++) {
Argument a = arguments[i];
if (a == null)
continue;
var am = a.Expr as AnonymousMethodExpression;
if (am != null) {
if (lambda_conv_msgs == null)
lambda_conv_msgs = new SessionReportPrinter ();
am.TypeInferenceReportPrinter = lambda_conv_msgs;
}
}
}
var ti = new TypeInference (arguments);
TypeSpec[] i_args = ti.InferMethodArguments (ec, ms);
if (i_args == null)
return ti.InferenceScore - 20000;
//
// Clear any error messages when the result was success
//
if (lambda_conv_msgs != null)
lambda_conv_msgs.ClearSession ();
if (i_args.Length != 0) {
ms = ms.MakeGenericMethod (ec, i_args);
}
}
//
// Type arguments constraints have to match for the method to be applicable
//
if (!CheckInflatedArguments (ms)) {
candidate = ms;
return int.MaxValue - 25000;
}
//
// We have a generic return type and at same time the method is override which
// means we have to also inflate override return type in case the candidate is
// best candidate and override return type is different to base return type.
//
// virtual Foo<T, object> with override Foo<T, dynamic>
//
if (candidate != pm) {
MethodSpec override_ms = (MethodSpec) pm;
var inflator = new TypeParameterInflator (ec, ms.DeclaringType, override_ms.GenericDefinition.TypeParameters, ms.TypeArguments);
returnType = inflator.Inflate (returnType);
} else {
returnType = ms.ReturnType;
}
candidate = ms;
pd = ms.Parameters;
ptypes = pd.Types;
} else {
if (type_arguments != null)
return int.MaxValue - 15000;
ptypes = cpd.Types;
}
//
// 2. Each argument has to be implicitly convertible to method parameter
//
Parameter.Modifier p_mod = 0;
TypeSpec pt = null;
for (int i = 0; i < arg_count; i++) {
Argument a = arguments[i];
if (a == null) {
var fp = pd.FixedParameters[i];
if (!fp.HasDefaultValue) {
arguments = orig_args;
return arg_count * 2 + 2;
}
//
// Get the default value expression, we can use the same expression
// if the type matches
//
Expression e = fp.DefaultValue;
if (e != null) {
e = ResolveDefaultValueArgument (ec, ptypes[i], e, loc);
if (e == null) {
// Restore for possible error reporting
for (int ii = i; ii < arg_count; ++ii)
arguments.RemoveAt (i);
return (arg_count - i) * 2 + 1;
}
}
if ((fp.ModFlags & Parameter.Modifier.CallerMask) != 0) {
//
// LAMESPEC: Attributes can be mixed together with build-in priority
//
if ((fp.ModFlags & Parameter.Modifier.CallerLineNumber) != 0) {
e = new IntLiteral (ec.BuiltinTypes, loc.Row, loc);
} else if ((fp.ModFlags & Parameter.Modifier.CallerFilePath) != 0) {
e = new StringLiteral (ec.BuiltinTypes, loc.NameFullPath, loc);
} else if (ec.MemberContext.CurrentMemberDefinition != null) {
e = new StringLiteral (ec.BuiltinTypes, ec.MemberContext.CurrentMemberDefinition.GetCallerMemberName (), loc);
}
}
arguments[i] = new Argument (e, Argument.AType.Default);
continue;
}
if (p_mod != Parameter.Modifier.PARAMS) {
p_mod = (pd.FixedParameters[i].ModFlags & ~Parameter.Modifier.PARAMS) | (cpd.FixedParameters[i].ModFlags & Parameter.Modifier.PARAMS);
pt = ptypes [i];
} else if (!params_expanded_form) {
params_expanded_form = true;
pt = ((ElementTypeSpec) pt).Element;
i -= 2;
continue;
}
score = 1;
if (!params_expanded_form) {
if (a.ArgType == Argument.AType.ExtensionType) {
//
// Indentity, implicit reference or boxing conversion must exist for the extension parameter
//
// LAMESPEC: or implicit type parameter conversion
//
var at = a.Type;
if (at == pt || TypeSpecComparer.IsEqual (at, pt) ||
Convert.ImplicitReferenceConversionExists (at, pt, false) ||
Convert.ImplicitBoxingConversion (null, at, pt) != null) {
score = 0;
continue;
}
} else {
score = IsArgumentCompatible (ec, a, p_mod, pt);
if (score < 0)
dynamicArgument = true;
}
}
//
// It can be applicable in expanded form (when not doing exact match like for delegates)
//
if (score != 0 && (p_mod & Parameter.Modifier.PARAMS) != 0 && (restrictions & Restrictions.CovariantDelegate) == 0) {
if (!params_expanded_form) {
pt = ((ElementTypeSpec) pt).Element;
}
if (score > 0)
score = IsArgumentCompatible (ec, a, Parameter.Modifier.NONE, pt);
if (score < 0) {
params_expanded_form = true;
dynamicArgument = true;
} else if (score == 0 || arg_count > pd.Count) {
params_expanded_form = true;
}
}
if (score > 0) {
if (params_expanded_form)
++score;
return (arg_count - i) * 2 + score;
}
}
//
// When params parameter has no argument it will be provided later if the method is the best candidate
//
if (arg_count + 1 == pd.Count && (cpd.FixedParameters [arg_count].ModFlags & Parameter.Modifier.PARAMS) != 0)
params_expanded_form = true;
//
// Restore original arguments for dynamic binder to keep the intention of original source code
//
if (dynamicArgument)
arguments = orig_args;
return 0;
}
public static Expression ResolveDefaultValueArgument (ResolveContext ec, TypeSpec ptype, Expression e, Location loc)
{
if (e is Constant && e.Type == ptype)
return e;
//
// LAMESPEC: No idea what the exact rules are for System.Reflection.Missing.Value instead of null
//
if (e == EmptyExpression.MissingValue && ptype.BuiltinType == BuiltinTypeSpec.Type.Object || ptype.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
e = new MemberAccess (new MemberAccess (new MemberAccess (
new QualifiedAliasMember (QualifiedAliasMember.GlobalAlias, "System", loc), "Reflection", loc), "Missing", loc), "Value", loc);
} else if (e is Constant) {
//
// Handles int to int? conversions, DefaultParameterValue check
//
e = Convert.ImplicitConversionStandard (ec, e, ptype, loc);
if (e == null)
return null;
} else {
e = new DefaultValueExpression (new TypeExpression (ptype, loc), loc);
}
return e.Resolve (ec);
}
//
// Tests argument compatibility with the parameter
// The possible return values are
// 0 - success
// 1 - modifier mismatch
// 2 - type mismatch
// -1 - dynamic binding required
//
int IsArgumentCompatible (ResolveContext ec, Argument argument, Parameter.Modifier param_mod, TypeSpec parameter)
{
//
// Types have to be identical when ref or out modifer
// is used and argument is not of dynamic type
//
if (((argument.Modifier | param_mod) & Parameter.Modifier.RefOutMask) != 0) {
if (argument.Type != parameter) {
//
// Do full equality check after quick path
//
if (!TypeSpecComparer.IsEqual (argument.Type, parameter)) {
//
// Using dynamic for ref/out parameter can still succeed at runtime
//
if (argument.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic && (argument.Modifier & Parameter.Modifier.RefOutMask) == 0 && (restrictions & Restrictions.CovariantDelegate) == 0)
return -1;
return 2;
}
}
if ((argument.Modifier & Parameter.Modifier.RefOutMask) != (param_mod & Parameter.Modifier.RefOutMask)) {
//
// Using dynamic for ref/out parameter can still succeed at runtime
//
if (argument.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic && (argument.Modifier & Parameter.Modifier.RefOutMask) == 0 && (restrictions & Restrictions.CovariantDelegate) == 0)
return -1;
return 1;
}
} else {
if (argument.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic && (restrictions & Restrictions.CovariantDelegate) == 0)
return -1;
//
// Use implicit conversion in all modes to return same candidates when the expression
// is used as argument or delegate conversion
//
if (!Convert.ImplicitConversionExists (ec, argument.Expr, parameter)) {
return parameter.IsDelegate && argument.Expr is AnonymousMethodExpression ? 2 : 3;
}
}
return 0;
}
static TypeSpec MoreSpecific (TypeSpec p, TypeSpec q)
{
if (TypeManager.IsGenericParameter (p) && !TypeManager.IsGenericParameter (q))
return q;
if (!TypeManager.IsGenericParameter (p) && TypeManager.IsGenericParameter (q))
return p;
var ac_p = p as ArrayContainer;
if (ac_p != null) {
var ac_q = q as ArrayContainer;
if (ac_q == null)
return null;
TypeSpec specific = MoreSpecific (ac_p.Element, ac_q.Element);
if (specific == ac_p.Element)
return p;
if (specific == ac_q.Element)
return q;
} else if (p.IsGeneric && q.IsGeneric) {
var pargs = TypeManager.GetTypeArguments (p);
var qargs = TypeManager.GetTypeArguments (q);
bool p_specific_at_least_once = false;
bool q_specific_at_least_once = false;
for (int i = 0; i < pargs.Length; i++) {
TypeSpec specific = MoreSpecific (pargs[i], qargs[i]);
if (specific == pargs[i])
p_specific_at_least_once = true;
if (specific == qargs[i])
q_specific_at_least_once = true;
}
if (p_specific_at_least_once && !q_specific_at_least_once)
return p;
if (!p_specific_at_least_once && q_specific_at_least_once)
return q;
}
return null;
}
//
// Find the best method from candidate list
//
public T ResolveMember<T> (ResolveContext rc, ref Arguments args) where T : MemberSpec, IParametersMember
{
List<AmbiguousCandidate> ambiguous_candidates = null;
MemberSpec best_candidate;
Arguments best_candidate_args = null;
bool best_candidate_params = false;
bool best_candidate_dynamic = false;
int best_candidate_rate;
IParametersMember best_parameter_member = null;
int args_count = args != null ? args.Count : 0;
Arguments candidate_args = args;
bool error_mode = false;
MemberSpec invocable_member = null;
while (true) {
best_candidate = null;
best_candidate_rate = int.MaxValue;
var type_members = members;
do {
for (int i = 0; i < type_members.Count; ++i) {
var member = type_members[i];
//
// Methods in a base class are not candidates if any method in a derived
// class is applicable
//
if ((member.Modifiers & Modifiers.OVERRIDE) != 0)
continue;
if (!error_mode) {
if (!member.IsAccessible (rc))
continue;
if (rc.IsRuntimeBinder && !member.DeclaringType.IsAccessible (rc))
continue;
if ((member.Modifiers & (Modifiers.PROTECTED | Modifiers.STATIC)) == Modifiers.PROTECTED &&
instance_qualifier != null && !instance_qualifier.CheckProtectedMemberAccess (rc, member)) {
continue;
}
}
IParametersMember pm = member as IParametersMember;
if (pm == null) {
//
// Will use it later to report ambiguity between best method and invocable member
//
if (Invocation.IsMemberInvocable (member))
invocable_member = member;
continue;
}
//
// Overload resolution is looking for base member but using parameter names
// and default values from the closest member. That means to do expensive lookup
// for the closest override for virtual or abstract members
//
if ((member.Modifiers & (Modifiers.VIRTUAL | Modifiers.ABSTRACT)) != 0) {
var override_params = base_provider.GetOverrideMemberParameters (member);
if (override_params != null)
pm = override_params;
}
//
// Check if the member candidate is applicable
//
bool params_expanded_form = false;
bool dynamic_argument = false;
TypeSpec rt = pm.MemberType;
int candidate_rate = IsApplicable (rc, ref candidate_args, args_count, ref member, pm, ref params_expanded_form, ref dynamic_argument, ref rt);
if (lambda_conv_msgs != null)
lambda_conv_msgs.EndSession ();
//
// How does it score compare to others
//
if (candidate_rate < best_candidate_rate) {
// Fatal error (missing dependency), cannot continue
if (candidate_rate < 0)
return null;
best_candidate_rate = candidate_rate;
best_candidate = member;
best_candidate_args = candidate_args;
best_candidate_params = params_expanded_form;
best_candidate_dynamic = dynamic_argument;
best_parameter_member = pm;
best_candidate_return_type = rt;
} else if (candidate_rate == 0) {
//
// The member look is done per type for most operations but sometimes
// it's not possible like for binary operators overload because they
// are unioned between 2 sides
//
if ((restrictions & Restrictions.BaseMembersIncluded) != 0) {
if (TypeSpec.IsBaseClass (best_candidate.DeclaringType, member.DeclaringType, true))
continue;
}
bool is_better;
if (best_candidate.DeclaringType.IsInterface && member.DeclaringType.ImplementsInterface (best_candidate.DeclaringType, false)) {
//
// We pack all interface members into top level type which makes the overload resolution
// more complicated for interfaces. We compensate it by removing methods with same
// signature when building the cache hence this path should not really be hit often
//
// Example:
// interface IA { void Foo (int arg); }
// interface IB : IA { void Foo (params int[] args); }
//
// IB::Foo is the best overload when calling IB.Foo (1)
//
is_better = true;
if (ambiguous_candidates != null) {
foreach (var amb_cand in ambiguous_candidates) {
if (member.DeclaringType.ImplementsInterface (best_candidate.DeclaringType, false)) {
continue;
}
is_better = false;
break;
}
if (is_better)
ambiguous_candidates = null;
}
} else {
// Is the new candidate better
is_better = BetterFunction (rc, candidate_args, member, pm.Parameters, params_expanded_form, best_candidate, best_parameter_member.Parameters, best_candidate_params);
}
if (is_better) {
best_candidate = member;
best_candidate_args = candidate_args;
best_candidate_params = params_expanded_form;
best_candidate_dynamic = dynamic_argument;
best_parameter_member = pm;
best_candidate_return_type = rt;
} else {
// It's not better but any other found later could be but we are not sure yet
if (ambiguous_candidates == null)
ambiguous_candidates = new List<AmbiguousCandidate> ();
ambiguous_candidates.Add (new AmbiguousCandidate (member, pm.Parameters, params_expanded_form));
}
}
// Restore expanded arguments
if (candidate_args != args)
candidate_args = args;
}
} while (best_candidate_rate != 0 && (type_members = base_provider.GetBaseMembers (type_members[0].DeclaringType.BaseType)) != null);
//
// We've found exact match
//
if (best_candidate_rate == 0)
break;
//
// Try extension methods lookup when no ordinary method match was found and provider enables it
//
if (!error_mode) {
var emg = base_provider.LookupExtensionMethod (rc);
if (emg != null) {
emg = emg.OverloadResolve (rc, ref args, null, restrictions);
if (emg != null) {
best_candidate_extension_group = emg;
return (T) (MemberSpec) emg.BestCandidate;
}
}
}
// Don't run expensive error reporting mode for probing
if (IsProbingOnly)
return null;
if (error_mode)
break;
if (lambda_conv_msgs != null && !lambda_conv_msgs.IsEmpty)
break;
lambda_conv_msgs = null;
error_mode = true;
}
//
// No best member match found, report an error
//
if (best_candidate_rate != 0 || error_mode) {
ReportOverloadError (rc, best_candidate, best_parameter_member, best_candidate_args, best_candidate_params);
return null;
}
if (best_candidate_dynamic) {
if (args[0].ArgType == Argument.AType.ExtensionType) {
rc.Report.Error (1973, loc,
"Type `{0}' does not contain a member `{1}' and the best extension method overload `{2}' cannot be dynamically dispatched. Consider calling the method without the extension method syntax",
args [0].Type.GetSignatureForError (), best_candidate.Name, best_candidate.GetSignatureForError ());
}
//
// Check type constraints only when explicit type arguments are used
//
if (best_candidate.IsGeneric && type_arguments != null) {
MethodSpec bc = best_candidate as MethodSpec;
if (bc != null && TypeParameterSpec.HasAnyTypeParameterConstrained (bc.GenericDefinition)) {
ConstraintChecker cc = new ConstraintChecker (rc);
cc.CheckAll (bc.GetGenericMethodDefinition (), bc.TypeArguments, bc.Constraints, loc);
}
}
BestCandidateIsDynamic = true;
return null;
}
//
// These flags indicates we are running delegate probing conversion. No need to
// do more expensive checks
//
if ((restrictions & (Restrictions.ProbingOnly | Restrictions.CovariantDelegate)) == (Restrictions.CovariantDelegate | Restrictions.ProbingOnly))
return (T) best_candidate;
if (ambiguous_candidates != null) {
//
// Now check that there are no ambiguities i.e the selected method
// should be better than all the others
//
for (int ix = 0; ix < ambiguous_candidates.Count; ix++) {
var candidate = ambiguous_candidates [ix];
if (!BetterFunction (rc, best_candidate_args, best_candidate, best_parameter_member.Parameters, best_candidate_params, candidate.Member, candidate.Parameters, candidate.Expanded)) {
var ambiguous = candidate.Member;
if (custom_errors == null || !custom_errors.AmbiguousCandidates (rc, best_candidate, ambiguous)) {
rc.Report.SymbolRelatedToPreviousError (best_candidate);
rc.Report.SymbolRelatedToPreviousError (ambiguous);
rc.Report.Error (121, loc, "The call is ambiguous between the following methods or properties: `{0}' and `{1}'",
best_candidate.GetSignatureForError (), ambiguous.GetSignatureForError ());
}
return (T) best_candidate;
}
}
}
if (invocable_member != null && !IsProbingOnly) {
rc.Report.SymbolRelatedToPreviousError (best_candidate);
rc.Report.SymbolRelatedToPreviousError (invocable_member);
rc.Report.Warning (467, 2, loc, "Ambiguity between method `{0}' and invocable non-method `{1}'. Using method group",
best_candidate.GetSignatureForError (), invocable_member.GetSignatureForError ());
}
//
// And now check if the arguments are all
// compatible, perform conversions if
// necessary etc. and return if everything is
// all right
//
if (!VerifyArguments (rc, ref best_candidate_args, best_candidate, best_parameter_member, best_candidate_params))
return null;
if (best_candidate == null)
return null;
//
// Don't run possibly expensive checks in probing mode
//
if (!IsProbingOnly && !rc.IsInProbingMode) {
//
// Check ObsoleteAttribute on the best method
//
ObsoleteAttribute oa = best_candidate.GetAttributeObsolete ();
if (oa != null && !rc.IsObsolete)
AttributeTester.Report_ObsoleteMessage (oa, best_candidate.GetSignatureForError (), loc, rc.Report);
best_candidate.MemberDefinition.SetIsUsed ();
}
args = best_candidate_args;
return (T) best_candidate;
}
public MethodSpec ResolveOperator (ResolveContext rc, ref Arguments args)
{
return ResolveMember<MethodSpec> (rc, ref args);
}
void ReportArgumentMismatch (ResolveContext ec, int idx, MemberSpec method,
Argument a, AParametersCollection expected_par, TypeSpec paramType)
{
if (custom_errors != null && custom_errors.ArgumentMismatch (ec, method, a, idx))
return;
if (a.Type == InternalType.ErrorType)
return;
if (a is CollectionElementInitializer.ElementInitializerArgument) {
ec.Report.SymbolRelatedToPreviousError (method);
if ((expected_par.FixedParameters[idx].ModFlags & Parameter.Modifier.RefOutMask) != 0) {
ec.Report.Error (1954, loc, "The best overloaded collection initalizer method `{0}' cannot have `ref' or `out' modifier",
TypeManager.CSharpSignature (method));
return;
}
ec.Report.Error (1950, loc, "The best overloaded collection initalizer method `{0}' has some invalid arguments",
TypeManager.CSharpSignature (method));
} else if (IsDelegateInvoke) {
ec.Report.Error (1594, loc, "Delegate `{0}' has some invalid arguments",
DelegateType.GetSignatureForError ());
} else {
ec.Report.SymbolRelatedToPreviousError (method);
ec.Report.Error (1502, loc, "The best overloaded method match for `{0}' has some invalid arguments",
method.GetSignatureForError ());
}
Parameter.Modifier mod = idx >= expected_par.Count ? 0 : expected_par.FixedParameters[idx].ModFlags;
string index = (idx + 1).ToString ();
if (((mod & Parameter.Modifier.RefOutMask) ^ (a.Modifier & Parameter.Modifier.RefOutMask)) != 0) {
if ((mod & Parameter.Modifier.RefOutMask) == 0)
ec.Report.Error (1615, a.Expr.Location, "Argument `#{0}' does not require `{1}' modifier. Consider removing `{1}' modifier",
index, Parameter.GetModifierSignature (a.Modifier));
else
ec.Report.Error (1620, a.Expr.Location, "Argument `#{0}' is missing `{1}' modifier",
index, Parameter.GetModifierSignature (mod));
} else {
string p1 = a.GetSignatureForError ();
string p2 = paramType.GetSignatureForError ();
if (p1 == p2) {
p1 = a.Type.GetSignatureForErrorIncludingAssemblyName ();
p2 = paramType.GetSignatureForErrorIncludingAssemblyName ();
}
if ((mod & Parameter.Modifier.RefOutMask) != 0) {
p1 = Parameter.GetModifierSignature (a.Modifier) + " " + p1;
p2 = Parameter.GetModifierSignature (a.Modifier) + " " + p2;
}
ec.Report.Error (1503, a.Expr.Location,
"Argument `#{0}' cannot convert `{1}' expression to type `{2}'", index, p1, p2);
}
}
//
// We have failed to find exact match so we return error info about the closest match
//
void ReportOverloadError (ResolveContext rc, MemberSpec best_candidate, IParametersMember pm, Arguments args, bool params_expanded)
{
int ta_count = type_arguments == null ? 0 : type_arguments.Count;
int arg_count = args == null ? 0 : args.Count;
if (ta_count != best_candidate.Arity && (ta_count > 0 || ((IParametersMember) best_candidate).Parameters.IsEmpty)) {
var mg = new MethodGroupExpr (new [] { best_candidate }, best_candidate.DeclaringType, loc);
mg.Error_TypeArgumentsCannotBeUsed (rc, best_candidate, ta_count, loc);
return;
}
if (lambda_conv_msgs != null && lambda_conv_msgs.Merge (rc.Report.Printer)) {
return;
}
if ((best_candidate.Modifiers & (Modifiers.PROTECTED | Modifiers.STATIC)) == Modifiers.PROTECTED &&
InstanceQualifier != null && !InstanceQualifier.CheckProtectedMemberAccess (rc, best_candidate)) {
MemberExpr.Error_ProtectedMemberAccess (rc, best_candidate, InstanceQualifier.InstanceType, loc);
}
//
// For candidates which match on parameters count report more details about incorrect arguments
//
if (pm != null) {
int unexpanded_count = ((IParametersMember) best_candidate).Parameters.HasParams ? pm.Parameters.Count - 1 : pm.Parameters.Count;
if (pm.Parameters.Count == arg_count || params_expanded || unexpanded_count == arg_count) {
// Reject any inaccessible member
if (!best_candidate.IsAccessible (rc) || !best_candidate.DeclaringType.IsAccessible (rc)) {
rc.Report.SymbolRelatedToPreviousError (best_candidate);
Expression.ErrorIsInaccesible (rc, best_candidate.GetSignatureForError (), loc);
return;
}
var ms = best_candidate as MethodSpec;
if (ms != null && ms.IsGeneric) {
bool constr_ok = true;
if (ms.TypeArguments != null)
constr_ok = new ConstraintChecker (rc.MemberContext).CheckAll (ms.GetGenericMethodDefinition (), ms.TypeArguments, ms.Constraints, loc);
if (ta_count == 0) {
if (custom_errors != null && custom_errors.TypeInferenceFailed (rc, best_candidate))
return;
if (constr_ok) {
rc.Report.Error (411, loc,
"The type arguments for method `{0}' cannot be inferred from the usage. Try specifying the type arguments explicitly",
ms.GetGenericMethodDefinition ().GetSignatureForError ());
}
return;
}
}
VerifyArguments (rc, ref args, best_candidate, pm, params_expanded);
return;
}
}
//
// We failed to find any method with correct argument count, report best candidate
//
if (custom_errors != null && custom_errors.NoArgumentMatch (rc, best_candidate))
return;
if (best_candidate.Kind == MemberKind.Constructor) {
rc.Report.SymbolRelatedToPreviousError (best_candidate);
Error_ConstructorMismatch (rc, best_candidate.DeclaringType, arg_count, loc);
} else if (IsDelegateInvoke) {
rc.Report.SymbolRelatedToPreviousError (DelegateType);
rc.Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
DelegateType.GetSignatureForError (), arg_count.ToString ());
} else {
string name = best_candidate.Kind == MemberKind.Indexer ? "this" : best_candidate.Name;
rc.Report.SymbolRelatedToPreviousError (best_candidate);
rc.Report.Error (1501, loc, "No overload for method `{0}' takes `{1}' arguments",
name, arg_count.ToString ());
}
}
bool VerifyArguments (ResolveContext ec, ref Arguments args, MemberSpec member, IParametersMember pm, bool chose_params_expanded)
{
var pd = pm.Parameters;
TypeSpec[] ptypes = ((IParametersMember) member).Parameters.Types;
Parameter.Modifier p_mod = 0;
TypeSpec pt = null;
int a_idx = 0, a_pos = 0;
Argument a = null;
ArrayInitializer params_initializers = null;
bool has_unsafe_arg = pm.MemberType.IsPointer;
int arg_count = args == null ? 0 : args.Count;
for (; a_idx < arg_count; a_idx++, ++a_pos) {
a = args[a_idx];
if (p_mod != Parameter.Modifier.PARAMS) {
p_mod = pd.FixedParameters[a_idx].ModFlags;
pt = ptypes[a_idx];
has_unsafe_arg |= pt.IsPointer;
if (p_mod == Parameter.Modifier.PARAMS) {
if (chose_params_expanded) {
params_initializers = new ArrayInitializer (arg_count - a_idx, a.Expr.Location);
pt = TypeManager.GetElementType (pt);
}
}
}
//
// Types have to be identical when ref or out modifer is used
//
if (((a.Modifier | p_mod) & Parameter.Modifier.RefOutMask) != 0) {
if ((a.Modifier & Parameter.Modifier.RefOutMask) != (p_mod & Parameter.Modifier.RefOutMask))
break;
if (a.Expr.Type == pt || TypeSpecComparer.IsEqual (a.Expr.Type, pt))
continue;
break;
}
NamedArgument na = a as NamedArgument;
if (na != null) {
int name_index = pd.GetParameterIndexByName (na.Name);
if (name_index < 0 || name_index >= pd.Count) {
if (IsDelegateInvoke) {
ec.Report.SymbolRelatedToPreviousError (DelegateType);
ec.Report.Error (1746, na.Location,
"The delegate `{0}' does not contain a parameter named `{1}'",
DelegateType.GetSignatureForError (), na.Name);
} else {
ec.Report.SymbolRelatedToPreviousError (member);
ec.Report.Error (1739, na.Location,
"The best overloaded method match for `{0}' does not contain a parameter named `{1}'",
TypeManager.CSharpSignature (member), na.Name);
}
} else if (args[name_index] != a) {
if (IsDelegateInvoke)
ec.Report.SymbolRelatedToPreviousError (DelegateType);
else
ec.Report.SymbolRelatedToPreviousError (member);
ec.Report.Error (1744, na.Location,
"Named argument `{0}' cannot be used for a parameter which has positional argument specified",
na.Name);
}
}
if (a.Expr.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic)
continue;
if ((restrictions & Restrictions.CovariantDelegate) != 0 && !Delegate.IsTypeCovariant (ec, a.Expr.Type, pt)) {
custom_errors.NoArgumentMatch (ec, member);
return false;
}
Expression conv = null;
if (a.ArgType == Argument.AType.ExtensionType) {
if (a.Expr.Type == pt || TypeSpecComparer.IsEqual (a.Expr.Type, pt)) {
conv = a.Expr;
} else {
conv = Convert.ImplicitReferenceConversion (a.Expr, pt, false);
if (conv == null)
conv = Convert.ImplicitBoxingConversion (a.Expr, a.Expr.Type, pt);
}
} else {
conv = Convert.ImplicitConversion (ec, a.Expr, pt, loc);
}
if (conv == null)
break;
//
// Convert params arguments to an array initializer
//
if (params_initializers != null) {
// we choose to use 'a.Expr' rather than 'conv' so that
// we don't hide the kind of expression we have (esp. CompoundAssign.Helper)
params_initializers.Add (a.Expr);
args.RemoveAt (a_idx--);
--arg_count;
continue;
}
// Update the argument with the implicit conversion
a.Expr = conv;
}
if (a_idx != arg_count) {
ReportArgumentMismatch (ec, a_pos, member, a, pd, pt);
return false;
}
//
// Fill not provided arguments required by params modifier
//
if (params_initializers == null && pd.HasParams && arg_count + 1 == pd.Count) {
if (args == null)
args = new Arguments (1);
pt = ptypes[pd.Count - 1];
pt = TypeManager.GetElementType (pt);
has_unsafe_arg |= pt.IsPointer;
params_initializers = new ArrayInitializer (0, loc);
}
//
// Append an array argument with all params arguments
//
if (params_initializers != null) {
args.Add (new Argument (
new ArrayCreation (new TypeExpression (pt, loc), params_initializers, loc).Resolve (ec)));
arg_count++;
}
if (has_unsafe_arg && !ec.IsUnsafe) {
Expression.UnsafeError (ec, loc);
}
//
// We could infer inaccesible type arguments
//
if (type_arguments == null && member.IsGeneric) {
var ms = (MethodSpec) member;
foreach (var ta in ms.TypeArguments) {
if (!ta.IsAccessible (ec)) {
ec.Report.SymbolRelatedToPreviousError (ta);
Expression.ErrorIsInaccesible (ec, member.GetSignatureForError (), loc);
break;
}
}
}
return true;
}
}
public class ConstantExpr : MemberExpr
{
readonly ConstSpec constant;
public ConstantExpr (ConstSpec constant, Location loc)
{
this.constant = constant;
this.loc = loc;
}
public override string Name {
get { throw new NotImplementedException (); }
}
public override string KindName {
get { return "constant"; }
}
public override bool IsInstance {
get { return !IsStatic; }
}
public override bool IsStatic {
get { return true; }
}
protected override TypeSpec DeclaringType {
get { return constant.DeclaringType; }
}
public override Expression CreateExpressionTree (ResolveContext ec)
{
throw new NotSupportedException ("ET");
}
protected override Expression DoResolve (ResolveContext rc)
{
ResolveInstanceExpression (rc, null);
DoBestMemberChecks (rc, constant);
var c = constant.GetConstant (rc);
// Creates reference expression to the constant value
return Constant.CreateConstantFromValue (constant.MemberType, c.GetValue (), loc);
}
public override void Emit (EmitContext ec)
{
throw new NotSupportedException ();
}
public override string GetSignatureForError ()
{
return constant.GetSignatureForError ();
}
public override void SetTypeArguments (ResolveContext ec, TypeArguments ta)
{
Error_TypeArgumentsCannotBeUsed (ec, "constant", GetSignatureForError (), loc);
}
}
//
// Fully resolved expression that references a Field
//
public class FieldExpr : MemberExpr, IDynamicAssign, IMemoryLocation, IVariableReference
{
protected FieldSpec spec;
VariableInfo variable_info;
LocalTemporary temp;
bool prepared;
protected FieldExpr (Location l)
{
loc = l;
}
public FieldExpr (FieldSpec spec, Location loc)
{
this.spec = spec;
this.loc = loc;
type = spec.MemberType;
}
public FieldExpr (FieldBase fi, Location l)
: this (fi.Spec, l)
{
}
#region Properties
public override string Name {
get {
return spec.Name;
}
}
public bool IsHoisted {
get {
IVariableReference hv = InstanceExpression as IVariableReference;
return hv != null && hv.IsHoisted;
}
}
public override bool IsInstance {
get {
return !spec.IsStatic;
}
}
public override bool IsStatic {
get {
return spec.IsStatic;
}
}
public override string KindName {
get { return "field"; }
}
public FieldSpec Spec {
get {
return spec;
}
}
protected override TypeSpec DeclaringType {
get {
return spec.DeclaringType;
}
}
public VariableInfo VariableInfo {
get {
return variable_info;
}
}
#endregion
public override string GetSignatureForError ()
{
return spec.GetSignatureForError ();
}
public bool IsMarshalByRefAccess (ResolveContext rc)
{
// Checks possible ldflda of field access expression
return !spec.IsStatic && TypeSpec.IsValueType (spec.MemberType) && !(InstanceExpression is This) &&
rc.Module.PredefinedTypes.MarshalByRefObject.Define () &&
TypeSpec.IsBaseClass (spec.DeclaringType, rc.Module.PredefinedTypes.MarshalByRefObject.TypeSpec, false);
}
public void SetHasAddressTaken ()
{
IVariableReference vr = InstanceExpression as IVariableReference;
if (vr != null) {
vr.SetHasAddressTaken ();
}
}
public override Expression CreateExpressionTree (ResolveContext ec)
{
return CreateExpressionTree (ec, true);
}
public Expression CreateExpressionTree (ResolveContext ec, bool convertInstance)
{
Arguments args;
Expression instance;
if (InstanceExpression == null) {
instance = new NullLiteral (loc);
} else if (convertInstance) {
instance = InstanceExpression.CreateExpressionTree (ec);
} else {
args = new Arguments (1);
args.Add (new Argument (InstanceExpression));
instance = CreateExpressionFactoryCall (ec, "Constant", args);
}
args = Arguments.CreateForExpressionTree (ec, null,
instance,
CreateTypeOfExpression ());
return CreateExpressionFactoryCall (ec, "Field", args);
}
public Expression CreateTypeOfExpression ()
{
return new TypeOfField (spec, loc);
}
protected override Expression DoResolve (ResolveContext ec)
{
spec.MemberDefinition.SetIsUsed ();
return DoResolve (ec, null);
}
Expression DoResolve (ResolveContext ec, Expression rhs)
{
bool lvalue_instance = rhs != null && IsInstance && spec.DeclaringType.IsStruct;
if (rhs != this) {
if (ResolveInstanceExpression (ec, rhs)) {
// Resolve the field's instance expression while flow analysis is turned
// off: when accessing a field "a.b", we must check whether the field
// "a.b" is initialized, not whether the whole struct "a" is initialized.
if (lvalue_instance) {
using (ec.With (ResolveContext.Options.DoFlowAnalysis, false)) {
bool out_access = rhs == EmptyExpression.OutAccess || rhs == EmptyExpression.LValueMemberOutAccess;
Expression right_side =
out_access ? EmptyExpression.LValueMemberOutAccess : EmptyExpression.LValueMemberAccess;
InstanceExpression = InstanceExpression.ResolveLValue (ec, right_side);
}
} else {
using (ec.With (ResolveContext.Options.DoFlowAnalysis, false)) {
InstanceExpression = InstanceExpression.Resolve (ec, ResolveFlags.VariableOrValue);
}
}
if (InstanceExpression == null)
return null;
}
DoBestMemberChecks (ec, spec);
}
var fb = spec as FixedFieldSpec;
IVariableReference var = InstanceExpression as IVariableReference;
if (lvalue_instance && var != null && var.VariableInfo != null) {
var.VariableInfo.SetStructFieldAssigned (ec, Name);
}
if (fb != null) {
IFixedExpression fe = InstanceExpression as IFixedExpression;
if (!ec.HasSet (ResolveContext.Options.FixedInitializerScope) && (fe == null || !fe.IsFixed)) {
ec.Report.Error (1666, loc, "You cannot use fixed size buffers contained in unfixed expressions. Try using the fixed statement");
}
if (InstanceExpression.eclass != ExprClass.Variable) {
ec.Report.SymbolRelatedToPreviousError (spec);
ec.Report.Error (1708, loc, "`{0}': Fixed size buffers can only be accessed through locals or fields",
TypeManager.GetFullNameSignature (spec));
} else if (var != null && var.IsHoisted) {
AnonymousMethodExpression.Error_AddressOfCapturedVar (ec, var, loc);
}
return new FixedBufferPtr (this, fb.ElementType, loc).Resolve (ec);
}
//
// Set flow-analysis variable info for struct member access. It will be check later
// for precise error reporting
//
if (var != null && var.VariableInfo != null && InstanceExpression.Type.IsStruct) {
variable_info = var.VariableInfo.GetStructFieldInfo (Name);
if (rhs != null && variable_info != null)
variable_info.SetStructFieldAssigned (ec, Name);
}
eclass = ExprClass.Variable;
return this;
}
public void VerifyAssignedStructField (ResolveContext rc, Expression rhs)
{
var fe = this;
do {
var var = fe.InstanceExpression as IVariableReference;
if (var != null) {
var vi = var.VariableInfo;
if (vi != null && !vi.IsStructFieldAssigned (rc, fe.Name) && (rhs == null || !fe.type.IsStruct)) {
if (rhs != null) {
rc.Report.Warning (1060, 1, fe.loc, "Use of possibly unassigned field `{0}'", fe.Name);
} else {
rc.Report.Error (170, fe.loc, "Use of possibly unassigned field `{0}'", fe.Name);
}
return;
}
}
fe = fe.InstanceExpression as FieldExpr;
} while (fe != null);
}
static readonly int [] codes = {
191, // instance, write access
192, // instance, out access
198, // static, write access
199, // static, out access
1648, // member of value instance, write access
1649, // member of value instance, out access
1650, // member of value static, write access
1651 // member of value static, out access
};
static readonly string [] msgs = {
/*0191*/ "A readonly field `{0}' cannot be assigned to (except in a constructor or a variable initializer)",
/*0192*/ "A readonly field `{0}' cannot be passed ref or out (except in a constructor)",
/*0198*/ "A static readonly field `{0}' cannot be assigned to (except in a static constructor or a variable initializer)",
/*0199*/ "A static readonly field `{0}' cannot be passed ref or out (except in a static constructor)",
/*1648*/ "Members of readonly field `{0}' cannot be modified (except in a constructor or a variable initializer)",
/*1649*/ "Members of readonly field `{0}' cannot be passed ref or out (except in a constructor)",
/*1650*/ "Fields of static readonly field `{0}' cannot be assigned to (except in a static constructor or a variable initializer)",
/*1651*/ "Fields of static readonly field `{0}' cannot be passed ref or out (except in a static constructor)"
};
// The return value is always null. Returning a value simplifies calling code.
Expression Report_AssignToReadonly (ResolveContext ec, Expression right_side)
{
int i = 0;
if (right_side == EmptyExpression.OutAccess || right_side == EmptyExpression.LValueMemberOutAccess)
i += 1;
if (IsStatic)
i += 2;
if (right_side == EmptyExpression.LValueMemberAccess || right_side == EmptyExpression.LValueMemberOutAccess)
i += 4;
ec.Report.Error (codes [i], loc, msgs [i], GetSignatureForError ());
return null;
}
override public Expression DoResolveLValue (ResolveContext ec, Expression right_side)
{
if (spec is FixedFieldSpec) {
// It could be much better error message but we want to be error compatible
Error_ValueAssignment (ec, right_side);
}
Expression e = DoResolve (ec, right_side);
if (e == null)
return null;
spec.MemberDefinition.SetIsAssigned ();
if ((right_side == EmptyExpression.UnaryAddress || right_side == EmptyExpression.OutAccess) &&
(spec.Modifiers & Modifiers.VOLATILE) != 0) {
ec.Report.Warning (420, 1, loc,
"`{0}': A volatile field references will not be treated as volatile",
spec.GetSignatureForError ());
}
if (spec.IsReadOnly) {
// InitOnly fields can only be assigned in constructors or initializers
if (!ec.HasAny (ResolveContext.Options.FieldInitializerScope | ResolveContext.Options.ConstructorScope))
return Report_AssignToReadonly (ec, right_side);
if (ec.HasSet (ResolveContext.Options.ConstructorScope)) {
// InitOnly fields cannot be assigned-to in a different constructor from their declaring type
if (ec.CurrentMemberDefinition.Parent.PartialContainer.Definition != spec.DeclaringType.GetDefinition ())
return Report_AssignToReadonly (ec, right_side);
// static InitOnly fields cannot be assigned-to in an instance constructor
if (IsStatic && !ec.IsStatic)
return Report_AssignToReadonly (ec, right_side);
// instance constructors can't modify InitOnly fields of other instances of the same type
if (!IsStatic && !(InstanceExpression is This))
return Report_AssignToReadonly (ec, right_side);
}
}
if (right_side == EmptyExpression.OutAccess && IsMarshalByRefAccess (ec)) {
ec.Report.SymbolRelatedToPreviousError (spec.DeclaringType);
ec.Report.Warning (197, 1, loc,
"Passing `{0}' as ref or out or taking its address may cause a runtime exception because it is a field of a marshal-by-reference class",
GetSignatureForError ());
}
eclass = ExprClass.Variable;
return this;
}
public override int GetHashCode ()
{
return spec.GetHashCode ();
}
public bool IsFixed {
get {
//
// A variable of the form V.I is fixed when V is a fixed variable of a struct type
//
IVariableReference variable = InstanceExpression as IVariableReference;
if (variable != null)
return InstanceExpression.Type.IsStruct && variable.IsFixed;
IFixedExpression fe = InstanceExpression as IFixedExpression;
return fe != null && fe.IsFixed;
}
}
public override bool Equals (object obj)
{
FieldExpr fe = obj as FieldExpr;
if (fe == null)
return false;
if (spec != fe.spec)
return false;
if (InstanceExpression == null || fe.InstanceExpression == null)
return true;
return InstanceExpression.Equals (fe.InstanceExpression);
}
public void Emit (EmitContext ec, bool leave_copy)
{
bool is_volatile = (spec.Modifiers & Modifiers.VOLATILE) != 0;
if (IsStatic){
if (is_volatile)
ec.Emit (OpCodes.Volatile);
ec.Emit (OpCodes.Ldsfld, spec);
} else {
if (!prepared)
EmitInstance (ec, false);
// Optimization for build-in types
if (type.IsStruct && type == ec.CurrentType && InstanceExpression.Type == type) {
ec.EmitLoadFromPtr (type);
} else {
var ff = spec as FixedFieldSpec;
if (ff != null) {
ec.Emit (OpCodes.Ldflda, spec);
ec.Emit (OpCodes.Ldflda, ff.Element);
} else {
if (is_volatile)
ec.Emit (OpCodes.Volatile);
ec.Emit (OpCodes.Ldfld, spec);
}
}
}
if (leave_copy) {
ec.Emit (OpCodes.Dup);
if (!IsStatic) {
temp = new LocalTemporary (this.Type);
temp.Store (ec);
}
}
}
public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound)
{
bool has_await_source = ec.HasSet (BuilderContext.Options.AsyncBody) && source.ContainsEmitWithAwait ();
if (isCompound && !(source is DynamicExpressionStatement)) {
if (has_await_source) {
if (IsInstance)
InstanceExpression = InstanceExpression.EmitToField (ec);
} else {
prepared = true;
}
}
if (IsInstance) {
if (has_await_source)
source = source.EmitToField (ec);
EmitInstance (ec, prepared);
}
source.Emit (ec);
if (leave_copy) {
ec.Emit (OpCodes.Dup);
if (!IsStatic) {
temp = new LocalTemporary (this.Type);
temp.Store (ec);
}
}
if ((spec.Modifiers & Modifiers.VOLATILE) != 0)
ec.Emit (OpCodes.Volatile);
spec.MemberDefinition.SetIsAssigned ();
if (IsStatic)
ec.Emit (OpCodes.Stsfld, spec);
else
ec.Emit (OpCodes.Stfld, spec);
if (temp != null) {
temp.Emit (ec);
temp.Release (ec);
temp = null;
}
}
//
// Emits store to field with prepared values on stack
//
public void EmitAssignFromStack (EmitContext ec)
{
if (IsStatic) {
ec.Emit (OpCodes.Stsfld, spec);
} else {
ec.Emit (OpCodes.Stfld, spec);
}
}
public override void Emit (EmitContext ec)
{
Emit (ec, false);
}
public override void EmitSideEffect (EmitContext ec)
{
bool is_volatile = (spec.Modifiers & Modifiers.VOLATILE) != 0;
if (is_volatile) // || is_marshal_by_ref ())
base.EmitSideEffect (ec);
}
public virtual void AddressOf (EmitContext ec, AddressOp mode)
{
if ((mode & AddressOp.Store) != 0)
spec.MemberDefinition.SetIsAssigned ();
if ((mode & AddressOp.Load) != 0)
spec.MemberDefinition.SetIsUsed ();
//
// Handle initonly fields specially: make a copy and then
// get the address of the copy.
//
bool need_copy;
if (spec.IsReadOnly){
need_copy = true;
if (ec.HasSet (EmitContext.Options.ConstructorScope) && spec.DeclaringType == ec.CurrentType) {
if (IsStatic){
if (ec.IsStatic)
need_copy = false;
} else
need_copy = false;
}
} else
need_copy = false;
if (need_copy) {
Emit (ec);
var temp = ec.GetTemporaryLocal (type);
ec.Emit (OpCodes.Stloc, temp);
ec.Emit (OpCodes.Ldloca, temp);
ec.FreeTemporaryLocal (temp, type);
return;
}
if (IsStatic){
ec.Emit (OpCodes.Ldsflda, spec);
} else {
if (!prepared)
EmitInstance (ec, false);
ec.Emit (OpCodes.Ldflda, spec);
}
}
public SLE.Expression MakeAssignExpression (BuilderContext ctx, Expression source)
{
return MakeExpression (ctx);
}
public override SLE.Expression MakeExpression (BuilderContext ctx)
{
#if STATIC
return base.MakeExpression (ctx);
#else
return SLE.Expression.Field (
IsStatic ? null : InstanceExpression.MakeExpression (ctx),
spec.GetMetaInfo ());
#endif
}
public override void SetTypeArguments (ResolveContext ec, TypeArguments ta)
{
Error_TypeArgumentsCannotBeUsed (ec, "field", GetSignatureForError (), loc);
}
}
//
// Expression that evaluates to a Property.
//
// This is not an LValue because we need to re-write the expression. We
// can not take data from the stack and store it.
//
sealed class PropertyExpr : PropertyOrIndexerExpr<PropertySpec>
{
Arguments arguments;
public PropertyExpr (PropertySpec spec, Location l)
: base (l)
{
best_candidate = spec;
type = spec.MemberType;
}
#region Properties
protected override Arguments Arguments {
get {
return arguments;
}
set {
arguments = value;
}
}
protected override TypeSpec DeclaringType {
get {
return best_candidate.DeclaringType;
}
}
public override string Name {
get {
return best_candidate.Name;
}
}
public override bool IsInstance {
get {
return !IsStatic;
}
}
public override bool IsStatic {
get {
return best_candidate.IsStatic;
}
}
public override string KindName {
get { return "property"; }
}
public PropertySpec PropertyInfo {
get {
return best_candidate;
}
}
#endregion
public override MethodGroupExpr CanReduceLambda (AnonymousMethodBody body)
{
if (best_candidate == null || !(best_candidate.IsStatic || InstanceExpression is This))
return null;
var args_count = arguments == null ? 0 : arguments.Count;
if (args_count != body.Parameters.Count && args_count == 0)
return null;
var mg = MethodGroupExpr.CreatePredefined (best_candidate.Get, DeclaringType, loc);
mg.InstanceExpression = InstanceExpression;
return mg;
}
public static PropertyExpr CreatePredefined (PropertySpec spec, Location loc)
{
return new PropertyExpr (spec, loc) {
Getter = spec.Get,
Setter = spec.Set
};
}
public override Expression CreateExpressionTree (ResolveContext ec)
{
Arguments args;
if (IsSingleDimensionalArrayLength ()) {
args = new Arguments (1);
args.Add (new Argument (InstanceExpression.CreateExpressionTree (ec)));
return CreateExpressionFactoryCall (ec, "ArrayLength", args);
}
args = new Arguments (2);
if (InstanceExpression == null)
args.Add (new Argument (new NullLiteral (loc)));
else
args.Add (new Argument (InstanceExpression.CreateExpressionTree (ec)));
args.Add (new Argument (new TypeOfMethod (Getter, loc)));
return CreateExpressionFactoryCall (ec, "Property", args);
}
public Expression CreateSetterTypeOfExpression (ResolveContext rc)
{
DoResolveLValue (rc, null);
return new TypeOfMethod (Setter, loc);
}
public override string GetSignatureForError ()
{
return best_candidate.GetSignatureForError ();
}
public override SLE.Expression MakeAssignExpression (BuilderContext ctx, Expression source)
{
#if STATIC
return base.MakeExpression (ctx);
#else
return SLE.Expression.Property (InstanceExpression.MakeExpression (ctx), (MethodInfo) Setter.GetMetaInfo ());
#endif
}
public override SLE.Expression MakeExpression (BuilderContext ctx)
{
#if STATIC
return base.MakeExpression (ctx);
#else
return SLE.Expression.Property (InstanceExpression.MakeExpression (ctx), (MethodInfo) Getter.GetMetaInfo ());
#endif
}
void Error_PropertyNotValid (ResolveContext ec)
{
ec.Report.SymbolRelatedToPreviousError (best_candidate);
ec.Report.Error (1546, loc, "Property or event `{0}' is not supported by the C# language",
GetSignatureForError ());
}
bool IsSingleDimensionalArrayLength ()
{
if (best_candidate.DeclaringType.BuiltinType != BuiltinTypeSpec.Type.Array || !best_candidate.HasGet || Name != "Length")
return false;
ArrayContainer ac = InstanceExpression.Type as ArrayContainer;
return ac != null && ac.Rank == 1;
}
public override void Emit (EmitContext ec, bool leave_copy)
{
//
// Special case: length of single dimension array property is turned into ldlen
//
if (IsSingleDimensionalArrayLength ()) {
EmitInstance (ec, false);
ec.Emit (OpCodes.Ldlen);
ec.Emit (OpCodes.Conv_I4);
return;
}
base.Emit (ec, leave_copy);
}
public override void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound)
{
Arguments args;
LocalTemporary await_source_arg = null;
if (isCompound && !(source is DynamicExpressionStatement)) {
emitting_compound_assignment = true;
source.Emit (ec);
if (has_await_arguments) {
await_source_arg = new LocalTemporary (Type);
await_source_arg.Store (ec);
args = new Arguments (1);
args.Add (new Argument (await_source_arg));
if (leave_copy) {
temp = await_source_arg;
}
has_await_arguments = false;
} else {
args = null;
if (leave_copy) {
ec.Emit (OpCodes.Dup);
temp = new LocalTemporary (this.Type);
temp.Store (ec);
}
}
} else {
args = arguments == null ? new Arguments (1) : arguments;
if (leave_copy) {
source.Emit (ec);
temp = new LocalTemporary (this.Type);
temp.Store (ec);
args.Add (new Argument (temp));
} else {
args.Add (new Argument (source));
}
}
emitting_compound_assignment = false;
var call = new CallEmitter ();
call.InstanceExpression = InstanceExpression;
if (args == null)
call.InstanceExpressionOnStack = true;
call.Emit (ec, Setter, args, loc);
if (temp != null) {
temp.Emit (ec);
temp.Release (ec);
}
if (await_source_arg != null) {
await_source_arg.Release (ec);
}
}
protected override Expression OverloadResolve (ResolveContext rc, Expression right_side)
{
eclass = ExprClass.PropertyAccess;
if (best_candidate.IsNotCSharpCompatible) {
Error_PropertyNotValid (rc);
}
ResolveInstanceExpression (rc, right_side);
if ((best_candidate.Modifiers & (Modifiers.ABSTRACT | Modifiers.VIRTUAL)) != 0 && best_candidate.DeclaringType != InstanceExpression.Type) {
var filter = new MemberFilter (best_candidate.Name, 0, MemberKind.Property, null, null);
var p = MemberCache.FindMember (InstanceExpression.Type, filter, BindingRestriction.InstanceOnly | BindingRestriction.OverrideOnly) as PropertySpec;
if (p != null) {
type = p.MemberType;
}
}
DoBestMemberChecks (rc, best_candidate);
// Handling of com-imported properties with any number of default property parameters
if (best_candidate.HasGet && !best_candidate.Get.Parameters.IsEmpty) {
var p = best_candidate.Get.Parameters;
arguments = new Arguments (p.Count);
for (int i = 0; i < p.Count; ++i) {
arguments.Add (new Argument (OverloadResolver.ResolveDefaultValueArgument (rc, p.Types [i], p.FixedParameters [i].DefaultValue, loc)));
}
} else if (best_candidate.HasSet && best_candidate.Set.Parameters.Count > 1) {
var p = best_candidate.Set.Parameters;
arguments = new Arguments (p.Count - 1);
for (int i = 0; i < p.Count - 1; ++i) {
arguments.Add (new Argument (OverloadResolver.ResolveDefaultValueArgument (rc, p.Types [i], p.FixedParameters [i].DefaultValue, loc)));
}
}
return this;
}
public override void SetTypeArguments (ResolveContext ec, TypeArguments ta)
{
Error_TypeArgumentsCannotBeUsed (ec, "property", GetSignatureForError (), loc);
}
}
abstract class PropertyOrIndexerExpr<T> : MemberExpr, IDynamicAssign where T : PropertySpec
{
// getter and setter can be different for base calls
MethodSpec getter, setter;
protected T best_candidate;
protected LocalTemporary temp;
protected bool emitting_compound_assignment;
protected bool has_await_arguments;
protected PropertyOrIndexerExpr (Location l)
{
loc = l;
}
#region Properties
protected abstract Arguments Arguments { get; set; }
public MethodSpec Getter {
get {
return getter;
}
set {
getter = value;
}
}
public MethodSpec Setter {
get {
return setter;
}
set {
setter = value;
}
}
#endregion
protected override Expression DoResolve (ResolveContext ec)
{
if (eclass == ExprClass.Unresolved) {
var expr = OverloadResolve (ec, null);
if (expr == null)
return null;
if (expr != this)
return expr.Resolve (ec);
}
if (!ResolveGetter (ec))
return null;
return this;
}
public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
{
if (right_side == EmptyExpression.OutAccess) {
// TODO: best_candidate can be null at this point
INamedBlockVariable variable = null;
if (best_candidate != null && ec.CurrentBlock.ParametersBlock.TopBlock.GetLocalName (best_candidate.Name, ec.CurrentBlock, ref variable) && variable is Linq.RangeVariable) {
ec.Report.Error (1939, loc, "A range variable `{0}' may not be passes as `ref' or `out' parameter",
best_candidate.Name);
} else {
right_side.DoResolveLValue (ec, this);
}
return null;
}
if (eclass == ExprClass.Unresolved) {
var expr = OverloadResolve (ec, right_side);
if (expr == null)
return null;
if (expr != this)
return expr.ResolveLValue (ec, right_side);
}
if (!ResolveSetter (ec))
return null;
return this;
}
//
// Implements the IAssignMethod interface for assignments
//
public virtual void Emit (EmitContext ec, bool leave_copy)
{
var call = new CallEmitter ();
call.InstanceExpression = InstanceExpression;
if (has_await_arguments)
call.HasAwaitArguments = true;
else
call.DuplicateArguments = emitting_compound_assignment;
call.Emit (ec, Getter, Arguments, loc);
if (call.HasAwaitArguments) {
InstanceExpression = call.InstanceExpression;
Arguments = call.EmittedArguments;
has_await_arguments = true;
}
if (leave_copy) {
ec.Emit (OpCodes.Dup);
temp = new LocalTemporary (Type);
temp.Store (ec);
}
}
public abstract void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound);
public override void Emit (EmitContext ec)
{
Emit (ec, false);
}
protected override FieldExpr EmitToFieldSource (EmitContext ec)
{
has_await_arguments = true;
Emit (ec, false);
return null;
}
public abstract SLE.Expression MakeAssignExpression (BuilderContext ctx, Expression source);
protected abstract Expression OverloadResolve (ResolveContext rc, Expression right_side);
bool ResolveGetter (ResolveContext rc)
{
if (!best_candidate.HasGet) {
if (InstanceExpression != EmptyExpression.Null) {
rc.Report.SymbolRelatedToPreviousError (best_candidate);
rc.Report.Error (154, loc, "The property or indexer `{0}' cannot be used in this context because it lacks the `get' accessor",
best_candidate.GetSignatureForError ());
return false;
}
} else if (!best_candidate.Get.IsAccessible (rc)) {
if (best_candidate.HasDifferentAccessibility) {
rc.Report.SymbolRelatedToPreviousError (best_candidate.Get);
rc.Report.Error (271, loc, "The property or indexer `{0}' cannot be used in this context because the get accessor is inaccessible",
TypeManager.CSharpSignature (best_candidate));
} else {
rc.Report.SymbolRelatedToPreviousError (best_candidate.Get);
ErrorIsInaccesible (rc, best_candidate.Get.GetSignatureForError (), loc);
}
}
if (best_candidate.HasDifferentAccessibility) {
CheckProtectedMemberAccess (rc, best_candidate.Get);
}
getter = CandidateToBaseOverride (rc, best_candidate.Get);
return true;
}
bool ResolveSetter (ResolveContext rc)
{
if (!best_candidate.HasSet) {
rc.Report.Error (200, loc, "Property or indexer `{0}' cannot be assigned to (it is read-only)",
GetSignatureForError ());
return false;
}
if (!best_candidate.Set.IsAccessible (rc)) {
if (best_candidate.HasDifferentAccessibility) {
rc.Report.SymbolRelatedToPreviousError (best_candidate.Set);
rc.Report.Error (272, loc, "The property or indexer `{0}' cannot be used in this context because the set accessor is inaccessible",
GetSignatureForError ());
} else {
rc.Report.SymbolRelatedToPreviousError (best_candidate.Set);
ErrorIsInaccesible (rc, best_candidate.GetSignatureForError (), loc);
}
}
if (best_candidate.HasDifferentAccessibility)
CheckProtectedMemberAccess (rc, best_candidate.Set);
setter = CandidateToBaseOverride (rc, best_candidate.Set);
return true;
}
}
/// <summary>
/// Fully resolved expression that evaluates to an Event
/// </summary>
public class EventExpr : MemberExpr, IAssignMethod
{
readonly EventSpec spec;
MethodSpec op;
public EventExpr (EventSpec spec, Location loc)
{
this.spec = spec;
this.loc = loc;
}
#region Properties
protected override TypeSpec DeclaringType {
get {
return spec.DeclaringType;
}
}
public override string Name {
get {
return spec.Name;
}
}
public override bool IsInstance {
get {
return !spec.IsStatic;
}
}
public override bool IsStatic {
get {
return spec.IsStatic;
}
}
public override string KindName {
get { return "event"; }
}
public MethodSpec Operator {
get {
return op;
}
}
#endregion
public override MemberExpr ResolveMemberAccess (ResolveContext ec, Expression left, SimpleName original)
{
//
// If the event is local to this class and we are not lhs of +=/-= we transform ourselves into a FieldExpr
//
if (!ec.HasSet (ResolveContext.Options.CompoundAssignmentScope)) {
if (spec.BackingField != null &&
(spec.DeclaringType == ec.CurrentType || TypeManager.IsNestedChildOf (ec.CurrentType, spec.DeclaringType.MemberDefinition))) {
spec.MemberDefinition.SetIsUsed ();
if (!ec.IsObsolete) {
ObsoleteAttribute oa = spec.GetAttributeObsolete ();
if (oa != null)
AttributeTester.Report_ObsoleteMessage (oa, spec.GetSignatureForError (), loc, ec.Report);
}
if ((spec.Modifiers & (Modifiers.ABSTRACT | Modifiers.EXTERN)) != 0)
Error_AssignmentEventOnly (ec);
FieldExpr ml = new FieldExpr (spec.BackingField, loc);
InstanceExpression = null;
return ml.ResolveMemberAccess (ec, left, original);
}
}
return base.ResolveMemberAccess (ec, left, original);
}
public override Expression CreateExpressionTree (ResolveContext ec)
{
throw new NotSupportedException ("ET");
}
public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
{
if (right_side == EmptyExpression.EventAddition) {
op = spec.AccessorAdd;
} else if (right_side == EmptyExpression.EventSubtraction) {
op = spec.AccessorRemove;
}
if (op == null) {
Error_AssignmentEventOnly (ec);
return null;
}
op = CandidateToBaseOverride (ec, op);
return this;
}
protected override Expression DoResolve (ResolveContext ec)
{
eclass = ExprClass.EventAccess;
type = spec.MemberType;
ResolveInstanceExpression (ec, null);
if (!ec.HasSet (ResolveContext.Options.CompoundAssignmentScope)) {
Error_AssignmentEventOnly (ec);
}
DoBestMemberChecks (ec, spec);
return this;
}
public override void Emit (EmitContext ec)
{
throw new NotSupportedException ();
//Error_CannotAssign ();
}
#region IAssignMethod Members
public void Emit (EmitContext ec, bool leave_copy)
{
throw new NotImplementedException ();
}
public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound)
{
if (leave_copy || !isCompound)
throw new NotImplementedException ("EventExpr::EmitAssign");
Arguments args = new Arguments (1);
args.Add (new Argument (source));
var call = new CallEmitter ();
call.InstanceExpression = InstanceExpression;
call.Emit (ec, op, args, loc);
}
#endregion
void Error_AssignmentEventOnly (ResolveContext ec)
{
if (spec.DeclaringType == ec.CurrentType || TypeManager.IsNestedChildOf (ec.CurrentType, spec.DeclaringType.MemberDefinition)) {
ec.Report.Error (79, loc,
"The event `{0}' can only appear on the left hand side of `+=' or `-=' operator",
GetSignatureForError ());
} else {
ec.Report.Error (70, loc,
"The event `{0}' can only appear on the left hand side of += or -= when used outside of the type `{1}'",
GetSignatureForError (), spec.DeclaringType.GetSignatureForError ());
}
}
protected override void Error_CannotCallAbstractBase (ResolveContext rc, string name)
{
name = name.Substring (0, name.LastIndexOf ('.'));
base.Error_CannotCallAbstractBase (rc, name);
}
public override string GetSignatureForError ()
{
return TypeManager.CSharpSignature (spec);
}
public override void SetTypeArguments (ResolveContext ec, TypeArguments ta)
{
Error_TypeArgumentsCannotBeUsed (ec, "event", GetSignatureForError (), loc);
}
}
public class TemporaryVariableReference : VariableReference
{
public class Declarator : Statement
{
TemporaryVariableReference variable;
public Declarator (TemporaryVariableReference variable)
{
this.variable = variable;
loc = variable.loc;
}
protected override void DoEmit (EmitContext ec)
{
variable.li.CreateBuilder (ec);
}
public override void Emit (EmitContext ec)
{
// Don't create sequence point
DoEmit (ec);
}
protected override void CloneTo (CloneContext clonectx, Statement target)
{
// Nothing
}
}
LocalVariable li;
public TemporaryVariableReference (LocalVariable li, Location loc)
{
this.li = li;
this.type = li.Type;
this.loc = loc;
}
public override bool IsLockedByStatement {
get {
return false;
}
set {
}
}
public LocalVariable LocalInfo {
get {
return li;
}
}
public static TemporaryVariableReference Create (TypeSpec type, Block block, Location loc)
{
var li = LocalVariable.CreateCompilerGenerated (type, block, loc);
return new TemporaryVariableReference (li, loc);
}
protected override Expression DoResolve (ResolveContext ec)
{
eclass = ExprClass.Variable;
//
// Don't capture temporary variables except when using
// state machine redirection and block yields
//
if (ec.CurrentAnonymousMethod != null && ec.CurrentAnonymousMethod is StateMachineInitializer &&
(ec.CurrentBlock.Explicit.HasYield || ec.CurrentBlock.Explicit.HasAwait) &&
ec.IsVariableCapturingRequired) {
AnonymousMethodStorey storey = li.Block.Explicit.CreateAnonymousMethodStorey (ec);
storey.CaptureLocalVariable (ec, li);
}
return this;
}
public override Expression DoResolveLValue (ResolveContext ec, Expression right_side)
{
return Resolve (ec);
}
public override void Emit (EmitContext ec)
{
li.CreateBuilder (ec);
Emit (ec, false);
}
public void EmitAssign (EmitContext ec, Expression source)
{
li.CreateBuilder (ec);
EmitAssign (ec, source, false, false);
}
public override HoistedVariable GetHoistedVariable (AnonymousExpression ae)
{
return li.HoistedVariant;
}
public override bool IsFixed {
get { return true; }
}
public override bool IsRef {
get { return false; }
}
public override string Name {
get { throw new NotImplementedException (); }
}
public override void SetHasAddressTaken ()
{
throw new NotImplementedException ();
}
protected override ILocalVariable Variable {
get { return li; }
}
public override VariableInfo VariableInfo {
get { return null; }
}
public override void VerifyAssigned (ResolveContext rc)
{
}
}
///
/// Handles `var' contextual keyword; var becomes a keyword only
/// if no type called var exists in a variable scope
///
class VarExpr : SimpleName
{
public VarExpr (Location loc)
: base ("var", loc)
{
}
public bool InferType (ResolveContext ec, Expression right_side)
{
if (type != null)
throw new InternalErrorException ("An implicitly typed local variable could not be redefined");
type = right_side.Type;
if (type == InternalType.NullLiteral || type.Kind == MemberKind.Void || type == InternalType.AnonymousMethod || type == InternalType.MethodGroup) {
ec.Report.Error (815, loc,
"An implicitly typed local variable declaration cannot be initialized with `{0}'",
type.GetSignatureForError ());
return false;
}
eclass = ExprClass.Variable;
return true;
}
protected override void Error_TypeOrNamespaceNotFound (IMemberContext ec)
{
if (ec.Module.Compiler.Settings.Version < LanguageVersion.V_3)
base.Error_TypeOrNamespaceNotFound (ec);
else
ec.Module.Compiler.Report.Error (825, loc, "The contextual keyword `var' may only appear within a local variable declaration");
}
}
public class InvalidStatementExpression : Statement
{
public Expression Expression {
get;
private set;
}
public InvalidStatementExpression (Expression expr)
{
this.Expression = expr;
}
public override void Emit (EmitContext ec)
{
// nothing
}
protected override void DoEmit (EmitContext ec)
{
// nothing
}
protected override void CloneTo (CloneContext clonectx, Statement target)
{
// nothing
}
public override Mono.CSharp.Expression CreateExpressionTree (ResolveContext ec)
{
return null;
}
public override object Accept (Mono.CSharp.StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
}
|