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
|
//
// statement.cs: Statement representation for the IL tree.
//
// Authors:
// Miguel de Icaza (miguel@ximian.com)
// Martin Baulig (martin@ximian.com)
// Marek Safar (marek.safar@gmail.com)
//
// Copyright 2001, 2002, 2003 Ximian, Inc.
// Copyright 2003, 2004 Novell, Inc.
// Copyright 2011 Xamarin Inc.
//
using System;
using System.Collections.Generic;
#if STATIC
using IKVM.Reflection.Emit;
#else
using System.Reflection.Emit;
#endif
namespace Mono.CSharp {
public abstract class Statement {
public Location loc;
/// <summary>
/// Resolves the statement, true means that all sub-statements
/// did resolve ok.
// </summary>
public virtual bool Resolve (BlockContext bc)
{
return true;
}
/// <summary>
/// We already know that the statement is unreachable, but we still
/// need to resolve it to catch errors.
/// </summary>
public virtual bool ResolveUnreachable (BlockContext ec, bool warn)
{
//
// This conflicts with csc's way of doing this, but IMHO it's
// the right thing to do.
//
// If something is unreachable, we still check whether it's
// correct. This means that you cannot use unassigned variables
// in unreachable code, for instance.
//
bool unreachable = false;
if (warn && !ec.UnreachableReported) {
ec.UnreachableReported = true;
unreachable = true;
ec.Report.Warning (162, 2, loc, "Unreachable code detected");
}
ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
ec.CurrentBranching.CurrentUsageVector.Goto ();
bool ok = Resolve (ec);
ec.KillFlowBranching ();
if (unreachable) {
ec.UnreachableReported = false;
}
return ok;
}
/// <summary>
/// Return value indicates whether all code paths emitted return.
/// </summary>
protected abstract void DoEmit (EmitContext ec);
public virtual void Emit (EmitContext ec)
{
ec.Mark (loc);
DoEmit (ec);
if (ec.StatementEpilogue != null) {
ec.EmitEpilogue ();
}
}
//
// This routine must be overrided in derived classes and make copies
// of all the data that might be modified if resolved
//
protected abstract void CloneTo (CloneContext clonectx, Statement target);
public Statement Clone (CloneContext clonectx)
{
Statement s = (Statement) this.MemberwiseClone ();
CloneTo (clonectx, s);
return s;
}
public virtual Expression CreateExpressionTree (ResolveContext ec)
{
ec.Report.Error (834, loc, "A lambda expression with statement body cannot be converted to an expresion tree");
return null;
}
public virtual object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
public sealed class EmptyStatement : Statement
{
public EmptyStatement (Location loc)
{
this.loc = loc;
}
public override bool Resolve (BlockContext ec)
{
return true;
}
public override bool ResolveUnreachable (BlockContext ec, bool warn)
{
return true;
}
public override void Emit (EmitContext ec)
{
}
protected override void DoEmit (EmitContext ec)
{
throw new NotSupportedException ();
}
protected override void CloneTo (CloneContext clonectx, Statement target)
{
// nothing needed.
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
public class If : Statement {
Expression expr;
public Statement TrueStatement;
public Statement FalseStatement;
bool is_true_ret;
public If (Expression bool_expr, Statement true_statement, Location l)
: this (bool_expr, true_statement, null, l)
{
}
public If (Expression bool_expr,
Statement true_statement,
Statement false_statement,
Location l)
{
this.expr = bool_expr;
TrueStatement = true_statement;
FalseStatement = false_statement;
loc = l;
}
public Expression Expr {
get {
return this.expr;
}
}
public override bool Resolve (BlockContext ec)
{
bool ok = true;
expr = expr.Resolve (ec);
if (expr == null) {
ok = false;
} else {
//
// Dead code elimination
//
if (expr is Constant) {
bool take = !((Constant) expr).IsDefaultValue;
if (take) {
if (!TrueStatement.Resolve (ec))
return false;
if ((FalseStatement != null) &&
!FalseStatement.ResolveUnreachable (ec, true))
return false;
FalseStatement = null;
} else {
if (!TrueStatement.ResolveUnreachable (ec, true))
return false;
TrueStatement = null;
if ((FalseStatement != null) &&
!FalseStatement.Resolve (ec))
return false;
}
return true;
}
}
ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
ok &= TrueStatement.Resolve (ec);
is_true_ret = ec.CurrentBranching.CurrentUsageVector.IsUnreachable;
ec.CurrentBranching.CreateSibling ();
if (FalseStatement != null)
ok &= FalseStatement.Resolve (ec);
ec.EndFlowBranching ();
return ok;
}
protected override void DoEmit (EmitContext ec)
{
Label false_target = ec.DefineLabel ();
Label end;
//
// If we're a boolean constant, Resolve() already
// eliminated dead code for us.
//
Constant c = expr as Constant;
if (c != null){
c.EmitSideEffect (ec);
if (!c.IsDefaultValue)
TrueStatement.Emit (ec);
else if (FalseStatement != null)
FalseStatement.Emit (ec);
return;
}
expr.EmitBranchable (ec, false_target, false);
TrueStatement.Emit (ec);
if (FalseStatement != null){
bool branch_emitted = false;
end = ec.DefineLabel ();
if (!is_true_ret){
ec.Emit (OpCodes.Br, end);
branch_emitted = true;
}
ec.MarkLabel (false_target);
FalseStatement.Emit (ec);
if (branch_emitted)
ec.MarkLabel (end);
} else {
ec.MarkLabel (false_target);
}
}
protected override void CloneTo (CloneContext clonectx, Statement t)
{
If target = (If) t;
target.expr = expr.Clone (clonectx);
target.TrueStatement = TrueStatement.Clone (clonectx);
if (FalseStatement != null)
target.FalseStatement = FalseStatement.Clone (clonectx);
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
public class Do : Statement {
public Expression expr;
public Statement EmbeddedStatement;
public Do (Statement statement, BooleanExpression bool_expr, Location doLocation, Location whileLocation)
{
expr = bool_expr;
EmbeddedStatement = statement;
loc = doLocation;
WhileLocation = whileLocation;
}
public Location WhileLocation {
get; private set;
}
public override bool Resolve (BlockContext ec)
{
bool ok = true;
ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
bool was_unreachable = ec.CurrentBranching.CurrentUsageVector.IsUnreachable;
ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
if (!EmbeddedStatement.Resolve (ec))
ok = false;
ec.EndFlowBranching ();
if (ec.CurrentBranching.CurrentUsageVector.IsUnreachable && !was_unreachable)
ec.Report.Warning (162, 2, expr.Location, "Unreachable code detected");
expr = expr.Resolve (ec);
if (expr == null)
ok = false;
else if (expr is Constant){
bool infinite = !((Constant) expr).IsDefaultValue;
if (infinite)
ec.CurrentBranching.CurrentUsageVector.Goto ();
}
ec.EndFlowBranching ();
return ok;
}
protected override void DoEmit (EmitContext ec)
{
Label loop = ec.DefineLabel ();
Label old_begin = ec.LoopBegin;
Label old_end = ec.LoopEnd;
ec.LoopBegin = ec.DefineLabel ();
ec.LoopEnd = ec.DefineLabel ();
ec.MarkLabel (loop);
EmbeddedStatement.Emit (ec);
ec.MarkLabel (ec.LoopBegin);
// Mark start of while condition
ec.Mark (WhileLocation);
//
// Dead code elimination
//
if (expr is Constant) {
bool res = !((Constant) expr).IsDefaultValue;
expr.EmitSideEffect (ec);
if (res)
ec.Emit (OpCodes.Br, loop);
} else {
expr.EmitBranchable (ec, loop, true);
}
ec.MarkLabel (ec.LoopEnd);
ec.LoopBegin = old_begin;
ec.LoopEnd = old_end;
}
protected override void CloneTo (CloneContext clonectx, Statement t)
{
Do target = (Do) t;
target.EmbeddedStatement = EmbeddedStatement.Clone (clonectx);
target.expr = expr.Clone (clonectx);
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
public class While : Statement {
public Expression expr;
public Statement Statement;
bool infinite, empty;
public While (BooleanExpression bool_expr, Statement statement, Location l)
{
this.expr = bool_expr;
Statement = statement;
loc = l;
}
public override bool Resolve (BlockContext ec)
{
bool ok = true;
expr = expr.Resolve (ec);
if (expr == null)
ok = false;
//
// Inform whether we are infinite or not
//
if (expr is Constant){
bool value = !((Constant) expr).IsDefaultValue;
if (value == false){
if (!Statement.ResolveUnreachable (ec, true))
return false;
empty = true;
return true;
} else
infinite = true;
}
ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
if (!infinite)
ec.CurrentBranching.CreateSibling ();
ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
if (!Statement.Resolve (ec))
ok = false;
ec.EndFlowBranching ();
// There's no direct control flow from the end of the embedded statement to the end of the loop
ec.CurrentBranching.CurrentUsageVector.Goto ();
ec.EndFlowBranching ();
return ok;
}
protected override void DoEmit (EmitContext ec)
{
if (empty) {
expr.EmitSideEffect (ec);
return;
}
Label old_begin = ec.LoopBegin;
Label old_end = ec.LoopEnd;
ec.LoopBegin = ec.DefineLabel ();
ec.LoopEnd = ec.DefineLabel ();
//
// Inform whether we are infinite or not
//
if (expr is Constant) {
// expr is 'true', since the 'empty' case above handles the 'false' case
ec.MarkLabel (ec.LoopBegin);
if (ec.EmitAccurateDebugInfo)
ec.Emit (OpCodes.Nop);
expr.EmitSideEffect (ec);
Statement.Emit (ec);
ec.Emit (OpCodes.Br, ec.LoopBegin);
//
// Inform that we are infinite (ie, `we return'), only
// if we do not `break' inside the code.
//
ec.MarkLabel (ec.LoopEnd);
} else {
Label while_loop = ec.DefineLabel ();
ec.Emit (OpCodes.Br, ec.LoopBegin);
ec.MarkLabel (while_loop);
Statement.Emit (ec);
ec.MarkLabel (ec.LoopBegin);
ec.Mark (loc);
expr.EmitBranchable (ec, while_loop, true);
ec.MarkLabel (ec.LoopEnd);
}
ec.LoopBegin = old_begin;
ec.LoopEnd = old_end;
}
protected override void CloneTo (CloneContext clonectx, Statement t)
{
While target = (While) t;
target.expr = expr.Clone (clonectx);
target.Statement = Statement.Clone (clonectx);
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
public class For : Statement
{
bool infinite, empty;
public For (Location l)
{
loc = l;
}
public Statement Initializer {
get; set;
}
public Expression Condition {
get; set;
}
public Statement Iterator {
get; set;
}
public Statement Statement {
get; set;
}
public override bool Resolve (BlockContext ec)
{
bool ok = true;
if (Initializer != null) {
if (!Initializer.Resolve (ec))
ok = false;
}
if (Condition != null) {
Condition = Condition.Resolve (ec);
if (Condition == null)
ok = false;
else if (Condition is Constant) {
bool value = !((Constant) Condition).IsDefaultValue;
if (value == false){
if (!Statement.ResolveUnreachable (ec, true))
return false;
if ((Iterator != null) &&
!Iterator.ResolveUnreachable (ec, false))
return false;
empty = true;
return true;
} else
infinite = true;
}
} else
infinite = true;
ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
if (!infinite)
ec.CurrentBranching.CreateSibling ();
bool was_unreachable = ec.CurrentBranching.CurrentUsageVector.IsUnreachable;
ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
if (!Statement.Resolve (ec))
ok = false;
ec.EndFlowBranching ();
if (Iterator != null){
if (ec.CurrentBranching.CurrentUsageVector.IsUnreachable) {
if (!Iterator.ResolveUnreachable (ec, !was_unreachable))
ok = false;
} else {
if (!Iterator.Resolve (ec))
ok = false;
}
}
// There's no direct control flow from the end of the embedded statement to the end of the loop
ec.CurrentBranching.CurrentUsageVector.Goto ();
ec.EndFlowBranching ();
return ok;
}
protected override void DoEmit (EmitContext ec)
{
if (Initializer != null)
Initializer.Emit (ec);
if (empty) {
Condition.EmitSideEffect (ec);
return;
}
Label old_begin = ec.LoopBegin;
Label old_end = ec.LoopEnd;
Label loop = ec.DefineLabel ();
Label test = ec.DefineLabel ();
ec.LoopBegin = ec.DefineLabel ();
ec.LoopEnd = ec.DefineLabel ();
ec.Emit (OpCodes.Br, test);
ec.MarkLabel (loop);
Statement.Emit (ec);
ec.MarkLabel (ec.LoopBegin);
Iterator.Emit (ec);
ec.MarkLabel (test);
//
// If test is null, there is no test, and we are just
// an infinite loop
//
if (Condition != null) {
ec.Mark (Condition.Location);
//
// The Resolve code already catches the case for
// Test == Constant (false) so we know that
// this is true
//
if (Condition is Constant) {
Condition.EmitSideEffect (ec);
ec.Emit (OpCodes.Br, loop);
} else {
Condition.EmitBranchable (ec, loop, true);
}
} else
ec.Emit (OpCodes.Br, loop);
ec.MarkLabel (ec.LoopEnd);
ec.LoopBegin = old_begin;
ec.LoopEnd = old_end;
}
protected override void CloneTo (CloneContext clonectx, Statement t)
{
For target = (For) t;
if (Initializer != null)
target.Initializer = Initializer.Clone (clonectx);
if (Condition != null)
target.Condition = Condition.Clone (clonectx);
if (Iterator != null)
target.Iterator = Iterator.Clone (clonectx);
target.Statement = Statement.Clone (clonectx);
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
public class StatementExpression : Statement
{
ExpressionStatement expr;
public StatementExpression (ExpressionStatement expr)
{
this.expr = expr;
loc = expr.StartLocation;
}
public StatementExpression (ExpressionStatement expr, Location loc)
{
this.expr = expr;
this.loc = loc;
}
public ExpressionStatement Expr {
get {
return this.expr;
}
}
protected override void CloneTo (CloneContext clonectx, Statement t)
{
StatementExpression target = (StatementExpression) t;
target.expr = (ExpressionStatement) expr.Clone (clonectx);
}
protected override void DoEmit (EmitContext ec)
{
expr.EmitStatement (ec);
}
public override bool Resolve (BlockContext ec)
{
expr = expr.ResolveStatement (ec);
return expr != null;
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
public class StatementErrorExpression : Statement
{
readonly Expression expr;
public StatementErrorExpression (Expression expr)
{
this.expr = expr;
this.loc = expr.StartLocation;
}
public Expression Expr {
get {
return expr;
}
}
public override bool Resolve (BlockContext bc)
{
expr.Error_InvalidExpressionStatement (bc);
return true;
}
protected override void DoEmit (EmitContext ec)
{
throw new NotSupportedException ();
}
protected override void CloneTo (CloneContext clonectx, Statement target)
{
throw new NotImplementedException ();
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
//
// Simple version of statement list not requiring a block
//
public class StatementList : Statement
{
List<Statement> statements;
public StatementList (Statement first, Statement second)
{
statements = new List<Statement> () { first, second };
}
#region Properties
public IList<Statement> Statements {
get {
return statements;
}
}
#endregion
public void Add (Statement statement)
{
statements.Add (statement);
}
public override bool Resolve (BlockContext ec)
{
foreach (var s in statements)
s.Resolve (ec);
return true;
}
protected override void DoEmit (EmitContext ec)
{
foreach (var s in statements)
s.Emit (ec);
}
protected override void CloneTo (CloneContext clonectx, Statement target)
{
StatementList t = (StatementList) target;
t.statements = new List<Statement> (statements.Count);
foreach (Statement s in statements)
t.statements.Add (s.Clone (clonectx));
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
// A 'return' or a 'yield break'
public abstract class ExitStatement : Statement
{
protected bool unwind_protect;
protected abstract bool DoResolve (BlockContext ec);
public virtual void Error_FinallyClause (Report Report)
{
Report.Error (157, loc, "Control cannot leave the body of a finally clause");
}
public sealed override bool Resolve (BlockContext ec)
{
var res = DoResolve (ec);
unwind_protect = ec.CurrentBranching.AddReturnOrigin (ec.CurrentBranching.CurrentUsageVector, this);
ec.CurrentBranching.CurrentUsageVector.Goto ();
return res;
}
}
/// <summary>
/// Implements the return statement
/// </summary>
public class Return : ExitStatement
{
Expression expr;
public Return (Expression expr, Location l)
{
this.expr = expr;
loc = l;
}
#region Properties
public Expression Expr {
get {
return expr;
}
protected set {
expr = value;
}
}
#endregion
protected override bool DoResolve (BlockContext ec)
{
if (expr == null) {
if (ec.ReturnType.Kind == MemberKind.Void)
return true;
//
// Return must not be followed by an expression when
// the method return type is Task
//
if (ec.CurrentAnonymousMethod is AsyncInitializer) {
var storey = (AsyncTaskStorey) ec.CurrentAnonymousMethod.Storey;
if (storey.ReturnType == ec.Module.PredefinedTypes.Task.TypeSpec) {
//
// Extra trick not to emit ret/leave inside awaiter body
//
expr = EmptyExpression.Null;
return true;
}
}
if (ec.CurrentIterator != null) {
Error_ReturnFromIterator (ec);
} else if (ec.ReturnType != InternalType.ErrorType) {
ec.Report.Error (126, loc,
"An object of a type convertible to `{0}' is required for the return statement",
ec.ReturnType.GetSignatureForError ());
}
return false;
}
expr = expr.Resolve (ec);
TypeSpec block_return_type = ec.ReturnType;
AnonymousExpression am = ec.CurrentAnonymousMethod;
if (am == null) {
if (block_return_type.Kind == MemberKind.Void) {
ec.Report.Error (127, loc,
"`{0}': A return keyword must not be followed by any expression when method returns void",
ec.GetSignatureForError ());
return false;
}
} else {
if (am.IsIterator) {
Error_ReturnFromIterator (ec);
return false;
}
var async_block = am as AsyncInitializer;
if (async_block != null) {
if (expr != null) {
var storey = (AsyncTaskStorey) am.Storey;
var async_type = storey.ReturnType;
if (async_type == null && async_block.ReturnTypeInference != null) {
async_block.ReturnTypeInference.AddCommonTypeBound (expr.Type);
return true;
}
if (async_type.Kind == MemberKind.Void) {
ec.Report.Error (127, loc,
"`{0}': A return keyword must not be followed by any expression when method returns void",
ec.GetSignatureForError ());
return false;
}
if (!async_type.IsGenericTask) {
if (this is ContextualReturn)
return true;
// Same error code as .NET but better error message
if (async_block.DelegateType != null) {
ec.Report.Error (1997, loc,
"`{0}': A return keyword must not be followed by an expression when async delegate returns `Task'. Consider using `Task<T>' return type",
async_block.DelegateType.GetSignatureForError ());
} else {
ec.Report.Error (1997, loc,
"`{0}': A return keyword must not be followed by an expression when async method returns `Task'. Consider using `Task<T>' return type",
ec.GetSignatureForError ());
}
return false;
}
//
// The return type is actually Task<T> type argument
//
if (expr.Type == async_type) {
ec.Report.Error (4016, loc,
"`{0}': The return expression type of async method must be `{1}' rather than `Task<{1}>'",
ec.GetSignatureForError (), async_type.TypeArguments[0].GetSignatureForError ());
} else {
block_return_type = async_type.TypeArguments[0];
}
}
} else {
// Same error code as .NET but better error message
if (block_return_type.Kind == MemberKind.Void) {
ec.Report.Error (127, loc,
"`{0}': A return keyword must not be followed by any expression when delegate returns void",
am.GetSignatureForError ());
return false;
}
var l = am as AnonymousMethodBody;
if (l != null && expr != null) {
if (l.ReturnTypeInference != null) {
l.ReturnTypeInference.AddCommonTypeBound (expr.Type);
return true;
}
//
// Try to optimize simple lambda. Only when optimizations are enabled not to cause
// unexpected debugging experience
//
if (this is ContextualReturn && !ec.IsInProbingMode && ec.Module.Compiler.Settings.Optimize) {
l.DirectMethodGroupConversion = expr.CanReduceLambda (l);
}
}
}
}
if (expr == null)
return false;
if (expr.Type != block_return_type && expr.Type != InternalType.ErrorType) {
expr = Convert.ImplicitConversionRequired (ec, expr, block_return_type, loc);
if (expr == null) {
if (am != null && block_return_type == ec.ReturnType) {
ec.Report.Error (1662, loc,
"Cannot convert `{0}' to delegate type `{1}' because some of the return types in the block are not implicitly convertible to the delegate return type",
am.ContainerType, am.GetSignatureForError ());
}
return false;
}
}
return true;
}
protected override void DoEmit (EmitContext ec)
{
if (expr != null) {
expr.Emit (ec);
var async_body = ec.CurrentAnonymousMethod as AsyncInitializer;
if (async_body != null) {
var async_return = ((AsyncTaskStorey) async_body.Storey).HoistedReturn;
// It's null for await without async
if (async_return != null) {
async_return.EmitAssign (ec);
ec.EmitEpilogue ();
}
ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, async_body.BodyEnd);
return;
}
ec.EmitEpilogue ();
if (unwind_protect || ec.EmitAccurateDebugInfo)
ec.Emit (OpCodes.Stloc, ec.TemporaryReturn ());
}
if (unwind_protect) {
ec.Emit (OpCodes.Leave, ec.CreateReturnLabel ());
} else if (ec.EmitAccurateDebugInfo) {
ec.Emit (OpCodes.Br, ec.CreateReturnLabel ());
} else {
ec.Emit (OpCodes.Ret);
}
}
void Error_ReturnFromIterator (ResolveContext rc)
{
rc.Report.Error (1622, loc,
"Cannot return a value from iterators. Use the yield return statement to return a value, or yield break to end the iteration");
}
protected override void CloneTo (CloneContext clonectx, Statement t)
{
Return target = (Return) t;
// It's null for simple return;
if (expr != null)
target.expr = expr.Clone (clonectx);
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
public class Goto : Statement {
string target;
LabeledStatement label;
bool unwind_protect;
public override bool Resolve (BlockContext ec)
{
unwind_protect = ec.CurrentBranching.AddGotoOrigin (ec.CurrentBranching.CurrentUsageVector, this);
ec.CurrentBranching.CurrentUsageVector.Goto ();
return true;
}
public Goto (string label, Location l)
{
loc = l;
target = label;
}
public string Target {
get { return target; }
}
public void SetResolvedTarget (LabeledStatement label)
{
this.label = label;
label.AddReference ();
}
protected override void CloneTo (CloneContext clonectx, Statement target)
{
// Nothing to clone
}
protected override void DoEmit (EmitContext ec)
{
if (label == null)
throw new InternalErrorException ("goto emitted before target resolved");
Label l = label.LabelTarget (ec);
ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, l);
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
public class LabeledStatement : Statement {
string name;
bool defined;
bool referenced;
Label label;
Block block;
FlowBranching.UsageVector vectors;
public LabeledStatement (string name, Block block, Location l)
{
this.name = name;
this.block = block;
this.loc = l;
}
public Label LabelTarget (EmitContext ec)
{
if (defined)
return label;
label = ec.DefineLabel ();
defined = true;
return label;
}
public Block Block {
get {
return block;
}
}
public string Name {
get { return name; }
}
public bool IsDefined {
get { return defined; }
}
public bool HasBeenReferenced {
get { return referenced; }
}
public FlowBranching.UsageVector JumpOrigins {
get { return vectors; }
}
public void AddUsageVector (FlowBranching.UsageVector vector)
{
vector = vector.Clone ();
vector.Next = vectors;
vectors = vector;
}
protected override void CloneTo (CloneContext clonectx, Statement target)
{
// nothing to clone
}
public override bool Resolve (BlockContext ec)
{
// this flow-branching will be terminated when the surrounding block ends
ec.StartFlowBranching (this);
return true;
}
protected override void DoEmit (EmitContext ec)
{
if (!HasBeenReferenced)
ec.Report.Warning (164, 2, loc, "This label has not been referenced");
LabelTarget (ec);
ec.MarkLabel (label);
}
public void AddReference ()
{
referenced = true;
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
/// <summary>
/// `goto default' statement
/// </summary>
public class GotoDefault : Statement {
public GotoDefault (Location l)
{
loc = l;
}
protected override void CloneTo (CloneContext clonectx, Statement target)
{
// nothing to clone
}
public override bool Resolve (BlockContext ec)
{
ec.CurrentBranching.CurrentUsageVector.Goto ();
if (ec.Switch == null) {
ec.Report.Error (153, loc, "A goto case is only valid inside a switch statement");
return false;
}
ec.Switch.RegisterGotoCase (null, null);
return true;
}
protected override void DoEmit (EmitContext ec)
{
ec.Emit (OpCodes.Br, ec.Switch.DefaultLabel.GetILLabel (ec));
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
/// <summary>
/// `goto case' statement
/// </summary>
public class GotoCase : Statement {
Expression expr;
public GotoCase (Expression e, Location l)
{
expr = e;
loc = l;
}
public Expression Expr {
get {
return this.expr;
}
}
public SwitchLabel Label { get; set; }
public override bool Resolve (BlockContext ec)
{
if (ec.Switch == null){
ec.Report.Error (153, loc, "A goto case is only valid inside a switch statement");
return false;
}
ec.CurrentBranching.CurrentUsageVector.Goto ();
Constant c = expr.ResolveLabelConstant (ec);
if (c == null) {
return false;
}
Constant res;
if (ec.Switch.IsNullable && c is NullLiteral) {
res = c;
} else {
TypeSpec type = ec.Switch.SwitchType;
res = c.Reduce (ec, type);
if (res == null) {
c.Error_ValueCannotBeConverted (ec, type, true);
return false;
}
if (!Convert.ImplicitStandardConversionExists (c, type))
ec.Report.Warning (469, 2, loc,
"The `goto case' value is not implicitly convertible to type `{0}'",
type.GetSignatureForError ());
}
ec.Switch.RegisterGotoCase (this, res);
return true;
}
protected override void DoEmit (EmitContext ec)
{
ec.Emit (OpCodes.Br, Label.GetILLabel (ec));
}
protected override void CloneTo (CloneContext clonectx, Statement t)
{
GotoCase target = (GotoCase) t;
target.expr = expr.Clone (clonectx);
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
public class Throw : Statement {
Expression expr;
public Throw (Expression expr, Location l)
{
this.expr = expr;
loc = l;
}
public Expression Expr {
get {
return this.expr;
}
}
public override bool Resolve (BlockContext ec)
{
if (expr == null) {
ec.CurrentBranching.CurrentUsageVector.Goto ();
return ec.CurrentBranching.CheckRethrow (loc);
}
expr = expr.Resolve (ec, ResolveFlags.Type | ResolveFlags.VariableOrValue);
ec.CurrentBranching.CurrentUsageVector.Goto ();
if (expr == null)
return false;
var et = ec.BuiltinTypes.Exception;
if (Convert.ImplicitConversionExists (ec, expr, et))
expr = Convert.ImplicitConversion (ec, expr, et, loc);
else
ec.Report.Error (155, expr.Location, "The type caught or thrown must be derived from System.Exception");
return true;
}
protected override void DoEmit (EmitContext ec)
{
if (expr == null)
ec.Emit (OpCodes.Rethrow);
else {
expr.Emit (ec);
ec.Emit (OpCodes.Throw);
}
}
protected override void CloneTo (CloneContext clonectx, Statement t)
{
Throw target = (Throw) t;
if (expr != null)
target.expr = expr.Clone (clonectx);
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
public class Break : Statement {
public Break (Location l)
{
loc = l;
}
bool unwind_protect;
public override bool Resolve (BlockContext ec)
{
unwind_protect = ec.CurrentBranching.AddBreakOrigin (ec.CurrentBranching.CurrentUsageVector, loc);
ec.CurrentBranching.CurrentUsageVector.Goto ();
return true;
}
protected override void DoEmit (EmitContext ec)
{
ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, ec.LoopEnd);
}
protected override void CloneTo (CloneContext clonectx, Statement t)
{
// nothing needed
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
public class Continue : Statement {
public Continue (Location l)
{
loc = l;
}
bool unwind_protect;
public override bool Resolve (BlockContext ec)
{
unwind_protect = ec.CurrentBranching.AddContinueOrigin (ec.CurrentBranching.CurrentUsageVector, loc);
ec.CurrentBranching.CurrentUsageVector.Goto ();
return true;
}
protected override void DoEmit (EmitContext ec)
{
ec.Emit (unwind_protect ? OpCodes.Leave : OpCodes.Br, ec.LoopBegin);
}
protected override void CloneTo (CloneContext clonectx, Statement t)
{
// nothing needed.
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
public interface ILocalVariable
{
void Emit (EmitContext ec);
void EmitAssign (EmitContext ec);
void EmitAddressOf (EmitContext ec);
}
public interface INamedBlockVariable
{
Block Block { get; }
Expression CreateReferenceExpression (ResolveContext rc, Location loc);
bool IsDeclared { get; }
bool IsParameter { get; }
Location Location { get; }
}
public class BlockVariableDeclarator
{
LocalVariable li;
Expression initializer;
public BlockVariableDeclarator (LocalVariable li, Expression initializer)
{
if (li.Type != null)
throw new ArgumentException ("Expected null variable type");
this.li = li;
this.initializer = initializer;
}
#region Properties
public LocalVariable Variable {
get {
return li;
}
}
public Expression Initializer {
get {
return initializer;
}
set {
initializer = value;
}
}
#endregion
public virtual BlockVariableDeclarator Clone (CloneContext cloneCtx)
{
var t = (BlockVariableDeclarator) MemberwiseClone ();
if (initializer != null)
t.initializer = initializer.Clone (cloneCtx);
return t;
}
}
public class BlockVariable : Statement
{
Expression initializer;
protected FullNamedExpression type_expr;
protected LocalVariable li;
protected List<BlockVariableDeclarator> declarators;
TypeSpec type;
public BlockVariable (FullNamedExpression type, LocalVariable li)
{
this.type_expr = type;
this.li = li;
this.loc = type_expr.Location;
}
protected BlockVariable (LocalVariable li)
{
this.li = li;
}
#region Properties
public List<BlockVariableDeclarator> Declarators {
get {
return declarators;
}
}
public Expression Initializer {
get {
return initializer;
}
set {
initializer = value;
}
}
public FullNamedExpression TypeExpression {
get {
return type_expr;
}
}
public LocalVariable Variable {
get {
return li;
}
}
#endregion
public void AddDeclarator (BlockVariableDeclarator decl)
{
if (declarators == null)
declarators = new List<BlockVariableDeclarator> ();
declarators.Add (decl);
}
static void CreateEvaluatorVariable (BlockContext bc, LocalVariable li)
{
if (bc.Report.Errors != 0)
return;
var container = bc.CurrentMemberDefinition.Parent.PartialContainer;
Field f = new Field (container, new TypeExpression (li.Type, li.Location), Modifiers.PUBLIC | Modifiers.STATIC,
new MemberName (li.Name, li.Location), null);
container.AddField (f);
f.Define ();
li.HoistedVariant = new HoistedEvaluatorVariable (f);
li.SetIsUsed ();
}
public override bool Resolve (BlockContext bc)
{
return Resolve (bc, true);
}
public bool Resolve (BlockContext bc, bool resolveDeclaratorInitializers)
{
if (type == null && !li.IsCompilerGenerated) {
var vexpr = type_expr as VarExpr;
//
// C# 3.0 introduced contextual keywords (var) which behaves like a type if type with
// same name exists or as a keyword when no type was found
//
if (vexpr != null && !vexpr.IsPossibleTypeOrNamespace (bc)) {
if (bc.Module.Compiler.Settings.Version < LanguageVersion.V_3)
bc.Report.FeatureIsNotAvailable (bc.Module.Compiler, loc, "implicitly typed local variable");
if (li.IsFixed) {
bc.Report.Error (821, loc, "A fixed statement cannot use an implicitly typed local variable");
return false;
}
if (li.IsConstant) {
bc.Report.Error (822, loc, "An implicitly typed local variable cannot be a constant");
return false;
}
if (Initializer == null) {
bc.Report.Error (818, loc, "An implicitly typed local variable declarator must include an initializer");
return false;
}
if (declarators != null) {
bc.Report.Error (819, loc, "An implicitly typed local variable declaration cannot include multiple declarators");
declarators = null;
}
Initializer = Initializer.Resolve (bc);
if (Initializer != null) {
((VarExpr) type_expr).InferType (bc, Initializer);
type = type_expr.Type;
} else {
// Set error type to indicate the var was placed correctly but could
// not be infered
//
// var a = missing ();
//
type = InternalType.ErrorType;
}
}
if (type == null) {
type = type_expr.ResolveAsType (bc);
if (type == null)
return false;
if (li.IsConstant && !type.IsConstantCompatible) {
Const.Error_InvalidConstantType (type, loc, bc.Report);
}
}
if (type.IsStatic)
FieldBase.Error_VariableOfStaticClass (loc, li.Name, type, bc.Report);
li.Type = type;
}
bool eval_global = bc.Module.Compiler.Settings.StatementMode && bc.CurrentBlock is ToplevelBlock;
if (eval_global) {
CreateEvaluatorVariable (bc, li);
} else if (type != InternalType.ErrorType) {
li.PrepareForFlowAnalysis (bc);
}
if (initializer != null) {
initializer = ResolveInitializer (bc, li, initializer);
// li.Variable.DefinitelyAssigned
}
if (declarators != null) {
foreach (var d in declarators) {
d.Variable.Type = li.Type;
if (eval_global) {
CreateEvaluatorVariable (bc, d.Variable);
} else if (type != InternalType.ErrorType) {
d.Variable.PrepareForFlowAnalysis (bc);
}
if (d.Initializer != null && resolveDeclaratorInitializers) {
d.Initializer = ResolveInitializer (bc, d.Variable, d.Initializer);
// d.Variable.DefinitelyAssigned
}
}
}
return true;
}
protected virtual Expression ResolveInitializer (BlockContext bc, LocalVariable li, Expression initializer)
{
var a = new SimpleAssign (li.CreateReferenceExpression (bc, li.Location), initializer, li.Location);
return a.ResolveStatement (bc);
}
protected override void DoEmit (EmitContext ec)
{
li.CreateBuilder (ec);
if (Initializer != null)
((ExpressionStatement) Initializer).EmitStatement (ec);
if (declarators != null) {
foreach (var d in declarators) {
d.Variable.CreateBuilder (ec);
if (d.Initializer != null) {
ec.Mark (d.Variable.Location);
((ExpressionStatement) d.Initializer).EmitStatement (ec);
}
}
}
}
protected override void CloneTo (CloneContext clonectx, Statement target)
{
BlockVariable t = (BlockVariable) target;
if (type_expr != null)
t.type_expr = (FullNamedExpression) type_expr.Clone (clonectx);
if (initializer != null)
t.initializer = initializer.Clone (clonectx);
if (declarators != null) {
t.declarators = null;
foreach (var d in declarators)
t.AddDeclarator (d.Clone (clonectx));
}
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
public class BlockConstant : BlockVariable
{
public BlockConstant (FullNamedExpression type, LocalVariable li)
: base (type, li)
{
}
public override void Emit (EmitContext ec)
{
// Nothing to emit, not even sequence point
}
protected override Expression ResolveInitializer (BlockContext bc, LocalVariable li, Expression initializer)
{
initializer = initializer.Resolve (bc);
if (initializer == null)
return null;
var c = initializer as Constant;
if (c == null) {
initializer.Error_ExpressionMustBeConstant (bc, initializer.Location, li.Name);
return null;
}
c = c.ConvertImplicitly (li.Type);
if (c == null) {
if (TypeSpec.IsReferenceType (li.Type))
initializer.Error_ConstantCanBeInitializedWithNullOnly (bc, li.Type, initializer.Location, li.Name);
else
initializer.Error_ValueCannotBeConverted (bc, li.Type, false);
return null;
}
li.ConstantValue = c;
return initializer;
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
//
// The information about a user-perceived local variable
//
public class LocalVariable : INamedBlockVariable, ILocalVariable
{
[Flags]
public enum Flags
{
Used = 1,
IsThis = 1 << 1,
AddressTaken = 1 << 2,
CompilerGenerated = 1 << 3,
Constant = 1 << 4,
ForeachVariable = 1 << 5,
FixedVariable = 1 << 6,
UsingVariable = 1 << 7,
// DefinitelyAssigned = 1 << 8,
IsLocked = 1 << 9,
ReadonlyMask = ForeachVariable | FixedVariable | UsingVariable
}
TypeSpec type;
readonly string name;
readonly Location loc;
readonly Block block;
Flags flags;
Constant const_value;
public VariableInfo VariableInfo;
HoistedVariable hoisted_variant;
LocalBuilder builder;
public LocalVariable (Block block, string name, Location loc)
{
this.block = block;
this.name = name;
this.loc = loc;
}
public LocalVariable (Block block, string name, Flags flags, Location loc)
: this (block, name, loc)
{
this.flags = flags;
}
//
// Used by variable declarators
//
public LocalVariable (LocalVariable li, string name, Location loc)
: this (li.block, name, li.flags, loc)
{
}
#region Properties
public bool AddressTaken {
get {
return (flags & Flags.AddressTaken) != 0;
}
}
public Block Block {
get {
return block;
}
}
public Constant ConstantValue {
get {
return const_value;
}
set {
const_value = value;
}
}
//
// Hoisted local variable variant
//
public HoistedVariable HoistedVariant {
get {
return hoisted_variant;
}
set {
hoisted_variant = value;
}
}
public bool IsDeclared {
get {
return type != null;
}
}
public bool IsCompilerGenerated {
get {
return (flags & Flags.CompilerGenerated) != 0;
}
}
public bool IsConstant {
get {
return (flags & Flags.Constant) != 0;
}
}
public bool IsLocked {
get {
return (flags & Flags.IsLocked) != 0;
}
set {
flags = value ? flags | Flags.IsLocked : flags & ~Flags.IsLocked;
}
}
public bool IsThis {
get {
return (flags & Flags.IsThis) != 0;
}
}
public bool IsFixed {
get {
return (flags & Flags.FixedVariable) != 0;
}
}
bool INamedBlockVariable.IsParameter {
get {
return false;
}
}
public bool IsReadonly {
get {
return (flags & Flags.ReadonlyMask) != 0;
}
}
public Location Location {
get {
return loc;
}
}
public string Name {
get {
return name;
}
}
public TypeSpec Type {
get {
return type;
}
set {
type = value;
}
}
#endregion
public void CreateBuilder (EmitContext ec)
{
if ((flags & Flags.Used) == 0) {
if (VariableInfo == null) {
// Missing flow analysis or wrong variable flags
throw new InternalErrorException ("VariableInfo is null and the variable `{0}' is not used", name);
}
if (VariableInfo.IsEverAssigned)
ec.Report.Warning (219, 3, Location, "The variable `{0}' is assigned but its value is never used", Name);
else
ec.Report.Warning (168, 3, Location, "The variable `{0}' is declared but never used", Name);
}
if (HoistedVariant != null)
return;
if (builder != null) {
if ((flags & Flags.CompilerGenerated) != 0)
return;
// To avoid Used warning duplicates
throw new InternalErrorException ("Already created variable `{0}'", name);
}
//
// All fixed variabled are pinned, a slot has to be alocated
//
builder = ec.DeclareLocal (Type, IsFixed);
if (!ec.HasSet (BuilderContext.Options.OmitDebugInfo) && (flags & Flags.CompilerGenerated) == 0)
ec.DefineLocalVariable (name, builder);
}
public static LocalVariable CreateCompilerGenerated (TypeSpec type, Block block, Location loc)
{
LocalVariable li = new LocalVariable (block, GetCompilerGeneratedName (block), Flags.CompilerGenerated | Flags.Used, loc);
li.Type = type;
return li;
}
public Expression CreateReferenceExpression (ResolveContext rc, Location loc)
{
if (IsConstant && const_value != null)
return Constant.CreateConstantFromValue (Type, const_value.GetValue (), loc);
return new LocalVariableReference (this, loc);
}
public void Emit (EmitContext ec)
{
// TODO: Need something better for temporary variables
if ((flags & Flags.CompilerGenerated) != 0)
CreateBuilder (ec);
ec.Emit (OpCodes.Ldloc, builder);
}
public void EmitAssign (EmitContext ec)
{
// TODO: Need something better for temporary variables
if ((flags & Flags.CompilerGenerated) != 0)
CreateBuilder (ec);
ec.Emit (OpCodes.Stloc, builder);
}
public void EmitAddressOf (EmitContext ec)
{
ec.Emit (OpCodes.Ldloca, builder);
}
public static string GetCompilerGeneratedName (Block block)
{
// HACK: Debugger depends on the name semantics
return "$locvar" + block.ParametersBlock.TemporaryLocalsCount++.ToString ("X");
}
public string GetReadOnlyContext ()
{
switch (flags & Flags.ReadonlyMask) {
case Flags.FixedVariable:
return "fixed variable";
case Flags.ForeachVariable:
return "foreach iteration variable";
case Flags.UsingVariable:
return "using variable";
}
throw new InternalErrorException ("Variable is not readonly");
}
public bool IsThisAssigned (BlockContext ec, Block block)
{
if (VariableInfo == null)
throw new Exception ();
if (!ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo))
return true;
return VariableInfo.IsFullyInitialized (ec, block.StartLocation);
}
public bool IsAssigned (BlockContext ec)
{
if (VariableInfo == null)
throw new Exception ();
return !ec.DoFlowAnalysis || ec.CurrentBranching.IsAssigned (VariableInfo);
}
public void PrepareForFlowAnalysis (BlockContext bc)
{
//
// No need for definitely assigned check for these guys
//
if ((flags & (Flags.Constant | Flags.ReadonlyMask | Flags.CompilerGenerated)) != 0)
return;
VariableInfo = new VariableInfo (this, bc.FlowOffset);
bc.FlowOffset += VariableInfo.Length;
}
//
// Mark the variables as referenced in the user code
//
public void SetIsUsed ()
{
flags |= Flags.Used;
}
public void SetHasAddressTaken ()
{
flags |= (Flags.AddressTaken | Flags.Used);
}
public override string ToString ()
{
return string.Format ("LocalInfo ({0},{1},{2},{3})", name, type, VariableInfo, Location);
}
}
/// <summary>
/// Block represents a C# block.
/// </summary>
///
/// <remarks>
/// This class is used in a number of places: either to represent
/// explicit blocks that the programmer places or implicit blocks.
///
/// Implicit blocks are used as labels or to introduce variable
/// declarations.
///
/// Top-level blocks derive from Block, and they are called ToplevelBlock
/// they contain extra information that is not necessary on normal blocks.
/// </remarks>
public class Block : Statement {
[Flags]
public enum Flags
{
Unchecked = 1,
HasRet = 8,
Unsafe = 16,
HasCapturedVariable = 64,
HasCapturedThis = 1 << 7,
IsExpressionTree = 1 << 8,
CompilerGenerated = 1 << 9,
HasAsyncModifier = 1 << 10,
Resolved = 1 << 11,
YieldBlock = 1 << 12,
AwaitBlock = 1 << 13,
Iterator = 1 << 14
}
public Block Parent;
public Location StartLocation;
public Location EndLocation;
public ExplicitBlock Explicit;
public ParametersBlock ParametersBlock;
protected Flags flags;
//
// The statements in this block
//
protected List<Statement> statements;
protected List<Statement> scope_initializers;
int? resolving_init_idx;
Block original;
#if DEBUG
static int id;
public int ID = id++;
static int clone_id_counter;
int clone_id;
#endif
// int assignable_slots;
public Block (Block parent, Location start, Location end)
: this (parent, 0, start, end)
{
}
public Block (Block parent, Flags flags, Location start, Location end)
{
if (parent != null) {
// the appropriate constructors will fixup these fields
ParametersBlock = parent.ParametersBlock;
Explicit = parent.Explicit;
}
this.Parent = parent;
this.flags = flags;
this.StartLocation = start;
this.EndLocation = end;
this.loc = start;
statements = new List<Statement> (4);
this.original = this;
}
#region Properties
public bool HasUnreachableClosingBrace {
get {
return (flags & Flags.HasRet) != 0;
}
set {
flags = value ? flags | Flags.HasRet : flags & ~Flags.HasRet;
}
}
public Block Original {
get {
return original;
}
protected set {
original = value;
}
}
public bool IsCompilerGenerated {
get { return (flags & Flags.CompilerGenerated) != 0; }
set { flags = value ? flags | Flags.CompilerGenerated : flags & ~Flags.CompilerGenerated; }
}
public bool Unchecked {
get { return (flags & Flags.Unchecked) != 0; }
set { flags = value ? flags | Flags.Unchecked : flags & ~Flags.Unchecked; }
}
public bool Unsafe {
get { return (flags & Flags.Unsafe) != 0; }
set { flags |= Flags.Unsafe; }
}
public List<Statement> Statements {
get { return statements; }
}
#endregion
public void SetEndLocation (Location loc)
{
EndLocation = loc;
}
public void AddLabel (LabeledStatement target)
{
ParametersBlock.TopBlock.AddLabel (target.Name, target);
}
public void AddLocalName (LocalVariable li)
{
AddLocalName (li.Name, li);
}
public void AddLocalName (string name, INamedBlockVariable li)
{
ParametersBlock.TopBlock.AddLocalName (name, li, false);
}
public virtual void Error_AlreadyDeclared (string name, INamedBlockVariable variable, string reason)
{
if (reason == null) {
Error_AlreadyDeclared (name, variable);
return;
}
ParametersBlock.TopBlock.Report.Error (136, variable.Location,
"A local variable named `{0}' cannot be declared in this scope because it would give a different meaning " +
"to `{0}', which is already used in a `{1}' scope to denote something else",
name, reason);
}
public virtual void Error_AlreadyDeclared (string name, INamedBlockVariable variable)
{
var pi = variable as ParametersBlock.ParameterInfo;
if (pi != null) {
pi.Parameter.Error_DuplicateName (ParametersBlock.TopBlock.Report);
} else {
ParametersBlock.TopBlock.Report.Error (128, variable.Location,
"A local variable named `{0}' is already defined in this scope", name);
}
}
public virtual void Error_AlreadyDeclaredTypeParameter (string name, Location loc)
{
ParametersBlock.TopBlock.Report.Error (412, loc,
"The type parameter name `{0}' is the same as local variable or parameter name",
name);
}
//
// It should be used by expressions which require to
// register a statement during resolve process.
//
public void AddScopeStatement (Statement s)
{
if (scope_initializers == null)
scope_initializers = new List<Statement> ();
//
// Simple recursive helper, when resolve scope initializer another
// new scope initializer can be added, this ensures it's initialized
// before existing one. For now this can happen with expression trees
// in base ctor initializer only
//
if (resolving_init_idx.HasValue) {
scope_initializers.Insert (resolving_init_idx.Value, s);
++resolving_init_idx;
} else {
scope_initializers.Add (s);
}
}
public void InsertStatement (int index, Statement s)
{
statements.Insert (index, s);
}
public void AddStatement (Statement s)
{
statements.Add (s);
}
public int AssignableSlots {
get {
// FIXME: HACK, we don't know the block available variables count now, so set this high enough
return 4096;
// return assignable_slots;
}
}
public LabeledStatement LookupLabel (string name)
{
return ParametersBlock.TopBlock.GetLabel (name, this);
}
public override bool Resolve (BlockContext ec)
{
if ((flags & Flags.Resolved) != 0)
return true;
Block prev_block = ec.CurrentBlock;
bool ok = true;
bool unreachable = ec.IsUnreachable;
bool prev_unreachable = unreachable;
ec.CurrentBlock = this;
ec.StartFlowBranching (this);
//
// Compiler generated scope statements
//
if (scope_initializers != null) {
for (resolving_init_idx = 0; resolving_init_idx < scope_initializers.Count; ++resolving_init_idx) {
scope_initializers[resolving_init_idx.Value].Resolve (ec);
}
resolving_init_idx = null;
}
//
// This flag is used to notate nested statements as unreachable from the beginning of this block.
// For the purposes of this resolution, it doesn't matter that the whole block is unreachable
// from the beginning of the function. The outer Resolve() that detected the unreachability is
// responsible for handling the situation.
//
int statement_count = statements.Count;
for (int ix = 0; ix < statement_count; ix++){
Statement s = statements [ix];
//
// Warn if we detect unreachable code.
//
if (unreachable) {
if (s is EmptyStatement)
continue;
if (!ec.UnreachableReported && !(s is LabeledStatement) && !(s is SwitchLabel)) {
ec.Report.Warning (162, 2, s.loc, "Unreachable code detected");
ec.UnreachableReported = true;
}
}
//
// Note that we're not using ResolveUnreachable() for unreachable
// statements here. ResolveUnreachable() creates a temporary
// flow branching and kills it afterwards. This leads to problems
// if you have two unreachable statements where the first one
// assigns a variable and the second one tries to access it.
//
if (!s.Resolve (ec)) {
ok = false;
if (!ec.IsInProbingMode)
statements [ix] = new EmptyStatement (s.loc);
continue;
}
if (unreachable && !(s is LabeledStatement) && !(s is SwitchLabel) && !(s is Block))
statements [ix] = new EmptyStatement (s.loc);
unreachable = ec.CurrentBranching.CurrentUsageVector.IsUnreachable;
if (unreachable) {
ec.IsUnreachable = true;
} else if (ec.IsUnreachable)
ec.IsUnreachable = false;
}
if (unreachable != prev_unreachable) {
ec.IsUnreachable = prev_unreachable;
ec.UnreachableReported = false;
}
while (ec.CurrentBranching is FlowBranchingLabeled)
ec.EndFlowBranching ();
bool flow_unreachable = ec.EndFlowBranching ();
ec.CurrentBlock = prev_block;
if (flow_unreachable)
flags |= Flags.HasRet;
// If we're a non-static `struct' constructor which doesn't have an
// initializer, then we must initialize all of the struct's fields.
if (this == ParametersBlock.TopBlock && !ParametersBlock.TopBlock.IsThisAssigned (ec) && !flow_unreachable)
ok = false;
flags |= Flags.Resolved;
return ok;
}
public override bool ResolveUnreachable (BlockContext ec, bool warn)
{
bool unreachable = false;
if (warn && !ec.UnreachableReported) {
ec.UnreachableReported = true;
unreachable = true;
ec.Report.Warning (162, 2, loc, "Unreachable code detected");
}
var fb = ec.StartFlowBranching (FlowBranching.BranchingType.Block, loc);
fb.CurrentUsageVector.IsUnreachable = true;
bool ok = Resolve (ec);
ec.KillFlowBranching ();
if (unreachable)
ec.UnreachableReported = false;
return ok;
}
protected override void DoEmit (EmitContext ec)
{
for (int ix = 0; ix < statements.Count; ix++){
statements [ix].Emit (ec);
}
}
public override void Emit (EmitContext ec)
{
if (scope_initializers != null)
EmitScopeInitializers (ec);
DoEmit (ec);
}
protected void EmitScopeInitializers (EmitContext ec)
{
foreach (Statement s in scope_initializers)
s.Emit (ec);
}
#if DEBUG
public override string ToString ()
{
return String.Format ("{0} ({1}:{2})", GetType (), ID, StartLocation);
}
#endif
protected override void CloneTo (CloneContext clonectx, Statement t)
{
Block target = (Block) t;
#if DEBUG
target.clone_id = clone_id_counter++;
#endif
clonectx.AddBlockMap (this, target);
if (original != this)
clonectx.AddBlockMap (original, target);
target.ParametersBlock = (ParametersBlock) (ParametersBlock == this ? target : clonectx.RemapBlockCopy (ParametersBlock));
target.Explicit = (ExplicitBlock) (Explicit == this ? target : clonectx.LookupBlock (Explicit));
if (Parent != null)
target.Parent = clonectx.RemapBlockCopy (Parent);
target.statements = new List<Statement> (statements.Count);
foreach (Statement s in statements)
target.statements.Add (s.Clone (clonectx));
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
public class ExplicitBlock : Block
{
protected AnonymousMethodStorey am_storey;
public ExplicitBlock (Block parent, Location start, Location end)
: this (parent, (Flags) 0, start, end)
{
}
public ExplicitBlock (Block parent, Flags flags, Location start, Location end)
: base (parent, flags, start, end)
{
this.Explicit = this;
}
#region Properties
public AnonymousMethodStorey AnonymousMethodStorey {
get {
return am_storey;
}
}
public bool HasAwait {
get {
return (flags & Flags.AwaitBlock) != 0;
}
}
public bool HasCapturedThis {
set {
flags = value ? flags | Flags.HasCapturedThis : flags & ~Flags.HasCapturedThis;
}
get {
return (flags & Flags.HasCapturedThis) != 0;
}
}
//
// Used to indicate that the block has reference to parent
// block and cannot be made static when defining anonymous method
//
public bool HasCapturedVariable {
set {
flags = value ? flags | Flags.HasCapturedVariable : flags & ~Flags.HasCapturedVariable;
}
get {
return (flags & Flags.HasCapturedVariable) != 0;
}
}
public bool HasYield {
get {
return (flags & Flags.YieldBlock) != 0;
}
}
#endregion
//
// Creates anonymous method storey in current block
//
public AnonymousMethodStorey CreateAnonymousMethodStorey (ResolveContext ec)
{
//
// Return same story for iterator and async blocks unless we are
// in nested anonymous method
//
if (ec.CurrentAnonymousMethod is StateMachineInitializer && ParametersBlock.Original == ec.CurrentAnonymousMethod.Block.Original)
return ec.CurrentAnonymousMethod.Storey;
if (am_storey == null) {
MemberBase mc = ec.MemberContext as MemberBase;
//
// Creates anonymous method storey for this block
//
am_storey = new AnonymousMethodStorey (this, ec.CurrentMemberDefinition.Parent.PartialContainer, mc, ec.CurrentTypeParameters, "AnonStorey", MemberKind.Class);
}
return am_storey;
}
public override void Emit (EmitContext ec)
{
if (am_storey != null) {
DefineStoreyContainer (ec, am_storey);
am_storey.EmitStoreyInstantiation (ec, this);
}
if (scope_initializers != null)
EmitScopeInitializers (ec);
if (ec.EmitAccurateDebugInfo && !IsCompilerGenerated && ec.Mark (StartLocation)) {
ec.Emit (OpCodes.Nop);
}
if (Parent != null)
ec.BeginScope ();
DoEmit (ec);
if (Parent != null)
ec.EndScope ();
if (ec.EmitAccurateDebugInfo && !HasUnreachableClosingBrace && !IsCompilerGenerated && ec.Mark (EndLocation)) {
ec.Emit (OpCodes.Nop);
}
}
protected void DefineStoreyContainer (EmitContext ec, AnonymousMethodStorey storey)
{
if (ec.CurrentAnonymousMethod != null && ec.CurrentAnonymousMethod.Storey != null) {
storey.SetNestedStoryParent (ec.CurrentAnonymousMethod.Storey);
storey.Mutator = ec.CurrentAnonymousMethod.Storey.Mutator;
}
//
// Creates anonymous method storey
//
storey.CreateContainer ();
storey.DefineContainer ();
if (Original.Explicit.HasCapturedThis && Original.ParametersBlock.TopBlock.ThisReferencesFromChildrenBlock != null) {
//
// Only first storey in path will hold this reference. All children blocks will
// reference it indirectly using $ref field
//
for (Block b = Original.Explicit; b != null; b = b.Parent) {
if (b.Parent != null) {
var s = b.Parent.Explicit.AnonymousMethodStorey;
if (s != null) {
storey.HoistedThis = s.HoistedThis;
break;
}
}
if (b.Explicit == b.Explicit.ParametersBlock && b.Explicit.ParametersBlock.StateMachine != null) {
storey.HoistedThis = b.Explicit.ParametersBlock.StateMachine.HoistedThis;
if (storey.HoistedThis != null)
break;
}
}
//
// We are the first storey on path and 'this' has to be hoisted
//
if (storey.HoistedThis == null) {
foreach (ExplicitBlock ref_block in Original.ParametersBlock.TopBlock.ThisReferencesFromChildrenBlock) {
//
// ThisReferencesFromChildrenBlock holds all reference even if they
// are not on this path. It saves some memory otherwise it'd have to
// be in every explicit block. We run this check to see if the reference
// is valid for this storey
//
Block block_on_path = ref_block;
for (; block_on_path != null && block_on_path != Original; block_on_path = block_on_path.Parent);
if (block_on_path == null)
continue;
if (storey.HoistedThis == null) {
storey.AddCapturedThisField (ec);
}
for (ExplicitBlock b = ref_block; b.AnonymousMethodStorey != storey; b = b.Parent.Explicit) {
if (b.AnonymousMethodStorey != null) {
b.AnonymousMethodStorey.AddParentStoreyReference (ec, storey);
b.AnonymousMethodStorey.HoistedThis = storey.HoistedThis;
//
// Stop propagation inside same top block
//
if (b.ParametersBlock == ParametersBlock.Original)
break;
b = b.ParametersBlock;
}
var pb = b as ParametersBlock;
if (pb != null && pb.StateMachine != null) {
if (pb.StateMachine == storey)
break;
//
// If we are state machine with no parent we can hook into we don't
// add reference but capture this directly
//
ExplicitBlock parent_storey_block = pb;
while (parent_storey_block.Parent != null) {
parent_storey_block = parent_storey_block.Parent.Explicit;
if (parent_storey_block.AnonymousMethodStorey != null) {
break;
}
}
if (parent_storey_block.AnonymousMethodStorey == null) {
pb.StateMachine.AddCapturedThisField (ec);
b.HasCapturedThis = true;
continue;
}
pb.StateMachine.AddParentStoreyReference (ec, storey);
}
b.HasCapturedVariable = true;
}
}
}
}
var ref_blocks = storey.ReferencesFromChildrenBlock;
if (ref_blocks != null) {
foreach (ExplicitBlock ref_block in ref_blocks) {
for (ExplicitBlock b = ref_block; b.AnonymousMethodStorey != storey; b = b.Parent.Explicit) {
if (b.AnonymousMethodStorey != null) {
b.AnonymousMethodStorey.AddParentStoreyReference (ec, storey);
//
// Stop propagation inside same top block
//
if (b.ParametersBlock == ParametersBlock.Original)
break;
b = b.ParametersBlock;
}
var pb = b as ParametersBlock;
if (pb != null && pb.StateMachine != null) {
if (pb.StateMachine == storey)
break;
pb.StateMachine.AddParentStoreyReference (ec, storey);
}
b.HasCapturedVariable = true;
}
}
}
storey.Define ();
storey.PrepareEmit ();
storey.Parent.PartialContainer.AddCompilerGeneratedClass (storey);
}
public void RegisterAsyncAwait ()
{
var block = this;
while ((block.flags & Flags.AwaitBlock) == 0) {
block.flags |= Flags.AwaitBlock;
if (block is ParametersBlock)
return;
block = block.Parent.Explicit;
}
}
public void RegisterIteratorYield ()
{
ParametersBlock.TopBlock.IsIterator = true;
var block = this;
while ((block.flags & Flags.YieldBlock) == 0) {
block.flags |= Flags.YieldBlock;
if (block.Parent == null)
return;
block = block.Parent.Explicit;
}
}
public void WrapIntoDestructor (TryFinally tf, ExplicitBlock tryBlock)
{
tryBlock.statements = statements;
statements = new List<Statement> (1);
statements.Add (tf);
}
}
//
// ParametersBlock was introduced to support anonymous methods
// and lambda expressions
//
public class ParametersBlock : ExplicitBlock
{
public class ParameterInfo : INamedBlockVariable
{
readonly ParametersBlock block;
readonly int index;
public VariableInfo VariableInfo;
bool is_locked;
public ParameterInfo (ParametersBlock block, int index)
{
this.block = block;
this.index = index;
}
#region Properties
public ParametersBlock Block {
get {
return block;
}
}
Block INamedBlockVariable.Block {
get {
return block;
}
}
public bool IsDeclared {
get {
return true;
}
}
public bool IsParameter {
get {
return true;
}
}
public bool IsLocked {
get {
return is_locked;
}
set {
is_locked = value;
}
}
public Location Location {
get {
return Parameter.Location;
}
}
public Parameter Parameter {
get {
return block.Parameters [index];
}
}
public TypeSpec ParameterType {
get {
return Parameter.Type;
}
}
#endregion
public Expression CreateReferenceExpression (ResolveContext rc, Location loc)
{
return new ParameterReference (this, loc);
}
}
//
// Block is converted into an expression
//
sealed class BlockScopeExpression : Expression
{
Expression child;
readonly ParametersBlock block;
public BlockScopeExpression (Expression child, ParametersBlock block)
{
this.child = child;
this.block = block;
}
public override bool ContainsEmitWithAwait ()
{
return child.ContainsEmitWithAwait ();
}
public override Expression CreateExpressionTree (ResolveContext ec)
{
throw new NotSupportedException ();
}
protected override Expression DoResolve (ResolveContext ec)
{
if (child == null)
return null;
child = child.Resolve (ec);
if (child == null)
return null;
eclass = child.eclass;
type = child.Type;
return this;
}
public override void Emit (EmitContext ec)
{
block.EmitScopeInitializers (ec);
child.Emit (ec);
}
}
protected ParametersCompiled parameters;
protected ParameterInfo[] parameter_info;
bool resolved;
protected bool unreachable;
protected ToplevelBlock top_block;
protected StateMachine state_machine;
public ParametersBlock (Block parent, ParametersCompiled parameters, Location start)
: base (parent, 0, start, start)
{
if (parameters == null)
throw new ArgumentNullException ("parameters");
this.parameters = parameters;
ParametersBlock = this;
flags |= (parent.ParametersBlock.flags & (Flags.YieldBlock | Flags.AwaitBlock));
this.top_block = parent.ParametersBlock.top_block;
ProcessParameters ();
}
protected ParametersBlock (ParametersCompiled parameters, Location start)
: base (null, 0, start, start)
{
if (parameters == null)
throw new ArgumentNullException ("parameters");
this.parameters = parameters;
ParametersBlock = this;
}
//
// It's supposed to be used by method body implementation of anonymous methods
//
protected ParametersBlock (ParametersBlock source, ParametersCompiled parameters)
: base (null, 0, source.StartLocation, source.EndLocation)
{
this.parameters = parameters;
this.statements = source.statements;
this.scope_initializers = source.scope_initializers;
this.resolved = true;
this.unreachable = source.unreachable;
this.am_storey = source.am_storey;
this.state_machine = source.state_machine;
ParametersBlock = this;
//
// Overwrite original for comparison purposes when linking cross references
// between anonymous methods
//
Original = source.Original;
}
#region Properties
public bool IsAsync {
get {
return (flags & Flags.HasAsyncModifier) != 0;
}
set {
flags = value ? flags | Flags.HasAsyncModifier : flags & ~Flags.HasAsyncModifier;
}
}
//
// Block has been converted to expression tree
//
public bool IsExpressionTree {
get {
return (flags & Flags.IsExpressionTree) != 0;
}
}
//
// The parameters for the block.
//
public ParametersCompiled Parameters {
get {
return parameters;
}
}
public StateMachine StateMachine {
get {
return state_machine;
}
}
public ToplevelBlock TopBlock {
get {
return top_block;
}
}
public bool Resolved {
get {
return (flags & Flags.Resolved) != 0;
}
}
public int TemporaryLocalsCount { get; set; }
#endregion
// <summary>
// Check whether all `out' parameters have been assigned.
// </summary>
public void CheckOutParameters (FlowBranching.UsageVector vector)
{
if (vector.IsUnreachable)
return;
int n = parameter_info == null ? 0 : parameter_info.Length;
for (int i = 0; i < n; i++) {
VariableInfo var = parameter_info[i].VariableInfo;
if (var == null)
continue;
if (vector.IsAssigned (var, false))
continue;
var p = parameter_info[i].Parameter;
TopBlock.Report.Error (177, p.Location,
"The out parameter `{0}' must be assigned to before control leaves the current method",
p.Name);
}
}
public override Expression CreateExpressionTree (ResolveContext ec)
{
if (statements.Count == 1) {
Expression expr = ((Statement) statements[0]).CreateExpressionTree (ec);
if (scope_initializers != null)
expr = new BlockScopeExpression (expr, this);
return expr;
}
return base.CreateExpressionTree (ec);
}
public override void Emit (EmitContext ec)
{
if (state_machine != null && state_machine.OriginalSourceBlock != this) {
DefineStoreyContainer (ec, state_machine);
state_machine.EmitStoreyInstantiation (ec, this);
}
base.Emit (ec);
}
public void EmitEmbedded (EmitContext ec)
{
if (state_machine != null && state_machine.OriginalSourceBlock != this) {
DefineStoreyContainer (ec, state_machine);
state_machine.EmitStoreyInstantiation (ec, this);
}
base.Emit (ec);
}
public ParameterInfo GetParameterInfo (Parameter p)
{
for (int i = 0; i < parameters.Count; ++i) {
if (parameters[i] == p)
return parameter_info[i];
}
throw new ArgumentException ("Invalid parameter");
}
public ParameterReference GetParameterReference (int index, Location loc)
{
return new ParameterReference (parameter_info[index], loc);
}
public Statement PerformClone ()
{
CloneContext clonectx = new CloneContext ();
return Clone (clonectx);
}
protected void ProcessParameters ()
{
if (parameters.Count == 0)
return;
parameter_info = new ParameterInfo[parameters.Count];
for (int i = 0; i < parameter_info.Length; ++i) {
var p = parameters.FixedParameters[i];
if (p == null)
continue;
// TODO: Should use Parameter only and more block there
parameter_info[i] = new ParameterInfo (this, i);
if (p.Name != null)
AddLocalName (p.Name, parameter_info[i]);
}
}
public bool Resolve (FlowBranching parent, BlockContext rc, IMethodData md)
{
if (resolved)
return true;
resolved = true;
if (rc.HasSet (ResolveContext.Options.ExpressionTreeConversion))
flags |= Flags.IsExpressionTree;
try {
ResolveMeta (rc);
using (rc.With (ResolveContext.Options.DoFlowAnalysis, true)) {
FlowBranchingToplevel top_level = rc.StartFlowBranching (this, parent);
if (!Resolve (rc))
return false;
unreachable = top_level.End ();
}
} catch (Exception e) {
if (e is CompletionResult || rc.Report.IsDisabled || e is FatalException)
throw;
if (rc.CurrentBlock != null) {
rc.Report.Error (584, rc.CurrentBlock.StartLocation, "Internal compiler error: {0}", e.Message);
} else {
rc.Report.Error (587, "Internal compiler error: {0}", e.Message);
}
if (rc.Module.Compiler.Settings.DebugFlags > 0)
throw;
}
if (rc.ReturnType.Kind != MemberKind.Void && !unreachable) {
if (rc.CurrentAnonymousMethod == null) {
// FIXME: Missing FlowAnalysis for generated iterator MoveNext method
if (md is StateMachineMethod) {
unreachable = true;
} else {
rc.Report.Error (161, md.Location, "`{0}': not all code paths return a value", md.GetSignatureForError ());
return false;
}
} else {
//
// If an asynchronous body of F is either an expression classified as nothing, or a
// statement block where no return statements have expressions, the inferred return type is Task
//
if (IsAsync) {
var am = rc.CurrentAnonymousMethod as AnonymousMethodBody;
if (am != null && am.ReturnTypeInference != null && !am.ReturnTypeInference.HasBounds (0)) {
am.ReturnTypeInference = null;
am.ReturnType = rc.Module.PredefinedTypes.Task.TypeSpec;
return true;
}
}
rc.Report.Error (1643, rc.CurrentAnonymousMethod.Location, "Not all code paths return a value in anonymous method of type `{0}'",
rc.CurrentAnonymousMethod.GetSignatureForError ());
return false;
}
}
return true;
}
void ResolveMeta (BlockContext ec)
{
int orig_count = parameters.Count;
for (int i = 0; i < orig_count; ++i) {
Parameter.Modifier mod = parameters.FixedParameters[i].ModFlags;
if ((mod & Parameter.Modifier.OUT) == 0)
continue;
VariableInfo vi = new VariableInfo (parameters, i, ec.FlowOffset);
parameter_info[i].VariableInfo = vi;
ec.FlowOffset += vi.Length;
}
}
public ToplevelBlock ConvertToIterator (IMethodData method, TypeDefinition host, TypeSpec iterator_type, bool is_enumerable)
{
var iterator = new Iterator (this, method, host, iterator_type, is_enumerable);
var stateMachine = new IteratorStorey (iterator);
state_machine = stateMachine;
iterator.SetStateMachine (stateMachine);
var tlb = new ToplevelBlock (host.Compiler, Parameters, Location.Null);
tlb.Original = this;
tlb.IsCompilerGenerated = true;
tlb.state_machine = stateMachine;
tlb.AddStatement (new Return (iterator, iterator.Location));
return tlb;
}
public ParametersBlock ConvertToAsyncTask (IMemberContext context, TypeDefinition host, ParametersCompiled parameters, TypeSpec returnType, TypeSpec delegateType, Location loc)
{
for (int i = 0; i < parameters.Count; i++) {
Parameter p = parameters[i];
Parameter.Modifier mod = p.ModFlags;
if ((mod & Parameter.Modifier.RefOutMask) != 0) {
host.Compiler.Report.Error (1988, p.Location,
"Async methods cannot have ref or out parameters");
return this;
}
if (p is ArglistParameter) {
host.Compiler.Report.Error (4006, p.Location,
"__arglist is not allowed in parameter list of async methods");
return this;
}
if (parameters.Types[i].IsPointer) {
host.Compiler.Report.Error (4005, p.Location,
"Async methods cannot have unsafe parameters");
return this;
}
}
if (!HasAwait) {
host.Compiler.Report.Warning (1998, 1, loc,
"Async block lacks `await' operator and will run synchronously");
}
var block_type = host.Module.Compiler.BuiltinTypes.Void;
var initializer = new AsyncInitializer (this, host, block_type);
initializer.Type = block_type;
initializer.DelegateType = delegateType;
var stateMachine = new AsyncTaskStorey (this, context, initializer, returnType);
state_machine = stateMachine;
initializer.SetStateMachine (stateMachine);
var b = this is ToplevelBlock ?
new ToplevelBlock (host.Compiler, Parameters, Location.Null) :
new ParametersBlock (Parent, parameters, Location.Null) {
IsAsync = true,
};
b.Original = this;
b.IsCompilerGenerated = true;
b.state_machine = stateMachine;
b.AddStatement (new StatementExpression (initializer));
return b;
}
}
//
//
//
public class ToplevelBlock : ParametersBlock
{
LocalVariable this_variable;
CompilerContext compiler;
Dictionary<string, object> names;
Dictionary<string, object> labels;
List<ExplicitBlock> this_references;
public ToplevelBlock (CompilerContext ctx, Location loc)
: this (ctx, ParametersCompiled.EmptyReadOnlyParameters, loc)
{
}
public ToplevelBlock (CompilerContext ctx, ParametersCompiled parameters, Location start)
: base (parameters, start)
{
this.compiler = ctx;
top_block = this;
flags |= Flags.HasRet;
ProcessParameters ();
}
//
// Recreates a top level block from parameters block. Used for
// compiler generated methods where the original block comes from
// explicit child block. This works for already resolved blocks
// only to ensure we resolve them in the correct flow order
//
public ToplevelBlock (ParametersBlock source, ParametersCompiled parameters)
: base (source, parameters)
{
this.compiler = source.TopBlock.compiler;
top_block = this;
flags |= Flags.HasRet;
}
public bool IsIterator {
get {
return (flags & Flags.Iterator) != 0;
}
set {
flags = value ? flags | Flags.Iterator : flags & ~Flags.Iterator;
}
}
public Report Report {
get {
return compiler.Report;
}
}
//
// Used by anonymous blocks to track references of `this' variable
//
public List<ExplicitBlock> ThisReferencesFromChildrenBlock {
get {
return this_references;
}
}
//
// Returns the "this" instance variable of this block.
// See AddThisVariable() for more information.
//
public LocalVariable ThisVariable {
get {
return this_variable;
}
}
public void AddLocalName (string name, INamedBlockVariable li, bool ignoreChildrenBlocks)
{
if (names == null)
names = new Dictionary<string, object> ();
object value;
if (!names.TryGetValue (name, out value)) {
names.Add (name, li);
return;
}
INamedBlockVariable existing = value as INamedBlockVariable;
List<INamedBlockVariable> existing_list;
if (existing != null) {
existing_list = new List<INamedBlockVariable> ();
existing_list.Add (existing);
names[name] = existing_list;
} else {
existing_list = (List<INamedBlockVariable>) value;
}
//
// A collision checking between local names
//
var variable_block = li.Block.Explicit;
for (int i = 0; i < existing_list.Count; ++i) {
existing = existing_list[i];
Block b = existing.Block.Explicit;
// Collision at same level
if (variable_block == b) {
li.Block.Error_AlreadyDeclared (name, li);
break;
}
// Collision with parent
Block parent = variable_block;
while ((parent = parent.Parent) != null) {
if (parent == b) {
li.Block.Error_AlreadyDeclared (name, li, "parent or current");
i = existing_list.Count;
break;
}
}
if (!ignoreChildrenBlocks && variable_block.Parent != b.Parent) {
// Collision with children
while ((b = b.Parent) != null) {
if (variable_block == b) {
li.Block.Error_AlreadyDeclared (name, li, "child");
i = existing_list.Count;
break;
}
}
}
}
existing_list.Add (li);
}
public void AddLabel (string name, LabeledStatement label)
{
if (labels == null)
labels = new Dictionary<string, object> ();
object value;
if (!labels.TryGetValue (name, out value)) {
labels.Add (name, label);
return;
}
LabeledStatement existing = value as LabeledStatement;
List<LabeledStatement> existing_list;
if (existing != null) {
existing_list = new List<LabeledStatement> ();
existing_list.Add (existing);
labels[name] = existing_list;
} else {
existing_list = (List<LabeledStatement>) value;
}
//
// A collision checking between labels
//
for (int i = 0; i < existing_list.Count; ++i) {
existing = existing_list[i];
Block b = existing.Block;
// Collision at same level
if (label.Block == b) {
Report.SymbolRelatedToPreviousError (existing.loc, name);
Report.Error (140, label.loc, "The label `{0}' is a duplicate", name);
break;
}
// Collision with parent
b = label.Block;
while ((b = b.Parent) != null) {
if (existing.Block == b) {
Report.Error (158, label.loc,
"The label `{0}' shadows another label by the same name in a contained scope", name);
i = existing_list.Count;
break;
}
}
// Collision with with children
b = existing.Block;
while ((b = b.Parent) != null) {
if (label.Block == b) {
Report.Error (158, label.loc,
"The label `{0}' shadows another label by the same name in a contained scope", name);
i = existing_list.Count;
break;
}
}
}
existing_list.Add (label);
}
public void AddThisReferenceFromChildrenBlock (ExplicitBlock block)
{
if (this_references == null)
this_references = new List<ExplicitBlock> ();
if (!this_references.Contains (block))
this_references.Add (block);
}
public void RemoveThisReferenceFromChildrenBlock (ExplicitBlock block)
{
this_references.Remove (block);
}
//
// Creates an arguments set from all parameters, useful for method proxy calls
//
public Arguments GetAllParametersArguments ()
{
int count = parameters.Count;
Arguments args = new Arguments (count);
for (int i = 0; i < count; ++i) {
var arg_expr = GetParameterReference (i, parameter_info[i].Location);
args.Add (new Argument (arg_expr));
}
return args;
}
//
// Lookup inside a block, the returned value can represent 3 states
//
// true+variable: A local name was found and it's valid
// false+variable: A local name was found in a child block only
// false+null: No local name was found
//
public bool GetLocalName (string name, Block block, ref INamedBlockVariable variable)
{
if (names == null)
return false;
object value;
if (!names.TryGetValue (name, out value))
return false;
variable = value as INamedBlockVariable;
Block b = block;
if (variable != null) {
do {
if (variable.Block == b.Original)
return true;
b = b.Parent;
} while (b != null);
b = variable.Block;
do {
if (block == b)
return false;
b = b.Parent;
} while (b != null);
} else {
List<INamedBlockVariable> list = (List<INamedBlockVariable>) value;
for (int i = 0; i < list.Count; ++i) {
variable = list[i];
do {
if (variable.Block == b.Original)
return true;
b = b.Parent;
} while (b != null);
b = variable.Block;
do {
if (block == b)
return false;
b = b.Parent;
} while (b != null);
b = block;
}
}
variable = null;
return false;
}
public LabeledStatement GetLabel (string name, Block block)
{
if (labels == null)
return null;
object value;
if (!labels.TryGetValue (name, out value)) {
return null;
}
var label = value as LabeledStatement;
Block b = block;
if (label != null) {
if (label.Block == b.Original)
return label;
} else {
List<LabeledStatement> list = (List<LabeledStatement>) value;
for (int i = 0; i < list.Count; ++i) {
label = list[i];
if (label.Block == b.Original)
return label;
}
}
return null;
}
// <summary>
// This is used by non-static `struct' constructors which do not have an
// initializer - in this case, the constructor must initialize all of the
// struct's fields. To do this, we add a "this" variable and use the flow
// analysis code to ensure that it's been fully initialized before control
// leaves the constructor.
// </summary>
public void AddThisVariable (BlockContext bc)
{
if (this_variable != null)
throw new InternalErrorException (StartLocation.ToString ());
this_variable = new LocalVariable (this, "this", LocalVariable.Flags.IsThis | LocalVariable.Flags.Used, StartLocation);
this_variable.Type = bc.CurrentType;
this_variable.PrepareForFlowAnalysis (bc);
}
public bool IsThisAssigned (BlockContext ec)
{
return this_variable == null || this_variable.IsThisAssigned (ec, this);
}
public override void Emit (EmitContext ec)
{
if (Report.Errors > 0)
return;
try {
if (IsCompilerGenerated) {
using (ec.With (BuilderContext.Options.OmitDebugInfo, true)) {
base.Emit (ec);
}
} else {
base.Emit (ec);
}
//
// If `HasReturnLabel' is set, then we already emitted a
// jump to the end of the method, so we must emit a `ret'
// there.
//
// Unfortunately, System.Reflection.Emit automatically emits
// a leave to the end of a finally block. This is a problem
// if no code is following the try/finally block since we may
// jump to a point after the end of the method.
// As a workaround, we're always creating a return label in
// this case.
//
if (ec.HasReturnLabel || !unreachable) {
if (ec.HasReturnLabel)
ec.MarkLabel (ec.ReturnLabel);
if (ec.EmitAccurateDebugInfo && !IsCompilerGenerated)
ec.Mark (EndLocation);
if (ec.ReturnType.Kind != MemberKind.Void)
ec.Emit (OpCodes.Ldloc, ec.TemporaryReturn ());
ec.Emit (OpCodes.Ret);
}
} catch (Exception e) {
throw new InternalErrorException (e, StartLocation);
}
}
}
public class SwitchLabel : Statement
{
Expression label;
Constant converted;
Label? il_label;
//
// if expr == null, then it is the default case.
//
public SwitchLabel (Expression expr, Location l)
{
label = expr;
loc = l;
}
public bool IsDefault {
get {
return label == null;
}
}
public Expression Label {
get {
return label;
}
}
public Location Location {
get {
return loc;
}
}
public Constant Converted {
get {
return converted;
}
set {
converted = value;
}
}
public bool SectionStart { get; set; }
public Label GetILLabel (EmitContext ec)
{
if (il_label == null){
il_label = ec.DefineLabel ();
}
return il_label.Value;
}
protected override void DoEmit (EmitContext ec)
{
ec.MarkLabel (GetILLabel (ec));
}
public override bool Resolve (BlockContext bc)
{
if (ResolveAndReduce (bc))
bc.Switch.RegisterLabel (bc, this);
bc.CurrentBranching.CurrentUsageVector.ResetBarrier ();
return base.Resolve (bc);
}
//
// Resolves the expression, reduces it to a literal if possible
// and then converts it to the requested type.
//
bool ResolveAndReduce (ResolveContext rc)
{
if (IsDefault)
return true;
var c = label.ResolveLabelConstant (rc);
if (c == null)
return false;
if (rc.Switch.IsNullable && c is NullLiteral) {
converted = c;
return true;
}
converted = c.ImplicitConversionRequired (rc, rc.Switch.SwitchType, loc);
return converted != null;
}
public void Error_AlreadyOccurs (ResolveContext ec, SwitchLabel collision_with)
{
string label;
if (converted == null)
label = "default";
else
label = converted.GetValueAsLiteral ();
ec.Report.SymbolRelatedToPreviousError (collision_with.loc, null);
ec.Report.Error (152, loc, "The label `case {0}:' already occurs in this switch statement", label);
}
protected override void CloneTo (CloneContext clonectx, Statement target)
{
var t = (SwitchLabel) target;
if (label != null)
t.label = label.Clone (clonectx);
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
public class Switch : Statement
{
// structure used to hold blocks of keys while calculating table switch
sealed class LabelsRange : IComparable<LabelsRange>
{
public readonly long min;
public long max;
public readonly List<long> label_values;
public LabelsRange (long value)
{
min = max = value;
label_values = new List<long> ();
label_values.Add (value);
}
public LabelsRange (long min, long max, ICollection<long> values)
{
this.min = min;
this.max = max;
this.label_values = new List<long> (values);
}
public long Range {
get {
return max - min + 1;
}
}
public bool AddValue (long value)
{
var gap = value - min + 1;
// Ensure the range has > 50% occupancy
if (gap > 2 * (label_values.Count + 1) || gap <= 0)
return false;
max = value;
label_values.Add (value);
return true;
}
public int CompareTo (LabelsRange other)
{
int nLength = label_values.Count;
int nLengthOther = other.label_values.Count;
if (nLengthOther == nLength)
return (int) (other.min - min);
return nLength - nLengthOther;
}
}
sealed class DispatchStatement : Statement
{
readonly Switch body;
public DispatchStatement (Switch body)
{
this.body = body;
}
protected override void CloneTo (CloneContext clonectx, Statement target)
{
throw new NotImplementedException ();
}
protected override void DoEmit (EmitContext ec)
{
body.EmitDispatch (ec);
}
}
public Expression Expr;
//
// Mapping of all labels to their SwitchLabels
//
Dictionary<long, SwitchLabel> labels;
Dictionary<string, SwitchLabel> string_labels;
List<SwitchLabel> case_labels;
List<Tuple<GotoCase, Constant>> goto_cases;
/// <summary>
/// The governing switch type
/// </summary>
public TypeSpec SwitchType;
Expression new_expr;
SwitchLabel case_null;
SwitchLabel case_default;
Label defaultLabel, nullLabel;
VariableReference value;
ExpressionStatement string_dictionary;
FieldExpr switch_cache_field;
ExplicitBlock block;
//
// Nullable Types support
//
Nullable.Unwrap unwrap;
public Switch (Expression e, ExplicitBlock block, Location l)
{
Expr = e;
this.block = block;
loc = l;
}
public ExplicitBlock Block {
get {
return block;
}
}
public SwitchLabel DefaultLabel {
get {
return case_default;
}
}
public bool IsNullable {
get {
return unwrap != null;
}
}
//
// Determines the governing type for a switch. The returned
// expression might be the expression from the switch, or an
// expression that includes any potential conversions to
//
Expression SwitchGoverningType (ResolveContext ec, Expression expr)
{
switch (expr.Type.BuiltinType) {
case BuiltinTypeSpec.Type.Byte:
case BuiltinTypeSpec.Type.SByte:
case BuiltinTypeSpec.Type.UShort:
case BuiltinTypeSpec.Type.Short:
case BuiltinTypeSpec.Type.UInt:
case BuiltinTypeSpec.Type.Int:
case BuiltinTypeSpec.Type.ULong:
case BuiltinTypeSpec.Type.Long:
case BuiltinTypeSpec.Type.Char:
case BuiltinTypeSpec.Type.String:
case BuiltinTypeSpec.Type.Bool:
return expr;
}
if (expr.Type.IsEnum)
return expr;
//
// Try to find a *user* defined implicit conversion.
//
// If there is no implicit conversion, or if there are multiple
// conversions, we have to report an error
//
Expression converted = null;
foreach (TypeSpec tt in ec.BuiltinTypes.SwitchUserTypes) {
Expression e;
e = Convert.ImplicitUserConversion (ec, expr, tt, loc);
if (e == null)
continue;
//
// Ignore over-worked ImplicitUserConversions that do
// an implicit conversion in addition to the user conversion.
//
if (!(e is UserCast))
continue;
if (converted != null){
ec.Report.ExtraInformation (loc, "(Ambiguous implicit user defined conversion in previous ");
return null;
}
converted = e;
}
return converted;
}
public static TypeSpec[] CreateSwitchUserTypes (BuiltinTypes types)
{
// LAMESPEC: For some reason it does not contain bool which looks like csc bug
return new[] {
types.SByte,
types.Byte,
types.Short,
types.UShort,
types.Int,
types.UInt,
types.Long,
types.ULong,
types.Char,
types.String
};
}
public void RegisterLabel (ResolveContext rc, SwitchLabel sl)
{
case_labels.Add (sl);
if (sl.IsDefault) {
if (case_default != null) {
sl.Error_AlreadyOccurs (rc, case_default);
} else {
case_default = sl;
}
return;
}
try {
if (string_labels != null) {
string string_value = sl.Converted.GetValue () as string;
if (string_value == null)
case_null = sl;
else
string_labels.Add (string_value, sl);
} else {
if (sl.Converted is NullLiteral) {
case_null = sl;
} else {
labels.Add (sl.Converted.GetValueAsLong (), sl);
}
}
} catch (ArgumentException) {
if (string_labels != null)
sl.Error_AlreadyOccurs (rc, string_labels[(string) sl.Converted.GetValue ()]);
else
sl.Error_AlreadyOccurs (rc, labels[sl.Converted.GetValueAsLong ()]);
}
}
//
// This method emits code for a lookup-based switch statement (non-string)
// Basically it groups the cases into blocks that are at least half full,
// and then spits out individual lookup opcodes for each block.
// It emits the longest blocks first, and short blocks are just
// handled with direct compares.
//
void EmitTableSwitch (EmitContext ec, Expression val)
{
if (labels != null && labels.Count > 0) {
List<LabelsRange> ranges;
if (string_labels != null) {
// We have done all hard work for string already
// setup single range only
ranges = new List<LabelsRange> (1);
ranges.Add (new LabelsRange (0, labels.Count - 1, labels.Keys));
} else {
var element_keys = new long[labels.Count];
labels.Keys.CopyTo (element_keys, 0);
Array.Sort (element_keys);
//
// Build possible ranges of switch labes to reduce number
// of comparisons
//
ranges = new List<LabelsRange> (element_keys.Length);
var range = new LabelsRange (element_keys[0]);
ranges.Add (range);
for (int i = 1; i < element_keys.Length; ++i) {
var l = element_keys[i];
if (range.AddValue (l))
continue;
range = new LabelsRange (l);
ranges.Add (range);
}
// sort the blocks so we can tackle the largest ones first
ranges.Sort ();
}
Label lbl_default = defaultLabel;
TypeSpec compare_type = SwitchType.IsEnum ? EnumSpec.GetUnderlyingType (SwitchType) : SwitchType;
for (int range_index = ranges.Count - 1; range_index >= 0; --range_index) {
LabelsRange kb = ranges[range_index];
lbl_default = (range_index == 0) ? defaultLabel : ec.DefineLabel ();
// Optimize small ranges using simple equality check
if (kb.Range <= 2) {
foreach (var key in kb.label_values) {
SwitchLabel sl = labels[key];
if (sl == case_default || sl == case_null)
continue;
if (sl.Converted.IsZeroInteger) {
val.EmitBranchable (ec, sl.GetILLabel (ec), false);
} else {
val.Emit (ec);
sl.Converted.Emit (ec);
ec.Emit (OpCodes.Beq, sl.GetILLabel (ec));
}
}
} else {
// TODO: if all the keys in the block are the same and there are
// no gaps/defaults then just use a range-check.
if (compare_type.BuiltinType == BuiltinTypeSpec.Type.Long || compare_type.BuiltinType == BuiltinTypeSpec.Type.ULong) {
// TODO: optimize constant/I4 cases
// check block range (could be > 2^31)
val.Emit (ec);
ec.EmitLong (kb.min);
ec.Emit (OpCodes.Blt, lbl_default);
val.Emit (ec);
ec.EmitLong (kb.max);
ec.Emit (OpCodes.Bgt, lbl_default);
// normalize range
val.Emit (ec);
if (kb.min != 0) {
ec.EmitLong (kb.min);
ec.Emit (OpCodes.Sub);
}
ec.Emit (OpCodes.Conv_I4); // assumes < 2^31 labels!
} else {
// normalize range
val.Emit (ec);
int first = (int) kb.min;
if (first > 0) {
ec.EmitInt (first);
ec.Emit (OpCodes.Sub);
} else if (first < 0) {
ec.EmitInt (-first);
ec.Emit (OpCodes.Add);
}
}
// first, build the list of labels for the switch
int iKey = 0;
long cJumps = kb.Range;
Label[] switch_labels = new Label[cJumps];
for (int iJump = 0; iJump < cJumps; iJump++) {
var key = kb.label_values[iKey];
if (key == kb.min + iJump) {
switch_labels[iJump] = labels[key].GetILLabel (ec);
iKey++;
} else {
switch_labels[iJump] = lbl_default;
}
}
// emit the switch opcode
ec.Emit (OpCodes.Switch, switch_labels);
}
// mark the default for this block
if (range_index != 0)
ec.MarkLabel (lbl_default);
}
// the last default just goes to the end
if (ranges.Count > 0)
ec.Emit (OpCodes.Br, lbl_default);
}
}
SwitchLabel FindLabel (Constant value)
{
SwitchLabel sl = null;
if (string_labels != null) {
string s = value.GetValue () as string;
if (s == null) {
if (case_null != null)
sl = case_null;
else if (case_default != null)
sl = case_default;
} else {
string_labels.TryGetValue (s, out sl);
}
} else {
if (value is NullLiteral) {
sl = case_null;
} else {
labels.TryGetValue (value.GetValueAsLong (), out sl);
}
}
return sl;
}
public override bool Resolve (BlockContext ec)
{
Expr = Expr.Resolve (ec);
if (Expr == null)
return false;
new_expr = SwitchGoverningType (ec, Expr);
if (new_expr == null && Expr.Type.IsNullableType) {
unwrap = Nullable.Unwrap.Create (Expr, false);
if (unwrap == null)
return false;
new_expr = SwitchGoverningType (ec, unwrap);
}
if (new_expr == null) {
if (Expr.Type != InternalType.ErrorType) {
ec.Report.Error (151, loc,
"A switch expression of type `{0}' cannot be converted to an integral type, bool, char, string, enum or nullable type",
Expr.Type.GetSignatureForError ());
}
return false;
}
// Validate switch.
SwitchType = new_expr.Type;
if (SwitchType.BuiltinType == BuiltinTypeSpec.Type.Bool && ec.Module.Compiler.Settings.Version == LanguageVersion.ISO_1) {
ec.Report.FeatureIsNotAvailable (ec.Module.Compiler, loc, "switch expression of boolean type");
return false;
}
if (block.Statements.Count == 0)
return true;
if (SwitchType.BuiltinType == BuiltinTypeSpec.Type.String) {
string_labels = new Dictionary<string, SwitchLabel> ();
} else {
labels = new Dictionary<long, SwitchLabel> ();
}
case_labels = new List<SwitchLabel> ();
var constant = new_expr as Constant;
//
// Don't need extra variable for constant switch or switch with
// only default case
//
if (constant == null) {
//
// Store switch expression for comparison purposes
//
value = new_expr as VariableReference;
if (value == null && !HasOnlyDefaultSection ()) {
var current_block = ec.CurrentBlock;
ec.CurrentBlock = Block;
// Create temporary variable inside switch scope
value = TemporaryVariableReference.Create (SwitchType, ec.CurrentBlock, loc);
value.Resolve (ec);
ec.CurrentBlock = current_block;
}
}
Switch old_switch = ec.Switch;
ec.Switch = this;
ec.Switch.SwitchType = SwitchType;
ec.StartFlowBranching (FlowBranching.BranchingType.Switch, loc);
ec.CurrentBranching.CurrentUsageVector.Goto ();
var ok = block.Resolve (ec);
if (case_default == null)
ec.CurrentBranching.CurrentUsageVector.ResetBarrier ();
ec.EndFlowBranching ();
ec.Switch = old_switch;
//
// Check if all goto cases are valid. Needs to be done after switch
// is resolved becuase goto can jump forward in the scope.
//
if (goto_cases != null) {
foreach (var gc in goto_cases) {
if (gc.Item1 == null) {
if (DefaultLabel == null) {
FlowBranchingBlock.Error_UnknownLabel (loc, "default", ec.Report);
}
continue;
}
var sl = FindLabel (gc.Item2);
if (sl == null) {
FlowBranchingBlock.Error_UnknownLabel (loc, "case " + gc.Item2.GetValueAsLiteral (), ec.Report);
} else {
gc.Item1.Label = sl;
}
}
}
if (constant != null) {
ResolveUnreachableSections (ec, constant);
}
if (!ok)
return false;
if (constant == null && SwitchType.BuiltinType == BuiltinTypeSpec.Type.String && string_labels.Count > 6) {
ResolveStringSwitchMap (ec);
}
//
// Anonymous storey initialization has to happen before
// any generated switch dispatch
//
block.InsertStatement (0, new DispatchStatement (this));
return true;
}
bool HasOnlyDefaultSection ()
{
for (int i = 0; i < block.Statements.Count; ++i) {
var s = block.Statements[i] as SwitchLabel;
if (s == null || s.IsDefault)
continue;
return false;
}
return true;
}
public void RegisterGotoCase (GotoCase gotoCase, Constant value)
{
if (goto_cases == null)
goto_cases = new List<Tuple<GotoCase, Constant>> ();
goto_cases.Add (Tuple.Create (gotoCase, value));
}
//
// Converts string switch into string hashtable
//
void ResolveStringSwitchMap (ResolveContext ec)
{
FullNamedExpression string_dictionary_type;
if (ec.Module.PredefinedTypes.Dictionary.Define ()) {
string_dictionary_type = new TypeExpression (
ec.Module.PredefinedTypes.Dictionary.TypeSpec.MakeGenericType (ec,
new [] { ec.BuiltinTypes.String, ec.BuiltinTypes.Int }),
loc);
} else if (ec.Module.PredefinedTypes.Hashtable.Define ()) {
string_dictionary_type = new TypeExpression (ec.Module.PredefinedTypes.Hashtable.TypeSpec, loc);
} else {
ec.Module.PredefinedTypes.Dictionary.Resolve ();
return;
}
var ctype = ec.CurrentMemberDefinition.Parent.PartialContainer;
Field field = new Field (ctype, string_dictionary_type,
Modifiers.STATIC | Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED,
new MemberName (CompilerGeneratedContainer.MakeName (null, "f", "switch$map", ec.Module.CounterSwitchTypes++), loc), null);
if (!field.Define ())
return;
ctype.AddField (field);
var init = new List<Expression> ();
int counter = -1;
labels = new Dictionary<long, SwitchLabel> (string_labels.Count);
string value = null;
foreach (SwitchLabel sl in case_labels) {
if (sl.SectionStart)
labels.Add (++counter, sl);
if (sl == case_default || sl == case_null)
continue;
value = (string) sl.Converted.GetValue ();
var init_args = new List<Expression> (2);
init_args.Add (new StringLiteral (ec.BuiltinTypes, value, sl.Location));
sl.Converted = new IntConstant (ec.BuiltinTypes, counter, loc);
init_args.Add (sl.Converted);
init.Add (new CollectionElementInitializer (init_args, loc));
}
Arguments args = new Arguments (1);
args.Add (new Argument (new IntConstant (ec.BuiltinTypes, init.Count, loc)));
Expression initializer = new NewInitialize (string_dictionary_type, args,
new CollectionOrObjectInitializers (init, loc), loc);
switch_cache_field = new FieldExpr (field, loc);
string_dictionary = new SimpleAssign (switch_cache_field, initializer.Resolve (ec));
}
void ResolveUnreachableSections (BlockContext bc, Constant value)
{
var constant_label = FindLabel (value) ?? case_default;
bool found = false;
bool unreachable_reported = false;
for (int i = 0; i < block.Statements.Count; ++i) {
var s = block.Statements[i];
if (s is SwitchLabel) {
if (unreachable_reported) {
found = unreachable_reported = false;
}
found |= s == constant_label;
continue;
}
if (found) {
unreachable_reported = true;
continue;
}
if (!unreachable_reported) {
unreachable_reported = true;
bc.Report.Warning (162, 2, s.loc, "Unreachable code detected");
}
block.Statements[i] = new EmptyStatement (s.loc);
}
}
void DoEmitStringSwitch (EmitContext ec)
{
Label l_initialized = ec.DefineLabel ();
//
// Skip initialization when value is null
//
value.EmitBranchable (ec, nullLabel, false);
//
// Check if string dictionary is initialized and initialize
//
switch_cache_field.EmitBranchable (ec, l_initialized, true);
using (ec.With (BuilderContext.Options.OmitDebugInfo, true)) {
string_dictionary.EmitStatement (ec);
}
ec.MarkLabel (l_initialized);
LocalTemporary string_switch_variable = new LocalTemporary (ec.BuiltinTypes.Int);
ResolveContext rc = new ResolveContext (ec.MemberContext);
if (switch_cache_field.Type.IsGeneric) {
Arguments get_value_args = new Arguments (2);
get_value_args.Add (new Argument (value));
get_value_args.Add (new Argument (string_switch_variable, Argument.AType.Out));
Expression get_item = new Invocation (new MemberAccess (switch_cache_field, "TryGetValue", loc), get_value_args).Resolve (rc);
if (get_item == null)
return;
//
// A value was not found, go to default case
//
get_item.EmitBranchable (ec, defaultLabel, false);
} else {
Arguments get_value_args = new Arguments (1);
get_value_args.Add (new Argument (value));
Expression get_item = new ElementAccess (switch_cache_field, get_value_args, loc).Resolve (rc);
if (get_item == null)
return;
LocalTemporary get_item_object = new LocalTemporary (ec.BuiltinTypes.Object);
get_item_object.EmitAssign (ec, get_item, true, false);
ec.Emit (OpCodes.Brfalse, defaultLabel);
ExpressionStatement get_item_int = (ExpressionStatement) new SimpleAssign (string_switch_variable,
new Cast (new TypeExpression (ec.BuiltinTypes.Int, loc), get_item_object, loc)).Resolve (rc);
get_item_int.EmitStatement (ec);
get_item_object.Release (ec);
}
EmitTableSwitch (ec, string_switch_variable);
string_switch_variable.Release (ec);
}
//
// Emits switch using simple if/else comparison for small label count (4 + optional default)
//
void EmitShortSwitch (EmitContext ec)
{
MethodSpec equal_method = null;
if (SwitchType.BuiltinType == BuiltinTypeSpec.Type.String) {
equal_method = ec.Module.PredefinedMembers.StringEqual.Resolve (loc);
}
if (equal_method != null) {
value.EmitBranchable (ec, nullLabel, false);
}
for (int i = 0; i < case_labels.Count; ++i) {
var label = case_labels [i];
if (label == case_default || label == case_null)
continue;
var constant = label.Converted;
if (equal_method != null) {
value.Emit (ec);
constant.Emit (ec);
var call = new CallEmitter ();
call.EmitPredefined (ec, equal_method, new Arguments (0));
ec.Emit (OpCodes.Brtrue, label.GetILLabel (ec));
continue;
}
if (constant.IsZeroInteger && constant.Type.BuiltinType != BuiltinTypeSpec.Type.Long && constant.Type.BuiltinType != BuiltinTypeSpec.Type.ULong) {
value.EmitBranchable (ec, label.GetILLabel (ec), false);
continue;
}
value.Emit (ec);
constant.Emit (ec);
ec.Emit (OpCodes.Beq, label.GetILLabel (ec));
}
ec.Emit (OpCodes.Br, defaultLabel);
}
void EmitDispatch (EmitContext ec)
{
if (value == null) {
//
// Constant switch, we already done the work
//
return;
}
if (string_dictionary != null) {
DoEmitStringSwitch (ec);
} else if (case_labels.Count < 4 || string_labels != null) {
EmitShortSwitch (ec);
} else {
EmitTableSwitch (ec, value);
}
}
protected override void DoEmit (EmitContext ec)
{
// Workaround broken flow-analysis
block.HasUnreachableClosingBrace = true;
//
// Setup the codegen context
//
Label old_end = ec.LoopEnd;
Switch old_switch = ec.Switch;
ec.LoopEnd = ec.DefineLabel ();
ec.Switch = this;
defaultLabel = case_default == null ? ec.LoopEnd : case_default.GetILLabel (ec);
nullLabel = case_null == null ? defaultLabel : case_null.GetILLabel (ec);
if (value != null) {
ec.Mark (loc);
if (IsNullable) {
unwrap.EmitCheck (ec);
ec.Emit (OpCodes.Brfalse, nullLabel);
value.EmitAssign (ec, new_expr, false, false);
} else if (new_expr != value) {
value.EmitAssign (ec, new_expr, false, false);
}
//
// Next statement is compiler generated we don't need extra
// nop when we can use the statement for sequence point
//
ec.Mark (block.StartLocation);
block.IsCompilerGenerated = true;
}
block.Emit (ec);
// Restore context state.
ec.MarkLabel (ec.LoopEnd);
//
// Restore the previous context
//
ec.LoopEnd = old_end;
ec.Switch = old_switch;
}
protected override void CloneTo (CloneContext clonectx, Statement t)
{
Switch target = (Switch) t;
target.Expr = Expr.Clone (clonectx);
target.block = (ExplicitBlock) block.Clone (clonectx);
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
// A place where execution can restart in an iterator
public abstract class ResumableStatement : Statement
{
bool prepared;
protected Label resume_point;
public Label PrepareForEmit (EmitContext ec)
{
if (!prepared) {
prepared = true;
resume_point = ec.DefineLabel ();
}
return resume_point;
}
public virtual Label PrepareForDispose (EmitContext ec, Label end)
{
return end;
}
public virtual void EmitForDispose (EmitContext ec, LocalBuilder pc, Label end, bool have_dispatcher)
{
}
}
public abstract class TryFinallyBlock : ExceptionStatement
{
protected Statement stmt;
Label dispose_try_block;
bool prepared_for_dispose, emitted_dispose;
Method finally_host;
protected TryFinallyBlock (Statement stmt, Location loc)
: base (loc)
{
this.stmt = stmt;
}
#region Properties
public Statement Statement {
get {
return stmt;
}
}
#endregion
protected abstract void EmitTryBody (EmitContext ec);
public abstract void EmitFinallyBody (EmitContext ec);
public override Label PrepareForDispose (EmitContext ec, Label end)
{
if (!prepared_for_dispose) {
prepared_for_dispose = true;
dispose_try_block = ec.DefineLabel ();
}
return dispose_try_block;
}
protected sealed override void DoEmit (EmitContext ec)
{
EmitTryBodyPrepare (ec);
EmitTryBody (ec);
ec.BeginFinallyBlock ();
Label start_finally = ec.DefineLabel ();
if (resume_points != null) {
var state_machine = (StateMachineInitializer) ec.CurrentAnonymousMethod;
ec.Emit (OpCodes.Ldloc, state_machine.SkipFinally);
ec.Emit (OpCodes.Brfalse_S, start_finally);
ec.Emit (OpCodes.Endfinally);
}
ec.MarkLabel (start_finally);
if (finally_host != null) {
finally_host.Define ();
finally_host.PrepareEmit ();
finally_host.Emit ();
// Now it's safe to add, to close it properly and emit sequence points
finally_host.Parent.AddMember (finally_host);
var ce = new CallEmitter ();
ce.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, loc);
ce.EmitPredefined (ec, finally_host.Spec, new Arguments (0));
} else {
EmitFinallyBody (ec);
}
ec.EndExceptionBlock ();
}
public override void EmitForDispose (EmitContext ec, LocalBuilder pc, Label end, bool have_dispatcher)
{
if (emitted_dispose)
return;
emitted_dispose = true;
Label end_of_try = ec.DefineLabel ();
// Ensure that the only way we can get into this code is through a dispatcher
if (have_dispatcher)
ec.Emit (OpCodes.Br, end);
ec.BeginExceptionBlock ();
ec.MarkLabel (dispose_try_block);
Label[] labels = null;
for (int i = 0; i < resume_points.Count; ++i) {
ResumableStatement s = resume_points[i];
Label ret = s.PrepareForDispose (ec, end_of_try);
if (ret.Equals (end_of_try) && labels == null)
continue;
if (labels == null) {
labels = new Label[resume_points.Count];
for (int j = 0; j < i; ++j)
labels[j] = end_of_try;
}
labels[i] = ret;
}
if (labels != null) {
int j;
for (j = 1; j < labels.Length; ++j)
if (!labels[0].Equals (labels[j]))
break;
bool emit_dispatcher = j < labels.Length;
if (emit_dispatcher) {
ec.Emit (OpCodes.Ldloc, pc);
ec.EmitInt (first_resume_pc);
ec.Emit (OpCodes.Sub);
ec.Emit (OpCodes.Switch, labels);
}
foreach (ResumableStatement s in resume_points)
s.EmitForDispose (ec, pc, end_of_try, emit_dispatcher);
}
ec.MarkLabel (end_of_try);
ec.BeginFinallyBlock ();
if (finally_host != null) {
var ce = new CallEmitter ();
ce.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, loc);
ce.EmitPredefined (ec, finally_host.Spec, new Arguments (0));
} else {
EmitFinallyBody (ec);
}
ec.EndExceptionBlock ();
}
public override bool Resolve (BlockContext bc)
{
//
// Finally block inside iterator is called from MoveNext and
// Dispose methods that means we need to lift the block into
// newly created host method to emit the body only once. The
// original block then simply calls the newly generated method.
//
if (bc.CurrentIterator != null && !bc.IsInProbingMode) {
var b = stmt as Block;
if (b != null && b.Explicit.HasYield) {
finally_host = bc.CurrentIterator.CreateFinallyHost (this);
}
}
return base.Resolve (bc);
}
}
//
// Base class for blocks using exception handling
//
public abstract class ExceptionStatement : ResumableStatement
{
#if !STATIC
bool code_follows;
#endif
protected List<ResumableStatement> resume_points;
protected int first_resume_pc;
protected ExceptionStatement (Location loc)
{
this.loc = loc;
}
protected virtual void EmitTryBodyPrepare (EmitContext ec)
{
StateMachineInitializer state_machine = null;
if (resume_points != null) {
state_machine = (StateMachineInitializer) ec.CurrentAnonymousMethod;
ec.EmitInt ((int) IteratorStorey.State.Running);
ec.Emit (OpCodes.Stloc, state_machine.CurrentPC);
}
ec.BeginExceptionBlock ();
if (resume_points != null) {
ec.MarkLabel (resume_point);
// For normal control flow, we want to fall-through the Switch
// So, we use CurrentPC rather than the $PC field, and initialize it to an outside value above
ec.Emit (OpCodes.Ldloc, state_machine.CurrentPC);
ec.EmitInt (first_resume_pc);
ec.Emit (OpCodes.Sub);
Label[] labels = new Label[resume_points.Count];
for (int i = 0; i < resume_points.Count; ++i)
labels[i] = resume_points[i].PrepareForEmit (ec);
ec.Emit (OpCodes.Switch, labels);
}
}
public void SomeCodeFollows ()
{
#if !STATIC
code_follows = true;
#endif
}
public override bool Resolve (BlockContext ec)
{
#if !STATIC
// System.Reflection.Emit automatically emits a 'leave' at the end of a try clause
// So, ensure there's some IL code after this statement.
if (!code_follows && resume_points == null && ec.CurrentBranching.CurrentUsageVector.IsUnreachable)
ec.NeedReturnLabel ();
#endif
return true;
}
public void AddResumePoint (ResumableStatement stmt, int pc)
{
if (resume_points == null) {
resume_points = new List<ResumableStatement> ();
first_resume_pc = pc;
}
if (pc != first_resume_pc + resume_points.Count)
throw new InternalErrorException ("missed an intervening AddResumePoint?");
resume_points.Add (stmt);
}
}
public class Lock : TryFinallyBlock
{
Expression expr;
TemporaryVariableReference expr_copy;
TemporaryVariableReference lock_taken;
public Lock (Expression expr, Statement stmt, Location loc)
: base (stmt, loc)
{
this.expr = expr;
}
public Expression Expr {
get {
return this.expr;
}
}
public override bool Resolve (BlockContext ec)
{
expr = expr.Resolve (ec);
if (expr == null)
return false;
if (!TypeSpec.IsReferenceType (expr.Type)) {
ec.Report.Error (185, loc,
"`{0}' is not a reference type as required by the lock statement",
expr.Type.GetSignatureForError ());
}
if (expr.Type.IsGenericParameter) {
expr = Convert.ImplicitTypeParameterConversion (expr, (TypeParameterSpec)expr.Type, ec.BuiltinTypes.Object);
}
VariableReference lv = expr as VariableReference;
bool locked;
if (lv != null) {
locked = lv.IsLockedByStatement;
lv.IsLockedByStatement = true;
} else {
lv = null;
locked = false;
}
//
// Have to keep original lock value around to unlock same location
// in the case of original value has changed or is null
//
expr_copy = TemporaryVariableReference.Create (ec.BuiltinTypes.Object, ec.CurrentBlock, loc);
expr_copy.Resolve (ec);
//
// Ensure Monitor methods are available
//
if (ResolvePredefinedMethods (ec) > 1) {
lock_taken = TemporaryVariableReference.Create (ec.BuiltinTypes.Bool, ec.CurrentBlock, loc);
lock_taken.Resolve (ec);
}
using (ec.Set (ResolveContext.Options.LockScope)) {
ec.StartFlowBranching (this);
Statement.Resolve (ec);
ec.EndFlowBranching ();
}
if (lv != null) {
lv.IsLockedByStatement = locked;
}
base.Resolve (ec);
return true;
}
protected override void EmitTryBodyPrepare (EmitContext ec)
{
expr_copy.EmitAssign (ec, expr);
if (lock_taken != null) {
//
// Initialize ref variable
//
lock_taken.EmitAssign (ec, new BoolLiteral (ec.BuiltinTypes, false, loc));
} else {
//
// Monitor.Enter (expr_copy)
//
expr_copy.Emit (ec);
ec.Emit (OpCodes.Call, ec.Module.PredefinedMembers.MonitorEnter.Get ());
}
base.EmitTryBodyPrepare (ec);
}
protected override void EmitTryBody (EmitContext ec)
{
//
// Monitor.Enter (expr_copy, ref lock_taken)
//
if (lock_taken != null) {
expr_copy.Emit (ec);
lock_taken.LocalInfo.CreateBuilder (ec);
lock_taken.AddressOf (ec, AddressOp.Load);
ec.Emit (OpCodes.Call, ec.Module.PredefinedMembers.MonitorEnter_v4.Get ());
}
Statement.Emit (ec);
}
public override void EmitFinallyBody (EmitContext ec)
{
//
// if (lock_taken) Monitor.Exit (expr_copy)
//
Label skip = ec.DefineLabel ();
if (lock_taken != null) {
lock_taken.Emit (ec);
ec.Emit (OpCodes.Brfalse_S, skip);
}
expr_copy.Emit (ec);
var m = ec.Module.PredefinedMembers.MonitorExit.Resolve (loc);
if (m != null)
ec.Emit (OpCodes.Call, m);
ec.MarkLabel (skip);
}
int ResolvePredefinedMethods (ResolveContext rc)
{
// Try 4.0 Monitor.Enter (object, ref bool) overload first
var m = rc.Module.PredefinedMembers.MonitorEnter_v4.Get ();
if (m != null)
return 4;
m = rc.Module.PredefinedMembers.MonitorEnter.Get ();
if (m != null)
return 1;
rc.Module.PredefinedMembers.MonitorEnter_v4.Resolve (loc);
return 0;
}
protected override void CloneTo (CloneContext clonectx, Statement t)
{
Lock target = (Lock) t;
target.expr = expr.Clone (clonectx);
target.stmt = Statement.Clone (clonectx);
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
public class Unchecked : Statement {
public Block Block;
public Unchecked (Block b, Location loc)
{
Block = b;
b.Unchecked = true;
this.loc = loc;
}
public override bool Resolve (BlockContext ec)
{
using (ec.With (ResolveContext.Options.AllCheckStateFlags, false))
return Block.Resolve (ec);
}
protected override void DoEmit (EmitContext ec)
{
using (ec.With (EmitContext.Options.CheckedScope, false))
Block.Emit (ec);
}
protected override void CloneTo (CloneContext clonectx, Statement t)
{
Unchecked target = (Unchecked) t;
target.Block = clonectx.LookupBlock (Block);
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
public class Checked : Statement {
public Block Block;
public Checked (Block b, Location loc)
{
Block = b;
b.Unchecked = false;
this.loc = loc;
}
public override bool Resolve (BlockContext ec)
{
using (ec.With (ResolveContext.Options.AllCheckStateFlags, true))
return Block.Resolve (ec);
}
protected override void DoEmit (EmitContext ec)
{
using (ec.With (EmitContext.Options.CheckedScope, true))
Block.Emit (ec);
}
protected override void CloneTo (CloneContext clonectx, Statement t)
{
Checked target = (Checked) t;
target.Block = clonectx.LookupBlock (Block);
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
public class Unsafe : Statement {
public Block Block;
public Unsafe (Block b, Location loc)
{
Block = b;
Block.Unsafe = true;
this.loc = loc;
}
public override bool Resolve (BlockContext ec)
{
if (ec.CurrentIterator != null)
ec.Report.Error (1629, loc, "Unsafe code may not appear in iterators");
using (ec.Set (ResolveContext.Options.UnsafeScope))
return Block.Resolve (ec);
}
protected override void DoEmit (EmitContext ec)
{
Block.Emit (ec);
}
protected override void CloneTo (CloneContext clonectx, Statement t)
{
Unsafe target = (Unsafe) t;
target.Block = clonectx.LookupBlock (Block);
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
//
// Fixed statement
//
public class Fixed : Statement
{
abstract class Emitter : ShimExpression
{
protected LocalVariable vi;
protected Emitter (Expression expr, LocalVariable li)
: base (expr)
{
vi = li;
}
public abstract void EmitExit (EmitContext ec);
}
class ExpressionEmitter : Emitter {
public ExpressionEmitter (Expression converted, LocalVariable li) :
base (converted, li)
{
}
protected override Expression DoResolve (ResolveContext rc)
{
throw new NotImplementedException ();
}
public override void Emit (EmitContext ec) {
//
// Store pointer in pinned location
//
expr.Emit (ec);
vi.EmitAssign (ec);
}
public override void EmitExit (EmitContext ec)
{
ec.EmitInt (0);
ec.Emit (OpCodes.Conv_U);
vi.EmitAssign (ec);
}
}
class StringEmitter : Emitter
{
LocalVariable pinned_string;
public StringEmitter (Expression expr, LocalVariable li, Location loc)
: base (expr, li)
{
}
protected override Expression DoResolve (ResolveContext rc)
{
pinned_string = new LocalVariable (vi.Block, "$pinned",
LocalVariable.Flags.FixedVariable | LocalVariable.Flags.CompilerGenerated | LocalVariable.Flags.Used,
vi.Location);
pinned_string.Type = rc.BuiltinTypes.String;
eclass = ExprClass.Variable;
type = rc.BuiltinTypes.Int;
return this;
}
public override void Emit (EmitContext ec)
{
pinned_string.CreateBuilder (ec);
expr.Emit (ec);
pinned_string.EmitAssign (ec);
// TODO: Should use Binary::Add
pinned_string.Emit (ec);
ec.Emit (OpCodes.Conv_I);
var m = ec.Module.PredefinedMembers.RuntimeHelpersOffsetToStringData.Resolve (loc);
if (m == null)
return;
PropertyExpr pe = new PropertyExpr (m, pinned_string.Location);
//pe.InstanceExpression = pinned_string;
pe.Resolve (new ResolveContext (ec.MemberContext)).Emit (ec);
ec.Emit (OpCodes.Add);
vi.EmitAssign (ec);
}
public override void EmitExit (EmitContext ec)
{
ec.EmitNull ();
pinned_string.EmitAssign (ec);
}
}
public class VariableDeclaration : BlockVariable
{
public VariableDeclaration (FullNamedExpression type, LocalVariable li)
: base (type, li)
{
}
protected override Expression ResolveInitializer (BlockContext bc, LocalVariable li, Expression initializer)
{
if (!Variable.Type.IsPointer && li == Variable) {
bc.Report.Error (209, TypeExpression.Location,
"The type of locals declared in a fixed statement must be a pointer type");
return null;
}
//
// The rules for the possible declarators are pretty wise,
// but the production on the grammar is more concise.
//
// So we have to enforce these rules here.
//
// We do not resolve before doing the case 1 test,
// because the grammar is explicit in that the token &
// is present, so we need to test for this particular case.
//
if (initializer is Cast) {
bc.Report.Error (254, initializer.Location, "The right hand side of a fixed statement assignment may not be a cast expression");
return null;
}
initializer = initializer.Resolve (bc);
if (initializer == null)
return null;
//
// Case 1: Array
//
if (initializer.Type.IsArray) {
TypeSpec array_type = TypeManager.GetElementType (initializer.Type);
//
// Provided that array_type is unmanaged,
//
if (!TypeManager.VerifyUnmanaged (bc.Module, array_type, loc))
return null;
//
// and T* is implicitly convertible to the
// pointer type given in the fixed statement.
//
ArrayPtr array_ptr = new ArrayPtr (initializer, array_type, loc);
Expression converted = Convert.ImplicitConversionRequired (bc, array_ptr.Resolve (bc), li.Type, loc);
if (converted == null)
return null;
//
// fixed (T* e_ptr = (e == null || e.Length == 0) ? null : converted [0])
//
converted = new Conditional (new BooleanExpression (new Binary (Binary.Operator.LogicalOr,
new Binary (Binary.Operator.Equality, initializer, new NullLiteral (loc)),
new Binary (Binary.Operator.Equality, new MemberAccess (initializer, "Length"), new IntConstant (bc.BuiltinTypes, 0, loc)))),
new NullLiteral (loc),
converted, loc);
converted = converted.Resolve (bc);
return new ExpressionEmitter (converted, li);
}
//
// Case 2: string
//
if (initializer.Type.BuiltinType == BuiltinTypeSpec.Type.String) {
return new StringEmitter (initializer, li, loc).Resolve (bc);
}
// Case 3: fixed buffer
if (initializer is FixedBufferPtr) {
return new ExpressionEmitter (initializer, li);
}
//
// Case 4: & object.
//
bool already_fixed = true;
Unary u = initializer as Unary;
if (u != null && u.Oper == Unary.Operator.AddressOf) {
IVariableReference vr = u.Expr as IVariableReference;
if (vr == null || !vr.IsFixed) {
already_fixed = false;
}
}
if (already_fixed) {
bc.Report.Error (213, loc, "You cannot use the fixed statement to take the address of an already fixed expression");
}
initializer = Convert.ImplicitConversionRequired (bc, initializer, li.Type, loc);
return new ExpressionEmitter (initializer, li);
}
}
VariableDeclaration decl;
Statement statement;
bool has_ret;
public Fixed (VariableDeclaration decl, Statement stmt, Location l)
{
this.decl = decl;
statement = stmt;
loc = l;
}
#region Properties
public Statement Statement {
get {
return statement;
}
}
public BlockVariable Variables {
get {
return decl;
}
}
#endregion
public override bool Resolve (BlockContext ec)
{
using (ec.Set (ResolveContext.Options.FixedInitializerScope)) {
if (!decl.Resolve (ec))
return false;
}
ec.StartFlowBranching (FlowBranching.BranchingType.Conditional, loc);
bool ok = statement.Resolve (ec);
bool flow_unreachable = ec.EndFlowBranching ();
has_ret = flow_unreachable;
return ok;
}
protected override void DoEmit (EmitContext ec)
{
decl.Variable.CreateBuilder (ec);
decl.Initializer.Emit (ec);
if (decl.Declarators != null) {
foreach (var d in decl.Declarators) {
d.Variable.CreateBuilder (ec);
d.Initializer.Emit (ec);
}
}
statement.Emit (ec);
if (has_ret)
return;
//
// Clear the pinned variable
//
((Emitter) decl.Initializer).EmitExit (ec);
if (decl.Declarators != null) {
foreach (var d in decl.Declarators) {
((Emitter)d.Initializer).EmitExit (ec);
}
}
}
protected override void CloneTo (CloneContext clonectx, Statement t)
{
Fixed target = (Fixed) t;
target.decl = (VariableDeclaration) decl.Clone (clonectx);
target.statement = statement.Clone (clonectx);
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
public class Catch : Statement
{
Block block;
LocalVariable li;
FullNamedExpression type_expr;
CompilerAssign assign;
TypeSpec type;
public Catch (Block block, Location loc)
{
this.block = block;
this.loc = loc;
}
#region Properties
public Block Block {
get {
return block;
}
}
public TypeSpec CatchType {
get {
return type;
}
}
public bool IsGeneral {
get {
return type_expr == null;
}
}
public FullNamedExpression TypeExpression {
get {
return type_expr;
}
set {
type_expr = value;
}
}
public LocalVariable Variable {
get {
return li;
}
set {
li = value;
}
}
#endregion
protected override void DoEmit (EmitContext ec)
{
if (IsGeneral)
ec.BeginCatchBlock (ec.BuiltinTypes.Object);
else
ec.BeginCatchBlock (CatchType);
if (li != null) {
li.CreateBuilder (ec);
//
// Special case hoisted catch variable, we have to use a temporary variable
// to pass via anonymous storey initialization with the value still on top
// of the stack
//
if (li.HoistedVariant != null) {
LocalTemporary lt = new LocalTemporary (li.Type);
lt.Store (ec);
// switch to assigning from the temporary variable and not from top of the stack
assign.UpdateSource (lt);
}
} else {
ec.Emit (OpCodes.Pop);
}
Block.Emit (ec);
}
public override bool Resolve (BlockContext ec)
{
using (ec.With (ResolveContext.Options.CatchScope, true)) {
if (type_expr != null) {
type = type_expr.ResolveAsType (ec);
if (type == null)
return false;
if (type.BuiltinType != BuiltinTypeSpec.Type.Exception && !TypeSpec.IsBaseClass (type, ec.BuiltinTypes.Exception, false)) {
ec.Report.Error (155, loc, "The type caught or thrown must be derived from System.Exception");
} else if (li != null) {
li.Type = type;
li.PrepareForFlowAnalysis (ec);
// source variable is at the top of the stack
Expression source = new EmptyExpression (li.Type);
if (li.Type.IsGenericParameter)
source = new UnboxCast (source, li.Type);
//
// Uses Location.Null to hide from symbol file
//
assign = new CompilerAssign (new LocalVariableReference (li, Location.Null), source, Location.Null);
Block.AddScopeStatement (new StatementExpression (assign, Location.Null));
}
}
return Block.Resolve (ec);
}
}
protected override void CloneTo (CloneContext clonectx, Statement t)
{
Catch target = (Catch) t;
if (type_expr != null)
target.type_expr = (FullNamedExpression) type_expr.Clone (clonectx);
target.block = clonectx.LookupBlock (block);
}
}
public class TryFinally : TryFinallyBlock
{
Block fini;
public Statement Stmt {
get { return this.stmt; }
}
public Block Fini {
get { return this.fini; }
}
public TryFinally (Statement stmt, Block fini, Location loc)
: base (stmt, loc)
{
this.fini = fini;
}
public Block Finallyblock {
get {
return fini;
}
}
public override bool Resolve (BlockContext ec)
{
bool ok = true;
ec.StartFlowBranching (this);
if (!stmt.Resolve (ec))
ok = false;
if (ok)
ec.CurrentBranching.CreateSibling (fini, FlowBranching.SiblingType.Finally);
using (ec.With (ResolveContext.Options.FinallyScope, true)) {
if (!fini.Resolve (ec))
ok = false;
}
ec.EndFlowBranching ();
ok &= base.Resolve (ec);
return ok;
}
protected override void EmitTryBody (EmitContext ec)
{
stmt.Emit (ec);
}
public override void EmitFinallyBody (EmitContext ec)
{
fini.Emit (ec);
}
protected override void CloneTo (CloneContext clonectx, Statement t)
{
TryFinally target = (TryFinally) t;
target.stmt = (Statement) stmt.Clone (clonectx);
if (fini != null)
target.fini = clonectx.LookupBlock (fini);
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
public class TryCatch : ExceptionStatement
{
public Block Block;
List<Catch> clauses;
readonly bool inside_try_finally;
public TryCatch (Block block, List<Catch> catch_clauses, Location l, bool inside_try_finally)
: base (l)
{
this.Block = block;
this.clauses = catch_clauses;
this.inside_try_finally = inside_try_finally;
}
public List<Catch> Clauses {
get {
return clauses;
}
}
public bool IsTryCatchFinally {
get {
return inside_try_finally;
}
}
public override bool Resolve (BlockContext ec)
{
bool ok = true;
ec.StartFlowBranching (this);
if (!Block.Resolve (ec))
ok = false;
for (int i = 0; i < clauses.Count; ++i) {
var c = clauses[i];
ec.CurrentBranching.CreateSibling (c.Block, FlowBranching.SiblingType.Catch);
if (!c.Resolve (ec)) {
ok = false;
continue;
}
TypeSpec resolved_type = c.CatchType;
for (int ii = 0; ii < clauses.Count; ++ii) {
if (ii == i)
continue;
if (clauses[ii].IsGeneral) {
if (resolved_type.BuiltinType != BuiltinTypeSpec.Type.Exception)
continue;
if (!ec.Module.DeclaringAssembly.WrapNonExceptionThrows)
continue;
if (!ec.Module.PredefinedAttributes.RuntimeCompatibility.IsDefined)
continue;
ec.Report.Warning (1058, 1, c.loc,
"A previous catch clause already catches all exceptions. All non-exceptions thrown will be wrapped in a `System.Runtime.CompilerServices.RuntimeWrappedException'");
continue;
}
if (ii >= i)
continue;
var ct = clauses[ii].CatchType;
if (ct == null)
continue;
if (resolved_type == ct || TypeSpec.IsBaseClass (resolved_type, ct, true)) {
ec.Report.Error (160, c.loc,
"A previous catch clause already catches all exceptions of this or a super type `{0}'",
ct.GetSignatureForError ());
ok = false;
}
}
}
ec.EndFlowBranching ();
return base.Resolve (ec) && ok;
}
protected sealed override void DoEmit (EmitContext ec)
{
if (!inside_try_finally)
EmitTryBodyPrepare (ec);
Block.Emit (ec);
foreach (Catch c in clauses)
c.Emit (ec);
if (!inside_try_finally)
ec.EndExceptionBlock ();
}
protected override void CloneTo (CloneContext clonectx, Statement t)
{
TryCatch target = (TryCatch) t;
target.Block = clonectx.LookupBlock (Block);
if (clauses != null){
target.clauses = new List<Catch> ();
foreach (Catch c in clauses)
target.clauses.Add ((Catch) c.Clone (clonectx));
}
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
public class Using : TryFinallyBlock
{
public class VariableDeclaration : BlockVariable
{
Statement dispose_call;
public VariableDeclaration (FullNamedExpression type, LocalVariable li)
: base (type, li)
{
}
public VariableDeclaration (LocalVariable li, Location loc)
: base (li)
{
this.loc = loc;
}
public VariableDeclaration (Expression expr)
: base (null)
{
loc = expr.Location;
Initializer = expr;
}
#region Properties
public bool IsNested { get; private set; }
#endregion
public void EmitDispose (EmitContext ec)
{
dispose_call.Emit (ec);
}
public override bool Resolve (BlockContext bc)
{
if (IsNested)
return true;
return base.Resolve (bc, false);
}
public Expression ResolveExpression (BlockContext bc)
{
var e = Initializer.Resolve (bc);
if (e == null)
return null;
li = LocalVariable.CreateCompilerGenerated (e.Type, bc.CurrentBlock, loc);
Initializer = ResolveInitializer (bc, Variable, e);
return e;
}
protected override Expression ResolveInitializer (BlockContext bc, LocalVariable li, Expression initializer)
{
if (li.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic) {
initializer = initializer.Resolve (bc);
if (initializer == null)
return null;
// Once there is dynamic used defer conversion to runtime even if we know it will never succeed
Arguments args = new Arguments (1);
args.Add (new Argument (initializer));
initializer = new DynamicConversion (bc.BuiltinTypes.IDisposable, 0, args, initializer.Location).Resolve (bc);
if (initializer == null)
return null;
var var = LocalVariable.CreateCompilerGenerated (initializer.Type, bc.CurrentBlock, loc);
dispose_call = CreateDisposeCall (bc, var);
dispose_call.Resolve (bc);
return base.ResolveInitializer (bc, li, new SimpleAssign (var.CreateReferenceExpression (bc, loc), initializer, loc));
}
if (li == Variable) {
CheckIDiposableConversion (bc, li, initializer);
dispose_call = CreateDisposeCall (bc, li);
dispose_call.Resolve (bc);
}
return base.ResolveInitializer (bc, li, initializer);
}
protected virtual void CheckIDiposableConversion (BlockContext bc, LocalVariable li, Expression initializer)
{
var type = li.Type;
if (type.BuiltinType != BuiltinTypeSpec.Type.IDisposable && !type.ImplementsInterface (bc.BuiltinTypes.IDisposable, false)) {
if (type.IsNullableType) {
// it's handled in CreateDisposeCall
return;
}
bc.Report.SymbolRelatedToPreviousError (type);
var loc = type_expr == null ? initializer.Location : type_expr.Location;
bc.Report.Error (1674, loc, "`{0}': type used in a using statement must be implicitly convertible to `System.IDisposable'",
type.GetSignatureForError ());
return;
}
}
protected virtual Statement CreateDisposeCall (BlockContext bc, LocalVariable lv)
{
var lvr = lv.CreateReferenceExpression (bc, lv.Location);
var type = lv.Type;
var loc = lv.Location;
var idt = bc.BuiltinTypes.IDisposable;
var m = bc.Module.PredefinedMembers.IDisposableDispose.Resolve (loc);
var dispose_mg = MethodGroupExpr.CreatePredefined (m, idt, loc);
dispose_mg.InstanceExpression = type.IsNullableType ?
new Cast (new TypeExpression (idt, loc), lvr, loc).Resolve (bc) :
lvr;
//
// Hide it from symbol file via null location
//
Statement dispose = new StatementExpression (new Invocation (dispose_mg, null), Location.Null);
// Add conditional call when disposing possible null variable
if (!type.IsStruct || type.IsNullableType)
dispose = new If (new Binary (Binary.Operator.Inequality, lvr, new NullLiteral (loc)), dispose, dispose.loc);
return dispose;
}
public void ResolveDeclaratorInitializer (BlockContext bc)
{
Initializer = base.ResolveInitializer (bc, Variable, Initializer);
}
public Statement RewriteUsingDeclarators (BlockContext bc, Statement stmt)
{
for (int i = declarators.Count - 1; i >= 0; --i) {
var d = declarators [i];
var vd = new VariableDeclaration (d.Variable, d.Variable.Location);
vd.Initializer = d.Initializer;
vd.IsNested = true;
vd.dispose_call = CreateDisposeCall (bc, d.Variable);
vd.dispose_call.Resolve (bc);
stmt = new Using (vd, stmt, d.Variable.Location);
}
declarators = null;
return stmt;
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
VariableDeclaration decl;
public Using (VariableDeclaration decl, Statement stmt, Location loc)
: base (stmt, loc)
{
this.decl = decl;
}
public Using (Expression expr, Statement stmt, Location loc)
: base (stmt, loc)
{
this.decl = new VariableDeclaration (expr);
}
#region Properties
public Expression Expr {
get {
return decl.Variable == null ? decl.Initializer : null;
}
}
public BlockVariable Variables {
get {
return decl;
}
}
#endregion
public override void Emit (EmitContext ec)
{
//
// Don't emit sequence point it will be set on variable declaration
//
DoEmit (ec);
}
protected override void EmitTryBodyPrepare (EmitContext ec)
{
decl.Emit (ec);
base.EmitTryBodyPrepare (ec);
}
protected override void EmitTryBody (EmitContext ec)
{
stmt.Emit (ec);
}
public override void EmitFinallyBody (EmitContext ec)
{
decl.EmitDispose (ec);
}
public override bool Resolve (BlockContext ec)
{
VariableReference vr;
bool vr_locked = false;
using (ec.Set (ResolveContext.Options.UsingInitializerScope)) {
if (decl.Variable == null) {
vr = decl.ResolveExpression (ec) as VariableReference;
if (vr != null) {
vr_locked = vr.IsLockedByStatement;
vr.IsLockedByStatement = true;
}
} else {
if (decl.IsNested) {
decl.ResolveDeclaratorInitializer (ec);
} else {
if (!decl.Resolve (ec))
return false;
if (decl.Declarators != null) {
stmt = decl.RewriteUsingDeclarators (ec, stmt);
}
}
vr = null;
}
}
ec.StartFlowBranching (this);
stmt.Resolve (ec);
ec.EndFlowBranching ();
if (vr != null)
vr.IsLockedByStatement = vr_locked;
base.Resolve (ec);
return true;
}
protected override void CloneTo (CloneContext clonectx, Statement t)
{
Using target = (Using) t;
target.decl = (VariableDeclaration) decl.Clone (clonectx);
target.stmt = stmt.Clone (clonectx);
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
/// <summary>
/// Implementation of the foreach C# statement
/// </summary>
public class Foreach : Statement
{
abstract class IteratorStatement : Statement
{
protected readonly Foreach for_each;
protected IteratorStatement (Foreach @foreach)
{
this.for_each = @foreach;
this.loc = @foreach.expr.Location;
}
protected override void CloneTo (CloneContext clonectx, Statement target)
{
throw new NotImplementedException ();
}
public override void Emit (EmitContext ec)
{
if (ec.EmitAccurateDebugInfo) {
ec.Emit (OpCodes.Nop);
}
base.Emit (ec);
}
}
sealed class ArrayForeach : IteratorStatement
{
TemporaryVariableReference[] lengths;
Expression [] length_exprs;
StatementExpression[] counter;
TemporaryVariableReference[] variables;
TemporaryVariableReference copy;
public ArrayForeach (Foreach @foreach, int rank)
: base (@foreach)
{
counter = new StatementExpression[rank];
variables = new TemporaryVariableReference[rank];
length_exprs = new Expression [rank];
//
// Only use temporary length variables when dealing with
// multi-dimensional arrays
//
if (rank > 1)
lengths = new TemporaryVariableReference [rank];
}
public override bool Resolve (BlockContext ec)
{
Block variables_block = for_each.variable.Block;
copy = TemporaryVariableReference.Create (for_each.expr.Type, variables_block, loc);
copy.Resolve (ec);
int rank = length_exprs.Length;
Arguments list = new Arguments (rank);
for (int i = 0; i < rank; i++) {
var v = TemporaryVariableReference.Create (ec.BuiltinTypes.Int, variables_block, loc);
variables[i] = v;
counter[i] = new StatementExpression (new UnaryMutator (UnaryMutator.Mode.PostIncrement, v, Location.Null));
counter[i].Resolve (ec);
if (rank == 1) {
length_exprs [i] = new MemberAccess (copy, "Length").Resolve (ec);
} else {
lengths[i] = TemporaryVariableReference.Create (ec.BuiltinTypes.Int, variables_block, loc);
lengths[i].Resolve (ec);
Arguments args = new Arguments (1);
args.Add (new Argument (new IntConstant (ec.BuiltinTypes, i, loc)));
length_exprs [i] = new Invocation (new MemberAccess (copy, "GetLength"), args).Resolve (ec);
}
list.Add (new Argument (v));
}
var access = new ElementAccess (copy, list, loc).Resolve (ec);
if (access == null)
return false;
TypeSpec var_type;
if (for_each.type is VarExpr) {
// Infer implicitly typed local variable from foreach array type
var_type = access.Type;
} else {
var_type = for_each.type.ResolveAsType (ec);
if (var_type == null)
return false;
access = Convert.ExplicitConversion (ec, access, var_type, loc);
if (access == null)
return false;
}
for_each.variable.Type = var_type;
var variable_ref = new LocalVariableReference (for_each.variable, loc).Resolve (ec);
if (variable_ref == null)
return false;
for_each.body.AddScopeStatement (new StatementExpression (new CompilerAssign (variable_ref, access, Location.Null), for_each.type.Location));
bool ok = true;
ec.StartFlowBranching (FlowBranching.BranchingType.Loop, loc);
ec.CurrentBranching.CreateSibling ();
ec.StartFlowBranching (FlowBranching.BranchingType.Embedded, loc);
if (!for_each.body.Resolve (ec))
ok = false;
ec.EndFlowBranching ();
// There's no direct control flow from the end of the embedded statement to the end of the loop
ec.CurrentBranching.CurrentUsageVector.Goto ();
ec.EndFlowBranching ();
return ok;
}
protected override void DoEmit (EmitContext ec)
{
copy.EmitAssign (ec, for_each.expr);
int rank = length_exprs.Length;
Label[] test = new Label [rank];
Label[] loop = new Label [rank];
for (int i = 0; i < rank; i++) {
test [i] = ec.DefineLabel ();
loop [i] = ec.DefineLabel ();
if (lengths != null)
lengths [i].EmitAssign (ec, length_exprs [i]);
}
IntConstant zero = new IntConstant (ec.BuiltinTypes, 0, loc);
for (int i = 0; i < rank; i++) {
variables [i].EmitAssign (ec, zero);
ec.Emit (OpCodes.Br, test [i]);
ec.MarkLabel (loop [i]);
}
for_each.body.Emit (ec);
ec.MarkLabel (ec.LoopBegin);
ec.Mark (for_each.expr.Location);
for (int i = rank - 1; i >= 0; i--){
counter [i].Emit (ec);
ec.MarkLabel (test [i]);
variables [i].Emit (ec);
if (lengths != null)
lengths [i].Emit (ec);
else
length_exprs [i].Emit (ec);
ec.Emit (OpCodes.Blt, loop [i]);
}
ec.MarkLabel (ec.LoopEnd);
}
}
sealed class CollectionForeach : IteratorStatement, OverloadResolver.IErrorHandler
{
class RuntimeDispose : Using.VariableDeclaration
{
public RuntimeDispose (LocalVariable lv, Location loc)
: base (lv, loc)
{
}
protected override void CheckIDiposableConversion (BlockContext bc, LocalVariable li, Expression initializer)
{
// Defered to runtime check
}
protected override Statement CreateDisposeCall (BlockContext bc, LocalVariable lv)
{
var idt = bc.BuiltinTypes.IDisposable;
//
// Fabricates code like
//
// if ((temp = vr as IDisposable) != null) temp.Dispose ();
//
var dispose_variable = LocalVariable.CreateCompilerGenerated (idt, bc.CurrentBlock, loc);
var idisaposable_test = new Binary (Binary.Operator.Inequality, new CompilerAssign (
dispose_variable.CreateReferenceExpression (bc, loc),
new As (lv.CreateReferenceExpression (bc, loc), new TypeExpression (dispose_variable.Type, loc), loc),
loc), new NullLiteral (loc));
var m = bc.Module.PredefinedMembers.IDisposableDispose.Resolve (loc);
var dispose_mg = MethodGroupExpr.CreatePredefined (m, idt, loc);
dispose_mg.InstanceExpression = dispose_variable.CreateReferenceExpression (bc, loc);
Statement dispose = new StatementExpression (new Invocation (dispose_mg, null));
return new If (idisaposable_test, dispose, loc);
}
}
LocalVariable variable;
Expression expr;
Statement statement;
ExpressionStatement init;
TemporaryVariableReference enumerator_variable;
bool ambiguous_getenumerator_name;
public CollectionForeach (Foreach @foreach, LocalVariable var, Expression expr)
: base (@foreach)
{
this.variable = var;
this.expr = expr;
}
void Error_WrongEnumerator (ResolveContext rc, MethodSpec enumerator)
{
rc.Report.SymbolRelatedToPreviousError (enumerator);
rc.Report.Error (202, loc,
"foreach statement requires that the return type `{0}' of `{1}' must have a suitable public MoveNext method and public Current property",
enumerator.ReturnType.GetSignatureForError (), enumerator.GetSignatureForError ());
}
MethodGroupExpr ResolveGetEnumerator (ResolveContext rc)
{
//
// Option 1: Try to match by name GetEnumerator first
//
var mexpr = Expression.MemberLookup (rc, false, expr.Type,
"GetEnumerator", 0, Expression.MemberLookupRestrictions.ExactArity, loc); // TODO: What if CS0229 ?
var mg = mexpr as MethodGroupExpr;
if (mg != null) {
mg.InstanceExpression = expr;
Arguments args = new Arguments (0);
mg = mg.OverloadResolve (rc, ref args, this, OverloadResolver.Restrictions.ProbingOnly);
// For ambiguous GetEnumerator name warning CS0278 was reported, but Option 2 could still apply
if (ambiguous_getenumerator_name)
mg = null;
if (mg != null && args.Count == 0 && !mg.BestCandidate.IsStatic && mg.BestCandidate.IsPublic) {
return mg;
}
}
//
// Option 2: Try to match using IEnumerable interfaces with preference of generic version
//
var t = expr.Type;
PredefinedMember<MethodSpec> iface_candidate = null;
var ptypes = rc.Module.PredefinedTypes;
var gen_ienumerable = ptypes.IEnumerableGeneric;
if (!gen_ienumerable.Define ())
gen_ienumerable = null;
var ifaces = t.Interfaces;
if (ifaces != null) {
foreach (var iface in ifaces) {
if (gen_ienumerable != null && iface.MemberDefinition == gen_ienumerable.TypeSpec.MemberDefinition) {
if (iface_candidate != null && iface_candidate != rc.Module.PredefinedMembers.IEnumerableGetEnumerator) {
rc.Report.SymbolRelatedToPreviousError (expr.Type);
rc.Report.Error (1640, loc,
"foreach statement cannot operate on variables of type `{0}' because it contains multiple implementation of `{1}'. Try casting to a specific implementation",
expr.Type.GetSignatureForError (), gen_ienumerable.TypeSpec.GetSignatureForError ());
return null;
}
// TODO: Cache this somehow
iface_candidate = new PredefinedMember<MethodSpec> (rc.Module, iface,
MemberFilter.Method ("GetEnumerator", 0, ParametersCompiled.EmptyReadOnlyParameters, null));
continue;
}
if (iface.BuiltinType == BuiltinTypeSpec.Type.IEnumerable && iface_candidate == null) {
iface_candidate = rc.Module.PredefinedMembers.IEnumerableGetEnumerator;
}
}
}
if (iface_candidate == null) {
if (expr.Type != InternalType.ErrorType) {
rc.Report.Error (1579, loc,
"foreach statement cannot operate on variables of type `{0}' because it does not contain a definition for `{1}' or is inaccessible",
expr.Type.GetSignatureForError (), "GetEnumerator");
}
return null;
}
var method = iface_candidate.Resolve (loc);
if (method == null)
return null;
mg = MethodGroupExpr.CreatePredefined (method, expr.Type, loc);
mg.InstanceExpression = expr;
return mg;
}
MethodGroupExpr ResolveMoveNext (ResolveContext rc, MethodSpec enumerator)
{
var ms = MemberCache.FindMember (enumerator.ReturnType,
MemberFilter.Method ("MoveNext", 0, ParametersCompiled.EmptyReadOnlyParameters, rc.BuiltinTypes.Bool),
BindingRestriction.InstanceOnly) as MethodSpec;
if (ms == null || !ms.IsPublic) {
Error_WrongEnumerator (rc, enumerator);
return null;
}
return MethodGroupExpr.CreatePredefined (ms, enumerator.ReturnType, expr.Location);
}
PropertySpec ResolveCurrent (ResolveContext rc, MethodSpec enumerator)
{
var ps = MemberCache.FindMember (enumerator.ReturnType,
MemberFilter.Property ("Current", null),
BindingRestriction.InstanceOnly) as PropertySpec;
if (ps == null || !ps.IsPublic) {
Error_WrongEnumerator (rc, enumerator);
return null;
}
return ps;
}
public override bool Resolve (BlockContext ec)
{
bool is_dynamic = expr.Type.BuiltinType == BuiltinTypeSpec.Type.Dynamic;
if (is_dynamic) {
expr = Convert.ImplicitConversionRequired (ec, expr, ec.BuiltinTypes.IEnumerable, loc);
} else if (expr.Type.IsNullableType) {
expr = new Nullable.UnwrapCall (expr).Resolve (ec);
}
var get_enumerator_mg = ResolveGetEnumerator (ec);
if (get_enumerator_mg == null) {
return false;
}
var get_enumerator = get_enumerator_mg.BestCandidate;
enumerator_variable = TemporaryVariableReference.Create (get_enumerator.ReturnType, variable.Block, loc);
enumerator_variable.Resolve (ec);
// Prepare bool MoveNext ()
var move_next_mg = ResolveMoveNext (ec, get_enumerator);
if (move_next_mg == null) {
return false;
}
move_next_mg.InstanceExpression = enumerator_variable;
// Prepare ~T~ Current { get; }
var current_prop = ResolveCurrent (ec, get_enumerator);
if (current_prop == null) {
return false;
}
var current_pe = new PropertyExpr (current_prop, loc) { InstanceExpression = enumerator_variable }.Resolve (ec);
if (current_pe == null)
return false;
VarExpr ve = for_each.type as VarExpr;
if (ve != null) {
if (is_dynamic) {
// Source type is dynamic, set element type to dynamic too
variable.Type = ec.BuiltinTypes.Dynamic;
} else {
// Infer implicitly typed local variable from foreach enumerable type
variable.Type = current_pe.Type;
}
} else {
if (is_dynamic) {
// Explicit cast of dynamic collection elements has to be done at runtime
current_pe = EmptyCast.Create (current_pe, ec.BuiltinTypes.Dynamic);
}
variable.Type = for_each.type.ResolveAsType (ec);
if (variable.Type == null)
return false;
current_pe = Convert.ExplicitConversion (ec, current_pe, variable.Type, loc);
if (current_pe == null)
return false;
}
var variable_ref = new LocalVariableReference (variable, loc).Resolve (ec);
if (variable_ref == null)
return false;
for_each.body.AddScopeStatement (new StatementExpression (new CompilerAssign (variable_ref, current_pe, Location.Null), for_each.type.Location));
var init = new Invocation (get_enumerator_mg, null);
statement = new While (new BooleanExpression (new Invocation (move_next_mg, null)),
for_each.body, Location.Null);
var enum_type = enumerator_variable.Type;
//
// Add Dispose method call when enumerator can be IDisposable
//
if (!enum_type.ImplementsInterface (ec.BuiltinTypes.IDisposable, false)) {
if (!enum_type.IsSealed && !TypeSpec.IsValueType (enum_type)) {
//
// Runtime Dispose check
//
var vd = new RuntimeDispose (enumerator_variable.LocalInfo, Location.Null);
vd.Initializer = init;
statement = new Using (vd, statement, Location.Null);
} else {
//
// No Dispose call needed
//
this.init = new SimpleAssign (enumerator_variable, init, Location.Null);
this.init.Resolve (ec);
}
} else {
//
// Static Dispose check
//
var vd = new Using.VariableDeclaration (enumerator_variable.LocalInfo, Location.Null);
vd.Initializer = init;
statement = new Using (vd, statement, Location.Null);
}
return statement.Resolve (ec);
}
protected override void DoEmit (EmitContext ec)
{
enumerator_variable.LocalInfo.CreateBuilder (ec);
if (init != null)
init.EmitStatement (ec);
statement.Emit (ec);
}
#region IErrorHandler Members
bool OverloadResolver.IErrorHandler.AmbiguousCandidates (ResolveContext ec, MemberSpec best, MemberSpec ambiguous)
{
ec.Report.SymbolRelatedToPreviousError (best);
ec.Report.Warning (278, 2, expr.Location,
"`{0}' contains ambiguous implementation of `{1}' pattern. Method `{2}' is ambiguous with method `{3}'",
expr.Type.GetSignatureForError (), "enumerable",
best.GetSignatureForError (), ambiguous.GetSignatureForError ());
ambiguous_getenumerator_name = true;
return true;
}
bool OverloadResolver.IErrorHandler.ArgumentMismatch (ResolveContext rc, MemberSpec best, Argument arg, int index)
{
return false;
}
bool OverloadResolver.IErrorHandler.NoArgumentMatch (ResolveContext rc, MemberSpec best)
{
return false;
}
bool OverloadResolver.IErrorHandler.TypeInferenceFailed (ResolveContext rc, MemberSpec best)
{
return false;
}
#endregion
}
Expression type;
LocalVariable variable;
Expression expr;
Statement statement;
Block body;
public Foreach (Expression type, LocalVariable var, Expression expr, Statement stmt, Block body, Location l)
{
this.type = type;
this.variable = var;
this.expr = expr;
this.statement = stmt;
this.body = body;
loc = l;
}
public Expression Expr {
get { return expr; }
}
public Statement Statement {
get { return statement; }
}
public Expression TypeExpression {
get { return type; }
}
public LocalVariable Variable {
get { return variable; }
}
public override bool Resolve (BlockContext ec)
{
expr = expr.Resolve (ec);
if (expr == null)
return false;
if (expr.IsNull) {
ec.Report.Error (186, loc, "Use of null is not valid in this context");
return false;
}
body.AddStatement (statement);
if (expr.Type.BuiltinType == BuiltinTypeSpec.Type.String) {
statement = new ArrayForeach (this, 1);
} else if (expr.Type is ArrayContainer) {
statement = new ArrayForeach (this, ((ArrayContainer) expr.Type).Rank);
} else {
if (expr.eclass == ExprClass.MethodGroup || expr is AnonymousMethodExpression) {
ec.Report.Error (446, expr.Location, "Foreach statement cannot operate on a `{0}'",
expr.ExprClassName);
return false;
}
statement = new CollectionForeach (this, variable, expr);
}
return statement.Resolve (ec);
}
protected override void DoEmit (EmitContext ec)
{
variable.CreateBuilder (ec);
Label old_begin = ec.LoopBegin, old_end = ec.LoopEnd;
ec.LoopBegin = ec.DefineLabel ();
ec.LoopEnd = ec.DefineLabel ();
statement.Emit (ec);
ec.LoopBegin = old_begin;
ec.LoopEnd = old_end;
}
protected override void CloneTo (CloneContext clonectx, Statement t)
{
Foreach target = (Foreach) t;
target.type = type.Clone (clonectx);
target.expr = expr.Clone (clonectx);
target.body = (Block) body.Clone (clonectx);
target.statement = statement.Clone (clonectx);
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
}
|