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
|
// Copyright (c) 2010-2013 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Threading;
using ICSharpCode.NRefactory.CSharp.TypeSystem;
using ICSharpCode.NRefactory.Semantics;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.TypeSystem.Implementation;
using ICSharpCode.NRefactory.Utils;
namespace ICSharpCode.NRefactory.CSharp.Resolver
{
/// <summary>
/// Contains the main resolver logic.
/// </summary>
/// <remarks>
/// This class is thread-safe.
/// </remarks>
public class CSharpResolver
{
static readonly ResolveResult ErrorResult = ErrorResolveResult.UnknownError;
readonly ICompilation compilation;
internal readonly CSharpConversions conversions;
readonly CSharpTypeResolveContext context;
readonly bool checkForOverflow;
readonly bool isWithinLambdaExpression;
#region Constructor
public CSharpResolver(ICompilation compilation)
{
if (compilation == null)
throw new ArgumentNullException("compilation");
this.compilation = compilation;
this.conversions = CSharpConversions.Get(compilation);
this.context = new CSharpTypeResolveContext(compilation.MainAssembly);
var pc = compilation.MainAssembly.UnresolvedAssembly as CSharpProjectContent;
if (pc != null) {
this.checkForOverflow = pc.CompilerSettings.CheckForOverflow;
}
}
public CSharpResolver(CSharpTypeResolveContext context)
{
if (context == null)
throw new ArgumentNullException("context");
this.compilation = context.Compilation;
this.conversions = CSharpConversions.Get(compilation);
this.context = context;
if (context.CurrentTypeDefinition != null)
currentTypeDefinitionCache = new TypeDefinitionCache(context.CurrentTypeDefinition);
}
private CSharpResolver(ICompilation compilation, CSharpConversions conversions, CSharpTypeResolveContext context, bool checkForOverflow, bool isWithinLambdaExpression, TypeDefinitionCache currentTypeDefinitionCache, ImmutableStack<IVariable> localVariableStack, ObjectInitializerContext objectInitializerStack)
{
this.compilation = compilation;
this.conversions = conversions;
this.context = context;
this.checkForOverflow = checkForOverflow;
this.isWithinLambdaExpression = isWithinLambdaExpression;
this.currentTypeDefinitionCache = currentTypeDefinitionCache;
this.localVariableStack = localVariableStack;
this.objectInitializerStack = objectInitializerStack;
}
#endregion
#region Properties
/// <summary>
/// Gets the compilation used by the resolver.
/// </summary>
public ICompilation Compilation {
get { return compilation; }
}
/// <summary>
/// Gets the current type resolve context.
/// </summary>
public CSharpTypeResolveContext CurrentTypeResolveContext {
get { return context; }
}
CSharpResolver WithContext(CSharpTypeResolveContext newContext)
{
return new CSharpResolver(compilation, conversions, newContext, checkForOverflow, isWithinLambdaExpression, currentTypeDefinitionCache, localVariableStack, objectInitializerStack);
}
/// <summary>
/// Gets whether the current context is <c>checked</c>.
/// </summary>
public bool CheckForOverflow {
get { return checkForOverflow; }
}
/// <summary>
/// Sets whether the current context is <c>checked</c>.
/// </summary>
public CSharpResolver WithCheckForOverflow(bool checkForOverflow)
{
if (checkForOverflow == this.checkForOverflow)
return this;
return new CSharpResolver(compilation, conversions, context, checkForOverflow, isWithinLambdaExpression, currentTypeDefinitionCache, localVariableStack, objectInitializerStack);
}
/// <summary>
/// Gets whether the resolver is currently within a lambda expression.
/// </summary>
public bool IsWithinLambdaExpression {
get { return isWithinLambdaExpression; }
}
/// <summary>
/// Sets whether the resolver is currently within a lambda expression.
/// </summary>
public CSharpResolver WithIsWithinLambdaExpression(bool isWithinLambdaExpression)
{
return new CSharpResolver(compilation, conversions, context, checkForOverflow, isWithinLambdaExpression, currentTypeDefinitionCache, localVariableStack, objectInitializerStack);
}
/// <summary>
/// Gets the current member definition that is used to look up identifiers as parameters
/// or type parameters.
/// </summary>
public IMember CurrentMember {
get { return context.CurrentMember; }
}
/// <summary>
/// Sets the current member definition.
/// </summary>
/// <remarks>Don't forget to also set CurrentTypeDefinition when setting CurrentMember;
/// setting one of the properties does not automatically set the other.</remarks>
public CSharpResolver WithCurrentMember(IMember member)
{
return WithContext(context.WithCurrentMember(member));
}
/// <summary>
/// Gets the current using scope that is used to look up identifiers as class names.
/// </summary>
public ResolvedUsingScope CurrentUsingScope {
get { return context.CurrentUsingScope; }
}
/// <summary>
/// Sets the current using scope that is used to look up identifiers as class names.
/// </summary>
public CSharpResolver WithCurrentUsingScope(ResolvedUsingScope usingScope)
{
return WithContext(context.WithUsingScope(usingScope));
}
#endregion
#region Per-CurrentTypeDefinition Cache
readonly TypeDefinitionCache currentTypeDefinitionCache;
/// <summary>
/// Gets the current type definition.
/// </summary>
public ITypeDefinition CurrentTypeDefinition {
get { return context.CurrentTypeDefinition; }
}
/// <summary>
/// Sets the current type definition.
/// </summary>
public CSharpResolver WithCurrentTypeDefinition(ITypeDefinition typeDefinition)
{
if (this.CurrentTypeDefinition == typeDefinition)
return this;
TypeDefinitionCache newTypeDefinitionCache;
if (typeDefinition != null)
newTypeDefinitionCache = new TypeDefinitionCache(typeDefinition);
else
newTypeDefinitionCache = null;
return new CSharpResolver(compilation, conversions, context.WithCurrentTypeDefinition(typeDefinition),
checkForOverflow, isWithinLambdaExpression, newTypeDefinitionCache, localVariableStack, objectInitializerStack);
}
sealed class TypeDefinitionCache
{
public readonly ITypeDefinition TypeDefinition;
public readonly Dictionary<string, ResolveResult> SimpleNameLookupCacheExpression = new Dictionary<string, ResolveResult>();
public readonly Dictionary<string, ResolveResult> SimpleNameLookupCacheInvocationTarget = new Dictionary<string, ResolveResult>();
public readonly Dictionary<string, ResolveResult> SimpleTypeLookupCache = new Dictionary<string, ResolveResult>();
public TypeDefinitionCache(ITypeDefinition typeDefinition)
{
this.TypeDefinition = typeDefinition;
}
}
#endregion
#region Local Variable Management
// We store the local variables in an immutable stack.
// The beginning of a block is marked by a null entry.
// This data structure is used to allow efficient cloning of the resolver with its local variable context.
readonly ImmutableStack<IVariable> localVariableStack = ImmutableStack<IVariable>.Empty;
CSharpResolver WithLocalVariableStack(ImmutableStack<IVariable> stack)
{
return new CSharpResolver(compilation, conversions, context, checkForOverflow, isWithinLambdaExpression, currentTypeDefinitionCache, stack, objectInitializerStack);
}
/// <summary>
/// Opens a new scope for local variables.
/// </summary>
public CSharpResolver PushBlock()
{
return WithLocalVariableStack(localVariableStack.Push(null));
}
/// <summary>
/// Closes the current scope for local variables; removing all variables in that scope.
/// </summary>
public CSharpResolver PopBlock()
{
var stack = localVariableStack;
IVariable removedVar;
do {
removedVar = stack.Peek();
stack = stack.Pop();
} while (removedVar != null);
return WithLocalVariableStack(stack);
}
/// <summary>
/// Adds a new variable or lambda parameter to the current block.
/// </summary>
public CSharpResolver AddVariable(IVariable variable)
{
if (variable == null)
throw new ArgumentNullException("variable");
return WithLocalVariableStack(localVariableStack.Push(variable));
}
/// <summary>
/// Removes the variable that was just added.
/// </summary>
public CSharpResolver PopLastVariable()
{
if (localVariableStack.Peek() == null)
throw new InvalidOperationException("There is no variable within the current block.");
return WithLocalVariableStack(localVariableStack.Pop());
}
/// <summary>
/// Gets all currently visible local variables and lambda parameters.
/// </summary>
public IEnumerable<IVariable> LocalVariables {
get {
return localVariableStack.Where(v => v != null);
}
}
#endregion
#region Object Initializer Context
sealed class ObjectInitializerContext
{
internal readonly ResolveResult initializedObject;
internal readonly ObjectInitializerContext prev;
public ObjectInitializerContext(ResolveResult initializedObject, CSharpResolver.ObjectInitializerContext prev)
{
this.initializedObject = initializedObject;
this.prev = prev;
}
}
readonly ObjectInitializerContext objectInitializerStack;
CSharpResolver WithObjectInitializerStack(ObjectInitializerContext stack)
{
return new CSharpResolver(compilation, conversions, context, checkForOverflow, isWithinLambdaExpression, currentTypeDefinitionCache, localVariableStack, stack);
}
/// <summary>
/// Pushes the type of the object that is currently being initialized.
/// </summary>
public CSharpResolver PushObjectInitializer(ResolveResult initializedObject)
{
if (initializedObject == null)
throw new ArgumentNullException("initializedObject");
return WithObjectInitializerStack(new ObjectInitializerContext(initializedObject, objectInitializerStack));
}
public CSharpResolver PopObjectInitializer()
{
if (objectInitializerStack == null)
throw new InvalidOperationException();
return WithObjectInitializerStack(objectInitializerStack.prev);
}
/// <summary>
/// Gets whether this context is within an object initializer.
/// </summary>
public bool IsInObjectInitializer {
get { return objectInitializerStack != null; }
}
/// <summary>
/// Gets the current object initializer. This usually is an <see cref="InitializedObjectResolveResult"/>
/// or (for nested initializers) a semantic tree based on an <see cref="InitializedObjectResolveResult"/>.
/// Returns ErrorResolveResult if there is no object initializer.
/// </summary>
public ResolveResult CurrentObjectInitializer {
get {
return objectInitializerStack != null ? objectInitializerStack.initializedObject : ErrorResult;
}
}
/// <summary>
/// Gets the type of the object currently being initialized.
/// Returns SharedTypes.Unknown if no object initializer is currently open (or if the object initializer
/// has unknown type).
/// </summary>
public IType CurrentObjectInitializerType {
get { return CurrentObjectInitializer.Type; }
}
#endregion
#region Clone
/// <summary>
/// Creates a copy of this CSharp resolver.
/// </summary>
[Obsolete("CSharpResolver is immutable, cloning is no longer necessary")]
public CSharpResolver Clone()
{
return this;
}
#endregion
#region ResolveUnaryOperator
#region ResolveUnaryOperator method
public ResolveResult ResolveUnaryOperator(UnaryOperatorType op, ResolveResult expression)
{
if (expression.Type.Kind == TypeKind.Dynamic) {
if (op == UnaryOperatorType.Await) {
return new AwaitResolveResult(SpecialType.Dynamic, new DynamicInvocationResolveResult(new DynamicMemberResolveResult(expression, "GetAwaiter"), DynamicInvocationType.Invocation, EmptyList<ResolveResult>.Instance), SpecialType.Dynamic, null, null, null);
}
else {
return UnaryOperatorResolveResult(SpecialType.Dynamic, op, expression);
}
}
// C# 4.0 spec: §7.3.3 Unary operator overload resolution
string overloadableOperatorName = GetOverloadableOperatorName(op);
if (overloadableOperatorName == null) {
switch (op) {
case UnaryOperatorType.Dereference:
PointerType p = expression.Type as PointerType;
if (p != null)
return UnaryOperatorResolveResult(p.ElementType, op, expression);
else
return ErrorResult;
case UnaryOperatorType.AddressOf:
return UnaryOperatorResolveResult(new PointerType(expression.Type), op, expression);
case UnaryOperatorType.Await: {
ResolveResult getAwaiterMethodGroup = ResolveMemberAccess(expression, "GetAwaiter", EmptyList<IType>.Instance, NameLookupMode.InvocationTarget);
ResolveResult getAwaiterInvocation = ResolveInvocation(getAwaiterMethodGroup, new ResolveResult[0], argumentNames: null, allowOptionalParameters: false);
var lookup = CreateMemberLookup();
IMethod getResultMethod;
IType awaitResultType;
var getResultMethodGroup = lookup.Lookup(getAwaiterInvocation, "GetResult", EmptyList<IType>.Instance, true) as MethodGroupResolveResult;
if (getResultMethodGroup != null) {
var getResultOR = getResultMethodGroup.PerformOverloadResolution(compilation, new ResolveResult[0], allowExtensionMethods: false, conversions: conversions);
getResultMethod = getResultOR.FoundApplicableCandidate ? getResultOR.GetBestCandidateWithSubstitutedTypeArguments() as IMethod : null;
awaitResultType = getResultMethod != null ? getResultMethod.ReturnType : SpecialType.UnknownType;
}
else {
getResultMethod = null;
awaitResultType = SpecialType.UnknownType;
}
var isCompletedRR = lookup.Lookup(getAwaiterInvocation, "IsCompleted", EmptyList<IType>.Instance, false);
var isCompletedProperty = (isCompletedRR is MemberResolveResult ? ((MemberResolveResult)isCompletedRR).Member as IProperty : null);
if (isCompletedProperty != null && (!isCompletedProperty.ReturnType.IsKnownType(KnownTypeCode.Boolean) || !isCompletedProperty.CanGet))
isCompletedProperty = null;
var interfaceOnCompleted = compilation.FindType(KnownTypeCode.INotifyCompletion).GetMethods().FirstOrDefault(x => x.Name == "OnCompleted");
var interfaceUnsafeOnCompleted = compilation.FindType(KnownTypeCode.ICriticalNotifyCompletion).GetMethods().FirstOrDefault(x => x.Name == "UnsafeOnCompleted");
IMethod onCompletedMethod = null;
var candidates = getAwaiterInvocation.Type.GetMethods().Where(x => x.ImplementedInterfaceMembers.Select(y => y.MemberDefinition).Contains(interfaceUnsafeOnCompleted)).ToList();
if (candidates.Count == 0) {
candidates = getAwaiterInvocation.Type.GetMethods().Where(x => x.ImplementedInterfaceMembers.Select(y => y.MemberDefinition).Contains(interfaceOnCompleted)).ToList();
if (candidates.Count == 1)
onCompletedMethod = candidates[0];
}
else if (candidates.Count == 1) {
onCompletedMethod = candidates[0];
}
return new AwaitResolveResult(awaitResultType, getAwaiterInvocation, getAwaiterInvocation.Type, isCompletedProperty, onCompletedMethod, getResultMethod);
}
default:
throw new ArgumentException("Invalid value for UnaryOperatorType", "op");
}
}
// If the type is nullable, get the underlying type:
IType type = NullableType.GetUnderlyingType(expression.Type);
bool isNullable = NullableType.IsNullable(expression.Type);
// the operator is overloadable:
OverloadResolution userDefinedOperatorOR = CreateOverloadResolution(new[] { expression });
foreach (var candidate in GetUserDefinedOperatorCandidates(type, overloadableOperatorName)) {
userDefinedOperatorOR.AddCandidate(candidate);
}
if (userDefinedOperatorOR.FoundApplicableCandidate) {
return CreateResolveResultForUserDefinedOperator(userDefinedOperatorOR, UnaryOperatorExpression.GetLinqNodeType(op, this.CheckForOverflow));
}
expression = UnaryNumericPromotion(op, ref type, isNullable, expression);
CSharpOperators.OperatorMethod[] methodGroup;
CSharpOperators operators = CSharpOperators.Get(compilation);
switch (op) {
case UnaryOperatorType.Increment:
case UnaryOperatorType.Decrement:
case UnaryOperatorType.PostIncrement:
case UnaryOperatorType.PostDecrement:
// C# 4.0 spec: §7.6.9 Postfix increment and decrement operators
// C# 4.0 spec: §7.7.5 Prefix increment and decrement operators
TypeCode code = ReflectionHelper.GetTypeCode(type);
if ((code >= TypeCode.Char && code <= TypeCode.Decimal) || type.Kind == TypeKind.Enum || type.Kind == TypeKind.Pointer)
return UnaryOperatorResolveResult(expression.Type, op, expression, isNullable);
else
return new ErrorResolveResult(expression.Type);
case UnaryOperatorType.Plus:
methodGroup = operators.UnaryPlusOperators;
break;
case UnaryOperatorType.Minus:
methodGroup = CheckForOverflow ? operators.CheckedUnaryMinusOperators : operators.UncheckedUnaryMinusOperators;
break;
case UnaryOperatorType.Not:
methodGroup = operators.LogicalNegationOperators;
break;
case UnaryOperatorType.BitNot:
if (type.Kind == TypeKind.Enum) {
if (expression.IsCompileTimeConstant && !isNullable && expression.ConstantValue != null) {
// evaluate as (E)(~(U)x);
var U = compilation.FindType(expression.ConstantValue.GetType());
var unpackedEnum = new ConstantResolveResult(U, expression.ConstantValue);
return CheckErrorAndResolveUncheckedCast(expression.Type, ResolveUnaryOperator(op, unpackedEnum));
} else {
return UnaryOperatorResolveResult(expression.Type, op, expression, isNullable);
}
} else {
methodGroup = operators.BitwiseComplementOperators;
break;
}
default:
throw new InvalidOperationException();
}
OverloadResolution builtinOperatorOR = CreateOverloadResolution(new[] { expression });
foreach (var candidate in methodGroup) {
builtinOperatorOR.AddCandidate(candidate);
}
CSharpOperators.UnaryOperatorMethod m = (CSharpOperators.UnaryOperatorMethod)builtinOperatorOR.BestCandidate;
IType resultType = m.ReturnType;
if (builtinOperatorOR.BestCandidateErrors != OverloadResolutionErrors.None) {
if (userDefinedOperatorOR.BestCandidate != null) {
// If there are any user-defined operators, prefer those over the built-in operators.
// It'll be a more informative error.
return CreateResolveResultForUserDefinedOperator(userDefinedOperatorOR, UnaryOperatorExpression.GetLinqNodeType(op, this.CheckForOverflow));
} else if (builtinOperatorOR.BestCandidateAmbiguousWith != null) {
// If the best candidate is ambiguous, just use the input type instead
// of picking one of the ambiguous overloads.
return new ErrorResolveResult(expression.Type);
} else {
return new ErrorResolveResult(resultType);
}
} else if (expression.IsCompileTimeConstant && m.CanEvaluateAtCompileTime) {
object val;
try {
val = m.Invoke(this, expression.ConstantValue);
} catch (ArithmeticException) {
return new ErrorResolveResult(resultType);
}
return new ConstantResolveResult(resultType, val);
} else {
expression = Convert(expression, m.Parameters[0].Type, builtinOperatorOR.ArgumentConversions[0]);
return UnaryOperatorResolveResult(resultType, op, expression,
builtinOperatorOR.BestCandidate is OverloadResolution.ILiftedOperator);
}
}
OperatorResolveResult UnaryOperatorResolveResult(IType resultType, UnaryOperatorType op, ResolveResult expression, bool isLifted = false)
{
return new OperatorResolveResult(
resultType, UnaryOperatorExpression.GetLinqNodeType(op, this.CheckForOverflow),
null, isLifted, new[] { expression });
}
#endregion
#region UnaryNumericPromotion
ResolveResult UnaryNumericPromotion(UnaryOperatorType op, ref IType type, bool isNullable, ResolveResult expression)
{
// C# 4.0 spec: §7.3.6.1
TypeCode code = ReflectionHelper.GetTypeCode(type);
if (isNullable && type.Kind == TypeKind.Null)
code = TypeCode.SByte; // cause promotion of null to int32
switch (op) {
case UnaryOperatorType.Minus:
if (code == TypeCode.UInt32) {
type = compilation.FindType(KnownTypeCode.Int64);
return Convert(expression, MakeNullable(type, isNullable),
isNullable ? Conversion.ImplicitNullableConversion : Conversion.ImplicitNumericConversion);
}
goto case UnaryOperatorType.Plus;
case UnaryOperatorType.Plus:
case UnaryOperatorType.BitNot:
if (code >= TypeCode.Char && code <= TypeCode.UInt16) {
type = compilation.FindType(KnownTypeCode.Int32);
return Convert(expression, MakeNullable(type, isNullable),
isNullable ? Conversion.ImplicitNullableConversion : Conversion.ImplicitNumericConversion);
}
break;
}
return expression;
}
#endregion
#region GetOverloadableOperatorName
static string GetOverloadableOperatorName(UnaryOperatorType op)
{
switch (op) {
case UnaryOperatorType.Not:
return "op_LogicalNot";
case UnaryOperatorType.BitNot:
return "op_OnesComplement";
case UnaryOperatorType.Minus:
return "op_UnaryNegation";
case UnaryOperatorType.Plus:
return "op_UnaryPlus";
case UnaryOperatorType.Increment:
case UnaryOperatorType.PostIncrement:
return "op_Increment";
case UnaryOperatorType.Decrement:
case UnaryOperatorType.PostDecrement:
return "op_Decrement";
default:
return null;
}
}
#endregion
#endregion
#region ResolveBinaryOperator
#region ResolveBinaryOperator method
public ResolveResult ResolveBinaryOperator(BinaryOperatorType op, ResolveResult lhs, ResolveResult rhs)
{
if (lhs.Type.Kind == TypeKind.Dynamic || rhs.Type.Kind == TypeKind.Dynamic) {
lhs = Convert(lhs, SpecialType.Dynamic);
rhs = Convert(rhs, SpecialType.Dynamic);
return BinaryOperatorResolveResult(SpecialType.Dynamic, lhs, op, rhs);
}
// C# 4.0 spec: §7.3.4 Binary operator overload resolution
string overloadableOperatorName = GetOverloadableOperatorName(op);
if (overloadableOperatorName == null) {
// Handle logical and/or exactly as bitwise and/or:
// - If the user overloads a bitwise operator, that implicitly creates the corresponding logical operator.
// - If both inputs are compile-time constants, it doesn't matter that we don't short-circuit.
// - If inputs aren't compile-time constants, we don't evaluate anything, so again it doesn't matter that we don't short-circuit
if (op == BinaryOperatorType.ConditionalAnd) {
overloadableOperatorName = GetOverloadableOperatorName(BinaryOperatorType.BitwiseAnd);
} else if (op == BinaryOperatorType.ConditionalOr) {
overloadableOperatorName = GetOverloadableOperatorName(BinaryOperatorType.BitwiseOr);
} else if (op == BinaryOperatorType.NullCoalescing) {
// null coalescing operator is not overloadable and needs to be handled separately
return ResolveNullCoalescingOperator(lhs, rhs);
} else {
throw new ArgumentException("Invalid value for BinaryOperatorType", "op");
}
}
// If the type is nullable, get the underlying type:
bool isNullable = NullableType.IsNullable(lhs.Type) || NullableType.IsNullable(rhs.Type);
IType lhsType = NullableType.GetUnderlyingType(lhs.Type);
IType rhsType = NullableType.GetUnderlyingType(rhs.Type);
// the operator is overloadable:
OverloadResolution userDefinedOperatorOR = CreateOverloadResolution(new[] { lhs, rhs });
HashSet<IParameterizedMember> userOperatorCandidates = new HashSet<IParameterizedMember>();
userOperatorCandidates.UnionWith(GetUserDefinedOperatorCandidates(lhsType, overloadableOperatorName));
userOperatorCandidates.UnionWith(GetUserDefinedOperatorCandidates(rhsType, overloadableOperatorName));
foreach (var candidate in userOperatorCandidates) {
userDefinedOperatorOR.AddCandidate(candidate);
}
if (userDefinedOperatorOR.FoundApplicableCandidate) {
return CreateResolveResultForUserDefinedOperator(userDefinedOperatorOR, BinaryOperatorExpression.GetLinqNodeType(op, this.CheckForOverflow));
}
if (lhsType.Kind == TypeKind.Null && rhsType.IsReferenceType == false
|| lhsType.IsReferenceType == false && rhsType.Kind == TypeKind.Null)
{
isNullable = true;
}
if (op == BinaryOperatorType.ShiftLeft || op == BinaryOperatorType.ShiftRight) {
// special case: the shift operators allow "var x = null << null", producing int?.
if (lhsType.Kind == TypeKind.Null && rhsType.Kind == TypeKind.Null)
isNullable = true;
// for shift operators, do unary promotion independently on both arguments
lhs = UnaryNumericPromotion(UnaryOperatorType.Plus, ref lhsType, isNullable, lhs);
rhs = UnaryNumericPromotion(UnaryOperatorType.Plus, ref rhsType, isNullable, rhs);
} else {
bool allowNullableConstants = op == BinaryOperatorType.Equality || op == BinaryOperatorType.InEquality;
if (!BinaryNumericPromotion(isNullable, ref lhs, ref rhs, allowNullableConstants))
return new ErrorResolveResult(lhs.Type);
}
// re-read underlying types after numeric promotion
lhsType = NullableType.GetUnderlyingType(lhs.Type);
rhsType = NullableType.GetUnderlyingType(rhs.Type);
IEnumerable<CSharpOperators.OperatorMethod> methodGroup;
CSharpOperators operators = CSharpOperators.Get(compilation);
switch (op) {
case BinaryOperatorType.Multiply:
methodGroup = operators.MultiplicationOperators;
break;
case BinaryOperatorType.Divide:
methodGroup = operators.DivisionOperators;
break;
case BinaryOperatorType.Modulus:
methodGroup = operators.RemainderOperators;
break;
case BinaryOperatorType.Add:
methodGroup = operators.AdditionOperators;
{
if (lhsType.Kind == TypeKind.Enum) {
// E operator +(E x, U y);
IType underlyingType = MakeNullable(GetEnumUnderlyingType(lhsType), isNullable);
if (TryConvert(ref rhs, underlyingType)) {
return HandleEnumOperator(isNullable, lhsType, op, lhs, rhs);
}
}
if (rhsType.Kind == TypeKind.Enum) {
// E operator +(U x, E y);
IType underlyingType = MakeNullable(GetEnumUnderlyingType(rhsType), isNullable);
if (TryConvert(ref lhs, underlyingType)) {
return HandleEnumOperator(isNullable, rhsType, op, lhs, rhs);
}
}
if (lhsType.Kind == TypeKind.Delegate && TryConvert(ref rhs, lhsType)) {
return BinaryOperatorResolveResult(lhsType, lhs, op, rhs);
} else if (rhsType.Kind == TypeKind.Delegate && TryConvert(ref lhs, rhsType)) {
return BinaryOperatorResolveResult(rhsType, lhs, op, rhs);
}
if (lhsType is PointerType) {
methodGroup = new [] {
PointerArithmeticOperator(lhsType, lhsType, KnownTypeCode.Int32),
PointerArithmeticOperator(lhsType, lhsType, KnownTypeCode.UInt32),
PointerArithmeticOperator(lhsType, lhsType, KnownTypeCode.Int64),
PointerArithmeticOperator(lhsType, lhsType, KnownTypeCode.UInt64)
};
} else if (rhsType is PointerType) {
methodGroup = new [] {
PointerArithmeticOperator(rhsType, KnownTypeCode.Int32, rhsType),
PointerArithmeticOperator(rhsType, KnownTypeCode.UInt32, rhsType),
PointerArithmeticOperator(rhsType, KnownTypeCode.Int64, rhsType),
PointerArithmeticOperator(rhsType, KnownTypeCode.UInt64, rhsType)
};
}
if (lhsType.Kind == TypeKind.Null && rhsType.Kind == TypeKind.Null)
return new ErrorResolveResult(SpecialType.NullType);
}
break;
case BinaryOperatorType.Subtract:
methodGroup = operators.SubtractionOperators;
{
if (lhsType.Kind == TypeKind.Enum) {
// E operator –(E x, U y);
IType underlyingType = MakeNullable(GetEnumUnderlyingType(lhsType), isNullable);
if (TryConvert(ref rhs, underlyingType)) {
return HandleEnumOperator(isNullable, lhsType, op, lhs, rhs);
}
// U operator –(E x, E y);
if (TryConvert(ref rhs, lhs.Type)) {
return HandleEnumSubtraction(isNullable, lhsType, lhs, rhs);
}
}
if (rhsType.Kind == TypeKind.Enum) {
// U operator –(E x, E y);
if (TryConvert(ref lhs, rhs.Type)) {
return HandleEnumSubtraction(isNullable, rhsType, lhs, rhs);
}
}
if (lhsType.Kind == TypeKind.Delegate && TryConvert(ref rhs, lhsType)) {
return BinaryOperatorResolveResult(lhsType, lhs, op, rhs);
} else if (rhsType.Kind == TypeKind.Delegate && TryConvert(ref lhs, rhsType)) {
return BinaryOperatorResolveResult(rhsType, lhs, op, rhs);
}
if (lhsType is PointerType) {
if (rhsType is PointerType) {
IType int64 = compilation.FindType(KnownTypeCode.Int64);
if (lhsType.Equals(rhsType)) {
return BinaryOperatorResolveResult(int64, lhs, op, rhs);
} else {
return new ErrorResolveResult(int64);
}
}
methodGroup = new [] {
PointerArithmeticOperator(lhsType, lhsType, KnownTypeCode.Int32),
PointerArithmeticOperator(lhsType, lhsType, KnownTypeCode.UInt32),
PointerArithmeticOperator(lhsType, lhsType, KnownTypeCode.Int64),
PointerArithmeticOperator(lhsType, lhsType, KnownTypeCode.UInt64)
};
}
if (lhsType.Kind == TypeKind.Null && rhsType.Kind == TypeKind.Null)
return new ErrorResolveResult(SpecialType.NullType);
}
break;
case BinaryOperatorType.ShiftLeft:
methodGroup = operators.ShiftLeftOperators;
break;
case BinaryOperatorType.ShiftRight:
methodGroup = operators.ShiftRightOperators;
break;
case BinaryOperatorType.Equality:
case BinaryOperatorType.InEquality:
case BinaryOperatorType.LessThan:
case BinaryOperatorType.GreaterThan:
case BinaryOperatorType.LessThanOrEqual:
case BinaryOperatorType.GreaterThanOrEqual:
{
if (lhsType.Kind == TypeKind.Enum && TryConvert(ref rhs, lhs.Type)) {
// bool operator op(E x, E y);
return HandleEnumComparison(op, lhsType, isNullable, lhs, rhs);
} else if (rhsType.Kind == TypeKind.Enum && TryConvert(ref lhs, rhs.Type)) {
// bool operator op(E x, E y);
return HandleEnumComparison(op, rhsType, isNullable, lhs, rhs);
} else if (lhsType is PointerType && rhsType is PointerType) {
return BinaryOperatorResolveResult(compilation.FindType(KnownTypeCode.Boolean), lhs, op, rhs);
}
if (op == BinaryOperatorType.Equality || op == BinaryOperatorType.InEquality) {
if (lhsType.IsReferenceType == true && rhsType.IsReferenceType == true) {
// If it's a reference comparison
if (op == BinaryOperatorType.Equality)
methodGroup = operators.ReferenceEqualityOperators;
else
methodGroup = operators.ReferenceInequalityOperators;
break;
} else if (lhsType.Kind == TypeKind.Null && IsNullableTypeOrNonValueType(rhs.Type)
|| IsNullableTypeOrNonValueType(lhs.Type) && rhsType.Kind == TypeKind.Null) {
// compare type parameter or nullable type with the null literal
return BinaryOperatorResolveResult(compilation.FindType(KnownTypeCode.Boolean), lhs, op, rhs);
}
}
switch (op) {
case BinaryOperatorType.Equality:
methodGroup = operators.ValueEqualityOperators;
break;
case BinaryOperatorType.InEquality:
methodGroup = operators.ValueInequalityOperators;
break;
case BinaryOperatorType.LessThan:
methodGroup = operators.LessThanOperators;
break;
case BinaryOperatorType.GreaterThan:
methodGroup = operators.GreaterThanOperators;
break;
case BinaryOperatorType.LessThanOrEqual:
methodGroup = operators.LessThanOrEqualOperators;
break;
case BinaryOperatorType.GreaterThanOrEqual:
methodGroup = operators.GreaterThanOrEqualOperators;
break;
default:
throw new InvalidOperationException();
}
}
break;
case BinaryOperatorType.BitwiseAnd:
case BinaryOperatorType.BitwiseOr:
case BinaryOperatorType.ExclusiveOr:
{
if (lhsType.Kind == TypeKind.Enum && TryConvert(ref rhs, lhs.Type)) {
// bool operator op(E x, E y);
return HandleEnumOperator(isNullable, lhsType, op, lhs, rhs);
} else if (rhsType.Kind == TypeKind.Enum && TryConvert(ref lhs, rhs.Type)) {
// bool operator op(E x, E y);
return HandleEnumOperator(isNullable, rhsType, op, lhs, rhs);
}
switch (op) {
case BinaryOperatorType.BitwiseAnd:
methodGroup = operators.BitwiseAndOperators;
break;
case BinaryOperatorType.BitwiseOr:
methodGroup = operators.BitwiseOrOperators;
break;
case BinaryOperatorType.ExclusiveOr:
methodGroup = operators.BitwiseXorOperators;
break;
default:
throw new InvalidOperationException();
}
}
break;
case BinaryOperatorType.ConditionalAnd:
methodGroup = operators.LogicalAndOperators;
break;
case BinaryOperatorType.ConditionalOr:
methodGroup = operators.LogicalOrOperators;
break;
default:
throw new InvalidOperationException();
}
OverloadResolution builtinOperatorOR = CreateOverloadResolution(new[] { lhs, rhs });
foreach (var candidate in methodGroup) {
builtinOperatorOR.AddCandidate(candidate);
}
CSharpOperators.BinaryOperatorMethod m = (CSharpOperators.BinaryOperatorMethod)builtinOperatorOR.BestCandidate;
IType resultType = m.ReturnType;
if (builtinOperatorOR.BestCandidateErrors != OverloadResolutionErrors.None) {
// If there are any user-defined operators, prefer those over the built-in operators.
// It'll be a more informative error.
if (userDefinedOperatorOR.BestCandidate != null)
return CreateResolveResultForUserDefinedOperator(userDefinedOperatorOR, BinaryOperatorExpression.GetLinqNodeType(op, this.CheckForOverflow));
else
return new ErrorResolveResult(resultType);
} else if (lhs.IsCompileTimeConstant && rhs.IsCompileTimeConstant && m.CanEvaluateAtCompileTime) {
object val;
try {
val = m.Invoke(this, lhs.ConstantValue, rhs.ConstantValue);
} catch (ArithmeticException) {
return new ErrorResolveResult(resultType);
}
return new ConstantResolveResult(resultType, val);
} else {
lhs = Convert(lhs, m.Parameters[0].Type, builtinOperatorOR.ArgumentConversions[0]);
rhs = Convert(rhs, m.Parameters[1].Type, builtinOperatorOR.ArgumentConversions[1]);
return BinaryOperatorResolveResult(resultType, lhs, op, rhs,
builtinOperatorOR.BestCandidate is OverloadResolution.ILiftedOperator);
}
}
bool IsNullableTypeOrNonValueType(IType type)
{
return NullableType.IsNullable(type) || type.IsReferenceType != false;
}
ResolveResult BinaryOperatorResolveResult(IType resultType, ResolveResult lhs, BinaryOperatorType op, ResolveResult rhs, bool isLifted = false)
{
return new OperatorResolveResult(
resultType, BinaryOperatorExpression.GetLinqNodeType(op, this.CheckForOverflow),
null, isLifted, new[] { lhs, rhs });
}
#endregion
#region Pointer arithmetic
CSharpOperators.BinaryOperatorMethod PointerArithmeticOperator(IType resultType, IType inputType1, KnownTypeCode inputType2)
{
return PointerArithmeticOperator(resultType, inputType1, compilation.FindType(inputType2));
}
CSharpOperators.BinaryOperatorMethod PointerArithmeticOperator(IType resultType, KnownTypeCode inputType1, IType inputType2)
{
return PointerArithmeticOperator(resultType, compilation.FindType(inputType1), inputType2);
}
CSharpOperators.BinaryOperatorMethod PointerArithmeticOperator(IType resultType, IType inputType1, IType inputType2)
{
return new CSharpOperators.BinaryOperatorMethod(compilation) {
ReturnType = resultType,
Parameters = {
new DefaultParameter(inputType1, string.Empty),
new DefaultParameter(inputType2, string.Empty)
}
};
}
#endregion
#region Enum helper methods
IType GetEnumUnderlyingType(IType enumType)
{
ITypeDefinition def = enumType.GetDefinition();
return def != null ? def.EnumUnderlyingType : SpecialType.UnknownType;
}
/// <summary>
/// Handle the case where an enum value is compared with another enum value
/// bool operator op(E x, E y);
/// </summary>
ResolveResult HandleEnumComparison(BinaryOperatorType op, IType enumType, bool isNullable, ResolveResult lhs, ResolveResult rhs)
{
// evaluate as ((U)x op (U)y)
IType elementType = GetEnumUnderlyingType(enumType);
if (lhs.IsCompileTimeConstant && rhs.IsCompileTimeConstant && !isNullable) {
lhs = ResolveCast(elementType, lhs);
if (lhs.IsError)
return lhs;
rhs = ResolveCast(elementType, rhs);
if (rhs.IsError)
return rhs;
return ResolveBinaryOperator(op, lhs, rhs);
}
IType resultType = compilation.FindType(KnownTypeCode.Boolean);
return BinaryOperatorResolveResult(resultType, lhs, op, rhs, isNullable);
}
/// <summary>
/// Handle the case where an enum value is subtracted from another enum value
/// U operator –(E x, E y);
/// </summary>
ResolveResult HandleEnumSubtraction(bool isNullable, IType enumType, ResolveResult lhs, ResolveResult rhs)
{
// evaluate as (U)((U)x – (U)y)
IType elementType = GetEnumUnderlyingType(enumType);
if (lhs.IsCompileTimeConstant && rhs.IsCompileTimeConstant && !isNullable) {
lhs = ResolveCast(elementType, lhs);
if (lhs.IsError)
return lhs;
rhs = ResolveCast(elementType, rhs);
if (rhs.IsError)
return rhs;
return CheckErrorAndResolveUncheckedCast(elementType, ResolveBinaryOperator(BinaryOperatorType.Subtract, lhs, rhs));
}
IType resultType = MakeNullable(elementType, isNullable);
return BinaryOperatorResolveResult(resultType, lhs, BinaryOperatorType.Subtract, rhs, isNullable);
}
/// <summary>
/// Handle the following enum operators:
/// E operator +(E x, U y);
/// E operator +(U x, E y);
/// E operator –(E x, U y);
/// E operator &(E x, E y);
/// E operator |(E x, E y);
/// E operator ^(E x, E y);
/// </summary>
ResolveResult HandleEnumOperator(bool isNullable, IType enumType, BinaryOperatorType op, ResolveResult lhs, ResolveResult rhs)
{
// evaluate as (E)((U)x op (U)y)
if (lhs.IsCompileTimeConstant && rhs.IsCompileTimeConstant && !isNullable) {
IType elementType = GetEnumUnderlyingType(enumType);
lhs = ResolveCast(elementType, lhs);
if (lhs.IsError)
return lhs;
rhs = ResolveCast(elementType, rhs);
if (rhs.IsError)
return rhs;
return CheckErrorAndResolveUncheckedCast(enumType, ResolveBinaryOperator(op, lhs, rhs));
}
IType resultType = MakeNullable(enumType, isNullable);
return BinaryOperatorResolveResult(resultType, lhs, op, rhs, isNullable);
}
IType MakeNullable(IType type, bool isNullable)
{
if (isNullable)
return NullableType.Create(compilation, type);
else
return type;
}
#endregion
#region BinaryNumericPromotion
bool BinaryNumericPromotion(bool isNullable, ref ResolveResult lhs, ref ResolveResult rhs, bool allowNullableConstants)
{
// C# 4.0 spec: §7.3.6.2
TypeCode lhsCode = ReflectionHelper.GetTypeCode(NullableType.GetUnderlyingType(lhs.Type));
TypeCode rhsCode = ReflectionHelper.GetTypeCode(NullableType.GetUnderlyingType(rhs.Type));
// if one of the inputs is the null literal, promote that to the type of the other operand
if (isNullable && lhs.Type.Kind == TypeKind.Null && rhsCode >= TypeCode.Boolean && rhsCode <= TypeCode.Decimal) {
lhs = CastTo(rhsCode, isNullable, lhs, allowNullableConstants);
lhsCode = rhsCode;
} else if (isNullable && rhs.Type.Kind == TypeKind.Null && lhsCode >= TypeCode.Boolean && lhsCode <= TypeCode.Decimal) {
rhs = CastTo(lhsCode, isNullable, rhs, allowNullableConstants);
rhsCode = lhsCode;
}
bool bindingError = false;
if (lhsCode >= TypeCode.Char && lhsCode <= TypeCode.Decimal
&& rhsCode >= TypeCode.Char && rhsCode <= TypeCode.Decimal)
{
TypeCode targetType;
if (lhsCode == TypeCode.Decimal || rhsCode == TypeCode.Decimal) {
targetType = TypeCode.Decimal;
bindingError = (lhsCode == TypeCode.Single || lhsCode == TypeCode.Double
|| rhsCode == TypeCode.Single || rhsCode == TypeCode.Double);
} else if (lhsCode == TypeCode.Double || rhsCode == TypeCode.Double) {
targetType = TypeCode.Double;
} else if (lhsCode == TypeCode.Single || rhsCode == TypeCode.Single) {
targetType = TypeCode.Single;
} else if (lhsCode == TypeCode.UInt64 || rhsCode == TypeCode.UInt64) {
targetType = TypeCode.UInt64;
bindingError = IsSigned(lhsCode, lhs) || IsSigned(rhsCode, rhs);
} else if (lhsCode == TypeCode.Int64 || rhsCode == TypeCode.Int64) {
targetType = TypeCode.Int64;
} else if (lhsCode == TypeCode.UInt32 || rhsCode == TypeCode.UInt32) {
targetType = (IsSigned(lhsCode, lhs) || IsSigned(rhsCode, rhs)) ? TypeCode.Int64 : TypeCode.UInt32;
} else {
targetType = TypeCode.Int32;
}
lhs = CastTo(targetType, isNullable, lhs, allowNullableConstants);
rhs = CastTo(targetType, isNullable, rhs, allowNullableConstants);
}
return !bindingError;
}
bool IsSigned(TypeCode code, ResolveResult rr)
{
// Determine whether the rr with code==ReflectionHelper.GetTypeCode(NullableType.GetUnderlyingType(rr.Type))
// is a signed primitive type.
switch (code) {
case TypeCode.SByte:
case TypeCode.Int16:
return true;
case TypeCode.Int32:
// for int, consider implicit constant expression conversion
if (rr.IsCompileTimeConstant && rr.ConstantValue != null && (int)rr.ConstantValue >= 0)
return false;
else
return true;
case TypeCode.Int64:
// for long, consider implicit constant expression conversion
if (rr.IsCompileTimeConstant && rr.ConstantValue != null && (long)rr.ConstantValue >= 0)
return false;
else
return true;
default:
return false;
}
}
ResolveResult CastTo(TypeCode targetType, bool isNullable, ResolveResult expression, bool allowNullableConstants)
{
IType elementType = compilation.FindType(targetType);
IType nullableType = MakeNullable(elementType, isNullable);
if (nullableType.Equals(expression.Type))
return expression;
if (allowNullableConstants && expression.IsCompileTimeConstant) {
if (expression.ConstantValue == null)
return new ConstantResolveResult(nullableType, null);
ResolveResult rr = ResolveCast(elementType, expression);
if (rr.IsError)
return rr;
Debug.Assert(rr.IsCompileTimeConstant);
return new ConstantResolveResult(nullableType, rr.ConstantValue);
} else {
return Convert(expression, nullableType,
isNullable ? Conversion.ImplicitNullableConversion : Conversion.ImplicitNumericConversion);
}
}
#endregion
#region GetOverloadableOperatorName
static string GetOverloadableOperatorName(BinaryOperatorType op)
{
switch (op) {
case BinaryOperatorType.Add:
return "op_Addition";
case BinaryOperatorType.Subtract:
return "op_Subtraction";
case BinaryOperatorType.Multiply:
return "op_Multiply";
case BinaryOperatorType.Divide:
return "op_Division";
case BinaryOperatorType.Modulus:
return "op_Modulus";
case BinaryOperatorType.BitwiseAnd:
return "op_BitwiseAnd";
case BinaryOperatorType.BitwiseOr:
return "op_BitwiseOr";
case BinaryOperatorType.ExclusiveOr:
return "op_ExclusiveOr";
case BinaryOperatorType.ShiftLeft:
return "op_LeftShift";
case BinaryOperatorType.ShiftRight:
return "op_RightShift";
case BinaryOperatorType.Equality:
return "op_Equality";
case BinaryOperatorType.InEquality:
return "op_Inequality";
case BinaryOperatorType.GreaterThan:
return "op_GreaterThan";
case BinaryOperatorType.LessThan:
return "op_LessThan";
case BinaryOperatorType.GreaterThanOrEqual:
return "op_GreaterThanOrEqual";
case BinaryOperatorType.LessThanOrEqual:
return "op_LessThanOrEqual";
default:
return null;
}
}
#endregion
#region Null coalescing operator
ResolveResult ResolveNullCoalescingOperator(ResolveResult lhs, ResolveResult rhs)
{
if (NullableType.IsNullable(lhs.Type)) {
IType a0 = NullableType.GetUnderlyingType(lhs.Type);
if (TryConvert(ref rhs, a0)) {
return BinaryOperatorResolveResult(a0, lhs, BinaryOperatorType.NullCoalescing, rhs);
}
}
if (TryConvert(ref rhs, lhs.Type)) {
return BinaryOperatorResolveResult(lhs.Type, lhs, BinaryOperatorType.NullCoalescing, rhs);
}
if (TryConvert(ref lhs, rhs.Type)) {
return BinaryOperatorResolveResult(rhs.Type, lhs, BinaryOperatorType.NullCoalescing, rhs);
} else {
return new ErrorResolveResult(lhs.Type);
}
}
#endregion
#endregion
#region Get user-defined operator candidates
IEnumerable<IParameterizedMember> GetUserDefinedOperatorCandidates(IType type, string operatorName)
{
if (operatorName == null)
return EmptyList<IMethod>.Instance;
TypeCode c = ReflectionHelper.GetTypeCode(type);
if (TypeCode.Boolean <= c && c <= TypeCode.Decimal || c == TypeCode.String) {
// The .NET framework contains some of C#'s built-in operators as user-defined operators.
// However, we must not use those as user-defined operators (we would skip numeric promotion).
return EmptyList<IMethod>.Instance;
}
// C# 4.0 spec: §7.3.5 Candidate user-defined operators
var operators = type.GetMethods(m => m.IsOperator && m.Name == operatorName).ToList();
LiftUserDefinedOperators(operators);
return operators;
}
void LiftUserDefinedOperators(List<IMethod> operators)
{
int nonLiftedMethodCount = operators.Count;
// Construct lifted operators
for (int i = 0; i < nonLiftedMethodCount; i++) {
var liftedMethod = LiftUserDefinedOperator(operators[i]);
if (liftedMethod != null)
operators.Add(liftedMethod);
}
}
LiftedUserDefinedOperator LiftUserDefinedOperator(IMethod m)
{
if (IsComparisonOperator(m)) {
if (!m.ReturnType.Equals(compilation.FindType(KnownTypeCode.Boolean)))
return null; // cannot lift this operator
} else {
if (!NullableType.IsNonNullableValueType(m.ReturnType))
return null; // cannot lift this operator
}
for (int i = 0; i < m.Parameters.Count; i++) {
if (!NullableType.IsNonNullableValueType(m.Parameters[i].Type))
return null; // cannot lift this operator
}
return new LiftedUserDefinedOperator(m);
}
static bool IsComparisonOperator(IMethod m)
{
var type = OperatorDeclaration.GetOperatorType(m.Name);
return type.HasValue && type.Value.IsComparisonOperator();
}
sealed class LiftedUserDefinedOperator : SpecializedMethod, OverloadResolution.ILiftedOperator
{
internal readonly IParameterizedMember nonLiftedOperator;
public LiftedUserDefinedOperator(IMethod nonLiftedMethod)
: base(nonLiftedMethod, TypeParameterSubstitution.Identity)
{
this.nonLiftedOperator = nonLiftedMethod;
var substitution = new MakeNullableVisitor(nonLiftedMethod.Compilation);
this.Parameters = base.CreateParameters(substitution);
// Comparison operators keep the 'bool' return type even when lifted.
if (IsComparisonOperator(nonLiftedMethod))
this.ReturnType = nonLiftedMethod.ReturnType;
else
this.ReturnType = nonLiftedMethod.ReturnType.AcceptVisitor(substitution);
}
public IList<IParameter> NonLiftedParameters {
get { return nonLiftedOperator.Parameters; }
}
public override bool Equals(object obj)
{
LiftedUserDefinedOperator op = obj as LiftedUserDefinedOperator;
return op != null && this.nonLiftedOperator.Equals(op.nonLiftedOperator);
}
public override int GetHashCode()
{
return nonLiftedOperator.GetHashCode() ^ 0x7191254;
}
}
sealed class MakeNullableVisitor : TypeVisitor
{
readonly ICompilation compilation;
public MakeNullableVisitor(ICompilation compilation)
{
this.compilation = compilation;
}
public override IType VisitTypeDefinition(ITypeDefinition type)
{
return NullableType.Create(compilation, type);
}
public override IType VisitTypeParameter(ITypeParameter type)
{
return NullableType.Create(compilation, type);
}
public override IType VisitParameterizedType(ParameterizedType type)
{
return NullableType.Create(compilation, type);
}
public override IType VisitOtherType(IType type)
{
return NullableType.Create(compilation, type);
}
}
ResolveResult CreateResolveResultForUserDefinedOperator(OverloadResolution r, System.Linq.Expressions.ExpressionType operatorType)
{
if (r.BestCandidateErrors != OverloadResolutionErrors.None)
return r.CreateResolveResult(null);
IMethod method = (IMethod)r.BestCandidate;
return new OperatorResolveResult(method.ReturnType, operatorType, method,
isLiftedOperator: method is OverloadResolution.ILiftedOperator,
operands: r.GetArgumentsWithConversions());
}
#endregion
#region ResolveCast
bool TryConvert(ref ResolveResult rr, IType targetType)
{
Conversion c = conversions.ImplicitConversion(rr, targetType);
if (c.IsValid) {
rr = Convert(rr, targetType, c);
return true;
} else {
return false;
}
}
ResolveResult Convert(ResolveResult rr, IType targetType)
{
return Convert(rr, targetType, conversions.ImplicitConversion(rr, targetType));
}
ResolveResult Convert(ResolveResult rr, IType targetType, Conversion c)
{
if (c == Conversion.IdentityConversion)
return rr;
else if (rr.IsCompileTimeConstant && c != Conversion.None && !c.IsUserDefined)
return ResolveCast(targetType, rr);
else
return new ConversionResolveResult(targetType, rr, c, checkForOverflow);
}
public ResolveResult ResolveCast(IType targetType, ResolveResult expression)
{
// C# 4.0 spec: §7.7.6 Cast expressions
Conversion c = conversions.ExplicitConversion(expression, targetType);
if (expression.IsCompileTimeConstant && !c.IsUserDefined) {
TypeCode code = ReflectionHelper.GetTypeCode(targetType);
if (code >= TypeCode.Boolean && code <= TypeCode.Decimal && expression.ConstantValue != null) {
try {
return new ConstantResolveResult(targetType, CSharpPrimitiveCast(code, expression.ConstantValue));
} catch (OverflowException) {
return new ErrorResolveResult(targetType);
} catch (InvalidCastException) {
return new ErrorResolveResult(targetType);
}
} else if (code == TypeCode.String) {
if (expression.ConstantValue == null || expression.ConstantValue is string)
return new ConstantResolveResult(targetType, expression.ConstantValue);
else
return new ErrorResolveResult(targetType);
} else if (targetType.Kind == TypeKind.Enum) {
code = ReflectionHelper.GetTypeCode(GetEnumUnderlyingType(targetType));
if (code >= TypeCode.SByte && code <= TypeCode.UInt64 && expression.ConstantValue != null) {
try {
return new ConstantResolveResult(targetType, CSharpPrimitiveCast(code, expression.ConstantValue));
} catch (OverflowException) {
return new ErrorResolveResult(targetType);
} catch (InvalidCastException) {
return new ErrorResolveResult(targetType);
}
}
}
}
return new ConversionResolveResult(targetType, expression, c, checkForOverflow);
}
internal object CSharpPrimitiveCast(TypeCode targetType, object input)
{
return Utils.CSharpPrimitiveCast.Cast(targetType, input, this.CheckForOverflow);
}
ResolveResult CheckErrorAndResolveUncheckedCast(IType targetType, ResolveResult expression)
{
if (expression.IsError)
return expression;
else
return WithCheckForOverflow(false).ResolveCast(targetType, expression);
}
#endregion
#region ResolveSimpleName
public ResolveResult ResolveSimpleName(string identifier, IList<IType> typeArguments, bool isInvocationTarget = false)
{
// C# 4.0 spec: §7.6.2 Simple Names
return LookupSimpleNameOrTypeName(
identifier, typeArguments,
isInvocationTarget ? NameLookupMode.InvocationTarget : NameLookupMode.Expression);
}
public ResolveResult LookupSimpleNameOrTypeName(string identifier, IList<IType> typeArguments, NameLookupMode lookupMode)
{
// C# 4.0 spec: §3.8 Namespace and type names; §7.6.2 Simple Names
if (identifier == null)
throw new ArgumentNullException("identifier");
if (typeArguments == null)
throw new ArgumentNullException("typeArguments");
int k = typeArguments.Count;
if (k == 0) {
if (lookupMode == NameLookupMode.Expression || lookupMode == NameLookupMode.InvocationTarget) {
// Look in local variables
foreach (IVariable v in this.LocalVariables) {
if (v.Name == identifier) {
return new LocalResolveResult(v);
}
}
// Look in parameters of current method
IParameterizedMember parameterizedMember = this.CurrentMember as IParameterizedMember;
if (parameterizedMember != null) {
foreach (IParameter p in parameterizedMember.Parameters) {
if (p.Name == identifier) {
return new LocalResolveResult(p);
}
}
}
}
// look in type parameters of current method
IMethod m = this.CurrentMember as IMethod;
if (m != null) {
foreach (ITypeParameter tp in m.TypeParameters) {
if (tp.Name == identifier)
return new TypeResolveResult(tp);
}
}
}
bool parameterizeResultType = !(typeArguments.Count != 0 && typeArguments.All(t => t.Kind == TypeKind.UnboundTypeArgument));
ResolveResult r = null;
if (currentTypeDefinitionCache != null) {
Dictionary<string, ResolveResult> cache = null;
bool foundInCache = false;
if (k == 0) {
switch (lookupMode) {
case NameLookupMode.Expression:
cache = currentTypeDefinitionCache.SimpleNameLookupCacheExpression;
break;
case NameLookupMode.InvocationTarget:
cache = currentTypeDefinitionCache.SimpleNameLookupCacheInvocationTarget;
break;
case NameLookupMode.Type:
cache = currentTypeDefinitionCache.SimpleTypeLookupCache;
break;
}
if (cache != null) {
lock (cache)
foundInCache = cache.TryGetValue(identifier, out r);
}
}
if (foundInCache) {
r = (r != null ? r.ShallowClone() : null);
} else {
r = LookInCurrentType(identifier, typeArguments, lookupMode, parameterizeResultType);
if (cache != null) {
// also cache missing members (r==null)
lock (cache)
cache[identifier] = r;
}
}
if (r != null)
return r;
}
if (context.CurrentUsingScope == null) {
// If no using scope was specified, we still need to look in the global namespace:
r = LookInUsingScopeNamespace(null, compilation.RootNamespace, identifier, typeArguments, parameterizeResultType);
} else {
if (k == 0 && lookupMode != NameLookupMode.TypeInUsingDeclaration) {
if (context.CurrentUsingScope.ResolveCache.TryGetValue(identifier, out r)) {
r = (r != null ? r.ShallowClone() : null);
} else {
r = LookInCurrentUsingScope(identifier, typeArguments, false, false);
context.CurrentUsingScope.ResolveCache.TryAdd(identifier, r);
}
} else {
r = LookInCurrentUsingScope(identifier, typeArguments, lookupMode == NameLookupMode.TypeInUsingDeclaration, parameterizeResultType);
}
}
if (r != null)
return r;
if (typeArguments.Count == 0 && identifier == "dynamic") {
return new TypeResolveResult(SpecialType.Dynamic);
} else {
return new UnknownIdentifierResolveResult(identifier, typeArguments.Count);
}
}
public bool IsVariableReferenceWithSameType (ResolveResult rr, string identifier, out TypeResolveResult trr)
{
if (!(rr is MemberResolveResult || rr is LocalResolveResult)) {
trr = null;
return false;
}
trr = LookupSimpleNameOrTypeName (identifier, EmptyList<IType>.Instance, NameLookupMode.Type) as TypeResolveResult;
return trr != null && trr.Type.Equals (rr.Type);
}
ResolveResult LookInCurrentType(string identifier, IList<IType> typeArguments, NameLookupMode lookupMode, bool parameterizeResultType)
{
int k = typeArguments.Count;
MemberLookup lookup = CreateMemberLookup(lookupMode);
// look in current type definitions
for (ITypeDefinition t = this.CurrentTypeDefinition; t != null; t = t.DeclaringTypeDefinition) {
if (k == 0) {
// Look for type parameter with that name
var typeParameters = t.TypeParameters;
// Look at all type parameters, including those copied from outer classes,
// so that we can fetch the version with the correct owner.
for (int i = 0; i < typeParameters.Count; i++) {
if (typeParameters[i].Name == identifier)
return new TypeResolveResult(typeParameters[i]);
}
}
if (lookupMode == NameLookupMode.BaseTypeReference && t == this.CurrentTypeDefinition) {
// don't look in current type when resolving a base type reference
continue;
}
ResolveResult r;
if (lookupMode == NameLookupMode.Expression || lookupMode == NameLookupMode.InvocationTarget) {
var targetResolveResult = (t == this.CurrentTypeDefinition ? ResolveThisReference() : new TypeResolveResult(t));
r = lookup.Lookup(targetResolveResult, identifier, typeArguments, lookupMode == NameLookupMode.InvocationTarget);
} else {
r = lookup.LookupType(t, identifier, typeArguments, parameterizeResultType);
}
if (!(r is UnknownMemberResolveResult)) // but do return AmbiguousMemberResolveResult
return r;
}
return null;
}
ResolveResult LookInCurrentUsingScope(string identifier, IList<IType> typeArguments, bool isInUsingDeclaration, bool parameterizeResultType)
{
// look in current namespace definitions
ResolvedUsingScope currentUsingScope = this.CurrentUsingScope;
for (ResolvedUsingScope u = currentUsingScope; u != null; u = u.Parent) {
var resultInNamespace = LookInUsingScopeNamespace(u, u.Namespace, identifier, typeArguments, parameterizeResultType);
if (resultInNamespace != null)
return resultInNamespace;
// then look for aliases:
if (typeArguments.Count == 0) {
if (u.ExternAliases.Contains(identifier)) {
return ResolveExternAlias(identifier);
}
if (!(isInUsingDeclaration && u == currentUsingScope)) {
foreach (var pair in u.UsingAliases) {
if (pair.Key == identifier) {
return pair.Value.ShallowClone();
}
}
}
}
// finally, look in the imported namespaces:
if (!(isInUsingDeclaration && u == currentUsingScope)) {
IType firstResult = null;
foreach (var importedNamespace in u.Usings) {
ITypeDefinition def = importedNamespace.GetTypeDefinition(identifier, typeArguments.Count);
if (def != null) {
IType resultType;
if (parameterizeResultType && typeArguments.Count > 0)
resultType = new ParameterizedType(def, typeArguments);
else
resultType = def;
if (firstResult == null || !TopLevelTypeDefinitionIsAccessible(firstResult.GetDefinition())) {
firstResult = resultType;
} else if (TopLevelTypeDefinitionIsAccessible(def)) {
return new AmbiguousTypeResolveResult(firstResult);
}
}
}
if (firstResult != null)
return new TypeResolveResult(firstResult);
}
// if we didn't find anything: repeat lookup with parent namespace
}
return null;
}
ResolveResult LookInUsingScopeNamespace(ResolvedUsingScope usingScope, INamespace n, string identifier, IList<IType> typeArguments, bool parameterizeResultType)
{
if (n == null)
return null;
// first look for a namespace
int k = typeArguments.Count;
if (k == 0) {
INamespace childNamespace = n.GetChildNamespace(identifier);
if (childNamespace != null) {
if (usingScope != null && usingScope.HasAlias(identifier))
return new AmbiguousTypeResolveResult(new UnknownType(null, identifier));
return new NamespaceResolveResult(childNamespace);
}
}
// then look for a type
ITypeDefinition def = n.GetTypeDefinition(identifier, k);
if (def != null) {
IType result = def;
if (parameterizeResultType && k > 0) {
result = new ParameterizedType(def, typeArguments);
}
if (usingScope != null && usingScope.HasAlias(identifier))
return new AmbiguousTypeResolveResult(result);
else
return new TypeResolveResult(result);
}
return null;
}
bool TopLevelTypeDefinitionIsAccessible(ITypeDefinition typeDef)
{
if (typeDef.IsInternal) {
return typeDef.ParentAssembly.InternalsVisibleTo(compilation.MainAssembly);
}
return true;
}
/// <summary>
/// Looks up an alias (identifier in front of :: operator)
/// </summary>
public ResolveResult ResolveAlias(string identifier)
{
if (identifier == "global")
return new NamespaceResolveResult(compilation.RootNamespace);
for (ResolvedUsingScope n = this.CurrentUsingScope; n != null; n = n.Parent) {
if (n.ExternAliases.Contains(identifier)) {
return ResolveExternAlias(identifier);
}
foreach (var pair in n.UsingAliases) {
if (pair.Key == identifier) {
return (pair.Value as NamespaceResolveResult) ?? ErrorResult;
}
}
}
return ErrorResult;
}
ResolveResult ResolveExternAlias(string alias)
{
INamespace ns = compilation.GetNamespaceForExternAlias(alias);
if (ns != null)
return new NamespaceResolveResult(ns);
else
return ErrorResult;
}
#endregion
#region ResolveMemberAccess
public ResolveResult ResolveMemberAccess(ResolveResult target, string identifier, IList<IType> typeArguments, NameLookupMode lookupMode = NameLookupMode.Expression)
{
// C# 4.0 spec: §7.6.4
bool parameterizeResultType = !(typeArguments.Count != 0 && typeArguments.All(t => t.Kind == TypeKind.UnboundTypeArgument));
NamespaceResolveResult nrr = target as NamespaceResolveResult;
if (nrr != null) {
return ResolveMemberAccessOnNamespace(nrr, identifier, typeArguments, parameterizeResultType);
}
if (target.Type.Kind == TypeKind.Dynamic)
return new DynamicMemberResolveResult(target, identifier);
MemberLookup lookup = CreateMemberLookup(lookupMode);
ResolveResult result;
switch (lookupMode) {
case NameLookupMode.Expression:
result = lookup.Lookup(target, identifier, typeArguments, isInvocation: false);
break;
case NameLookupMode.InvocationTarget:
result = lookup.Lookup(target, identifier, typeArguments, isInvocation: true);
break;
case NameLookupMode.Type:
case NameLookupMode.TypeInUsingDeclaration:
case NameLookupMode.BaseTypeReference:
result = lookup.LookupType(target.Type, identifier, typeArguments, parameterizeResultType);
break;
default:
throw new NotSupportedException("Invalid value for NameLookupMode");
}
if (result is UnknownMemberResolveResult) {
// We intentionally use all extension methods here, not just the eligible ones.
// Proper eligibility checking is only possible for the full invocation
// (after we know the remaining arguments).
// The eligibility check in GetExtensionMethods is only intended for code completion.
var extensionMethods = GetExtensionMethods(identifier, typeArguments);
if (extensionMethods.Count > 0) {
return new MethodGroupResolveResult(target, identifier, EmptyList<MethodListWithDeclaringType>.Instance, typeArguments) {
extensionMethods = extensionMethods
};
}
} else {
MethodGroupResolveResult mgrr = result as MethodGroupResolveResult;
if (mgrr != null) {
Debug.Assert(mgrr.extensionMethods == null);
// set the values that are necessary to make MethodGroupResolveResult.GetExtensionMethods() work
mgrr.resolver = this;
}
}
return result;
}
[Obsolete("Use ResolveMemberAccess() with NameLookupMode.Type instead")]
public ResolveResult ResolveMemberType(ResolveResult target, string identifier, IList<IType> typeArguments)
{
return ResolveMemberAccess(target, identifier, typeArguments, NameLookupMode.Type);
}
ResolveResult ResolveMemberAccessOnNamespace(NamespaceResolveResult nrr, string identifier, IList<IType> typeArguments, bool parameterizeResultType)
{
if (typeArguments.Count == 0) {
INamespace childNamespace = nrr.Namespace.GetChildNamespace(identifier);
if (childNamespace != null)
return new NamespaceResolveResult(childNamespace);
}
ITypeDefinition def = nrr.Namespace.GetTypeDefinition(identifier, typeArguments.Count);
if (def != null) {
if (parameterizeResultType && typeArguments.Count > 0)
return new TypeResolveResult(new ParameterizedType(def, typeArguments));
else
return new TypeResolveResult(def);
}
return ErrorResult;
}
/// <summary>
/// Creates a MemberLookup instance using this resolver's settings.
/// </summary>
public MemberLookup CreateMemberLookup()
{
ITypeDefinition currentTypeDefinition = this.CurrentTypeDefinition;
bool isInEnumMemberInitializer = this.CurrentMember != null && this.CurrentMember.SymbolKind == SymbolKind.Field
&& currentTypeDefinition != null && currentTypeDefinition.Kind == TypeKind.Enum;
return new MemberLookup(currentTypeDefinition, this.Compilation.MainAssembly, isInEnumMemberInitializer);
}
/// <summary>
/// Creates a MemberLookup instance using this resolver's settings.
/// </summary>
public MemberLookup CreateMemberLookup(NameLookupMode lookupMode)
{
if (lookupMode == NameLookupMode.BaseTypeReference && this.CurrentTypeDefinition != null) {
// When looking up a base type reference, treat us as being outside the current type definition
// for accessibility purposes.
// This avoids a stack overflow when referencing a protected class nested inside the base class
// of a parent class. (NameLookupTests.InnerClassInheritingFromProtectedBaseInnerClassShouldNotCauseStackOverflow)
return new MemberLookup(this.CurrentTypeDefinition.DeclaringTypeDefinition, this.Compilation.MainAssembly, false);
} else {
return CreateMemberLookup();
}
}
#endregion
#region ResolveIdentifierInObjectInitializer
public ResolveResult ResolveIdentifierInObjectInitializer(string identifier)
{
MemberLookup memberLookup = CreateMemberLookup();
return memberLookup.Lookup(this.CurrentObjectInitializer, identifier, EmptyList<IType>.Instance, false);
}
#endregion
#region GetExtensionMethods
/// <summary>
/// Gets all extension methods that are available in the current context.
/// </summary>
/// <param name="name">Name of the extension method. Pass null to retrieve all extension methods.</param>
/// <param name="typeArguments">Explicitly provided type arguments.
/// An empty list will return all matching extension method definitions;
/// a non-empty list will return <see cref="SpecializedMethod"/>s for all extension methods
/// with the matching number of type parameters.</param>
/// <remarks>
/// The results are stored in nested lists because they are grouped by using scope.
/// That is, for "using SomeExtensions; namespace X { using MoreExtensions; ... }",
/// the return value will be
/// new List {
/// new List { all extensions from MoreExtensions },
/// new List { all extensions from SomeExtensions }
/// }
/// </remarks>
public List<List<IMethod>> GetExtensionMethods(string name = null, IList<IType> typeArguments = null)
{
return GetExtensionMethods(null, name, typeArguments);
}
/// <summary>
/// Gets the extension methods that are called 'name'
/// and are applicable with a first argument type of 'targetType'.
/// </summary>
/// <param name="targetType">Type of the 'this' argument</param>
/// <param name="name">Name of the extension method. Pass null to retrieve all extension methods.</param>
/// <param name="typeArguments">Explicitly provided type arguments.
/// An empty list will return all matching extension method definitions;
/// a non-empty list will return <see cref="SpecializedMethod"/>s for all extension methods
/// with the matching number of type parameters.</param>
/// <param name="substituteInferredTypes">
/// Specifies whether to produce a <see cref="SpecializedMethod"/>
/// when type arguments could be inferred from <paramref name="targetType"/>. This parameter
/// is only used for inferred types and has no effect if <paramref name="typeArguments"/> is non-empty.
/// </param>
/// <remarks>
/// The results are stored in nested lists because they are grouped by using scope.
/// That is, for "using SomeExtensions; namespace X { using MoreExtensions; ... }",
/// the return value will be
/// new List {
/// new List { all extensions from MoreExtensions },
/// new List { all extensions from SomeExtensions }
/// }
/// </remarks>
public List<List<IMethod>> GetExtensionMethods(IType targetType, string name = null, IList<IType> typeArguments = null, bool substituteInferredTypes = false)
{
List<List<IMethod>> extensionMethodGroups = new List<List<IMethod>>();
foreach (var inputGroup in GetAllExtensionMethods()) {
List<IMethod> outputGroup = new List<IMethod>();
foreach (var method in inputGroup) {
if (name != null && method.Name != name)
continue;
IType[] inferredTypes;
if (typeArguments != null && typeArguments.Count > 0) {
if (method.TypeParameters.Count != typeArguments.Count)
continue;
var sm = method.Specialize(new TypeParameterSubstitution(null, typeArguments));
if (IsEligibleExtensionMethod(compilation, conversions, targetType, sm, false, out inferredTypes))
outputGroup.Add(sm);
} else {
if (IsEligibleExtensionMethod(compilation, conversions, targetType, method, true, out inferredTypes)) {
if (substituteInferredTypes && inferredTypes != null) {
outputGroup.Add(method.Specialize(new TypeParameterSubstitution(null, inferredTypes)));
} else {
outputGroup.Add(method);
}
}
}
}
if (outputGroup.Count > 0)
extensionMethodGroups.Add(outputGroup);
}
return extensionMethodGroups;
}
/// <summary>
/// Checks whether the specified extension method is eligible on the target type.
/// </summary>
/// <param name="targetType">Target type that is passed as first argument to the extension method.</param>
/// <param name="method">The extension method.</param>
/// <param name="useTypeInference">Whether to perform type inference for the method.
/// Use <c>false</c> if <paramref name="method"/> is already parameterized (e.g. when type arguments were given explicitly).
/// Otherwise, use <c>true</c>.
/// </param>
/// <param name="outInferredTypes">If the method is generic and <paramref name="useTypeInference"/> is <c>true</c>,
/// and at least some of the type arguments could be inferred, this parameter receives the inferred type arguments.
/// Since only the type for the first parameter is considered, not all type arguments may be inferred.
/// If an array is returned, any slot with an uninferred type argument will be set to the method's
/// corresponding type parameter.
/// </param>
public static bool IsEligibleExtensionMethod(IType targetType, IMethod method, bool useTypeInference, out IType[] outInferredTypes)
{
if (targetType == null)
throw new ArgumentNullException("targetType");
if (method == null)
throw new ArgumentNullException("method");
var compilation = method.Compilation;
return IsEligibleExtensionMethod(compilation, CSharpConversions.Get(compilation), targetType, method, useTypeInference, out outInferredTypes);
}
static bool IsEligibleExtensionMethod(ICompilation compilation, CSharpConversions conversions, IType targetType, IMethod method, bool useTypeInference, out IType[] outInferredTypes)
{
outInferredTypes = null;
if (targetType == null)
return true;
if (method.Parameters.Count == 0)
return false;
IType thisParameterType = method.Parameters[0].Type;
if (useTypeInference && method.TypeParameters.Count > 0) {
// We need to infer type arguments from targetType:
TypeInference ti = new TypeInference(compilation, conversions);
ResolveResult[] arguments = { new ResolveResult(targetType) };
IType[] parameterTypes = { method.Parameters[0].Type };
bool success;
var inferredTypes = ti.InferTypeArguments(method.TypeParameters, arguments, parameterTypes, out success);
var substitution = new TypeParameterSubstitution(null, inferredTypes);
// Validate that the types that could be inferred (aren't unknown) satisfy the constraints:
bool hasInferredTypes = false;
for (int i = 0; i < inferredTypes.Length; i++) {
if (inferredTypes[i].Kind != TypeKind.Unknown && inferredTypes[i].Kind != TypeKind.UnboundTypeArgument) {
hasInferredTypes = true;
if (!OverloadResolution.ValidateConstraints(method.TypeParameters[i], inferredTypes[i], substitution, conversions))
return false;
} else {
inferredTypes[i] = method.TypeParameters[i]; // do not substitute types that could not be inferred
}
}
if (hasInferredTypes)
outInferredTypes = inferredTypes;
thisParameterType = thisParameterType.AcceptVisitor(substitution);
}
Conversion c = conversions.ImplicitConversion(targetType, thisParameterType);
return c.IsValid && (c.IsIdentityConversion || c.IsReferenceConversion || c.IsBoxingConversion);
}
/// <summary>
/// Gets all extension methods available in the current using scope.
/// This list includes unaccessible
/// </summary>
IList<List<IMethod>> GetAllExtensionMethods()
{
var currentUsingScope = context.CurrentUsingScope;
if (currentUsingScope == null)
return EmptyList<List<IMethod>>.Instance;
List<List<IMethod>> extensionMethodGroups = LazyInit.VolatileRead(ref currentUsingScope.AllExtensionMethods);
if (extensionMethodGroups != null) {
return extensionMethodGroups;
}
extensionMethodGroups = new List<List<IMethod>>();
List<IMethod> m;
for (ResolvedUsingScope scope = currentUsingScope; scope != null; scope = scope.Parent) {
INamespace ns = scope.Namespace;
if (ns != null) {
m = GetExtensionMethods(ns).ToList();
if (m.Count > 0)
extensionMethodGroups.Add(m);
}
m = scope.Usings
.Distinct()
.SelectMany(importedNamespace => GetExtensionMethods(importedNamespace))
.ToList();
if (m.Count > 0)
extensionMethodGroups.Add(m);
}
return LazyInit.GetOrSet(ref currentUsingScope.AllExtensionMethods, extensionMethodGroups);
}
IEnumerable<IMethod> GetExtensionMethods(INamespace ns)
{
// TODO: maybe make this a property on INamespace?
return
from c in ns.Types
where c.IsStatic && c.HasExtensionMethods && c.TypeParameters.Count == 0
from m in c.Methods
where m.IsExtensionMethod
select m;
}
#endregion
#region ResolveInvocation
IList<ResolveResult> AddArgumentNamesIfNecessary(ResolveResult[] arguments, string[] argumentNames) {
if (argumentNames == null) {
return arguments;
}
else {
var result = new ResolveResult[arguments.Length];
for (int i = 0; i < arguments.Length; i++) {
result[i] = (argumentNames[i] != null ? new NamedArgumentResolveResult(argumentNames[i], arguments[i]) : arguments[i]);
}
return result;
}
}
private ResolveResult ResolveInvocation(ResolveResult target, ResolveResult[] arguments, string[] argumentNames, bool allowOptionalParameters)
{
// C# 4.0 spec: §7.6.5
if (target.Type.Kind == TypeKind.Dynamic) {
return new DynamicInvocationResolveResult(target, DynamicInvocationType.Invocation, AddArgumentNamesIfNecessary(arguments, argumentNames));
}
bool isDynamic = arguments.Any(a => a.Type.Kind == TypeKind.Dynamic);
MethodGroupResolveResult mgrr = target as MethodGroupResolveResult;
if (mgrr != null) {
if (isDynamic) {
// If we have dynamic arguments, we need to represent the invocation as a dynamic invocation if there is more than one applicable method.
var or2 = CreateOverloadResolution(arguments, argumentNames, mgrr.TypeArguments.ToArray());
var applicableMethods = mgrr.MethodsGroupedByDeclaringType.SelectMany(m => m, (x, m) => new { x.DeclaringType, Method = m }).Where(x => OverloadResolution.IsApplicable(or2.AddCandidate(x.Method))).ToList();
if (applicableMethods.Count > 1) {
ResolveResult actualTarget;
if (applicableMethods.All(x => x.Method.IsStatic) && !(mgrr.TargetResult is TypeResolveResult))
actualTarget = new TypeResolveResult(mgrr.TargetType);
else
actualTarget = mgrr.TargetResult;
var l = new List<MethodListWithDeclaringType>();
foreach (var m in applicableMethods) {
if (l.Count == 0 || l[l.Count - 1].DeclaringType != m.DeclaringType)
l.Add(new MethodListWithDeclaringType(m.DeclaringType));
l[l.Count - 1].Add(m.Method);
}
return new DynamicInvocationResolveResult(new MethodGroupResolveResult(actualTarget, mgrr.MethodName, l, mgrr.TypeArguments), DynamicInvocationType.Invocation, AddArgumentNamesIfNecessary(arguments, argumentNames));
}
}
OverloadResolution or = mgrr.PerformOverloadResolution(compilation, arguments, argumentNames, checkForOverflow: checkForOverflow, conversions: conversions, allowOptionalParameters: allowOptionalParameters);
if (or.BestCandidate != null) {
if (or.BestCandidate.IsStatic && !or.IsExtensionMethodInvocation && !(mgrr.TargetResult is TypeResolveResult))
return or.CreateResolveResult(new TypeResolveResult(mgrr.TargetType), returnTypeOverride: isDynamic ? SpecialType.Dynamic : null);
else
return or.CreateResolveResult(mgrr.TargetResult, returnTypeOverride: isDynamic ? SpecialType.Dynamic : null);
} else {
// No candidate found at all (not even an inapplicable one).
// This can happen with empty method groups (as sometimes used with extension methods)
return new UnknownMethodResolveResult(
mgrr.TargetType, mgrr.MethodName, mgrr.TypeArguments, CreateParameters(arguments, argumentNames));
}
}
UnknownMemberResolveResult umrr = target as UnknownMemberResolveResult;
if (umrr != null) {
return new UnknownMethodResolveResult(umrr.TargetType, umrr.MemberName, umrr.TypeArguments, CreateParameters(arguments, argumentNames));
}
UnknownIdentifierResolveResult uirr = target as UnknownIdentifierResolveResult;
if (uirr != null && CurrentTypeDefinition != null) {
return new UnknownMethodResolveResult(CurrentTypeDefinition, uirr.Identifier, EmptyList<IType>.Instance, CreateParameters(arguments, argumentNames));
}
IMethod invokeMethod = target.Type.GetDelegateInvokeMethod();
if (invokeMethod != null) {
OverloadResolution or = CreateOverloadResolution(arguments, argumentNames);
or.AddCandidate(invokeMethod);
return new CSharpInvocationResolveResult(
target, invokeMethod, //invokeMethod.ReturnType.Resolve(context),
or.GetArgumentsWithConversionsAndNames(), or.BestCandidateErrors,
isExpandedForm: or.BestCandidateIsExpandedForm,
isDelegateInvocation: true,
argumentToParameterMap: or.GetArgumentToParameterMap(),
returnTypeOverride: isDynamic ? SpecialType.Dynamic : null);
}
return ErrorResult;
}
/// <summary>
/// Resolves an invocation.
/// </summary>
/// <param name="target">The target of the invocation. Usually a MethodGroupResolveResult.</param>
/// <param name="arguments">
/// Arguments passed to the method.
/// The resolver may mutate this array to wrap elements in <see cref="ConversionResolveResult"/>s!
/// </param>
/// <param name="argumentNames">
/// The argument names. Pass the null string for positional arguments.
/// </param>
/// <returns>InvocationResolveResult or UnknownMethodResolveResult</returns>
public ResolveResult ResolveInvocation(ResolveResult target, ResolveResult[] arguments, string[] argumentNames = null)
{
return ResolveInvocation(target, arguments, argumentNames, allowOptionalParameters: true);
}
List<IParameter> CreateParameters(ResolveResult[] arguments, string[] argumentNames)
{
List<IParameter> list = new List<IParameter>();
if (argumentNames == null) {
argumentNames = new string[arguments.Length];
} else {
if (argumentNames.Length != arguments.Length)
throw new ArgumentException();
argumentNames = (string[])argumentNames.Clone();
}
for (int i = 0; i < arguments.Length; i++) {
// invent argument names where necessary:
if (argumentNames[i] == null) {
string newArgumentName = GuessParameterName(arguments[i]);
if (argumentNames.Contains(newArgumentName)) {
// disambiguate argument name (e.g. add a number)
int num = 1;
string newName;
do {
newName = newArgumentName + num.ToString();
num++;
} while(argumentNames.Contains(newName));
newArgumentName = newName;
}
argumentNames[i] = newArgumentName;
}
// create the parameter:
ByReferenceResolveResult brrr = arguments[i] as ByReferenceResolveResult;
if (brrr != null) {
list.Add(new DefaultParameter(arguments[i].Type, argumentNames[i], isRef: brrr.IsRef, isOut: brrr.IsOut));
} else {
// argument might be a lambda or delegate type, so we have to try to guess the delegate type
IType type = arguments[i].Type;
if (type.Kind == TypeKind.Null || type.Kind == TypeKind.Unknown) {
list.Add(new DefaultParameter(compilation.FindType(KnownTypeCode.Object), argumentNames[i]));
} else {
list.Add(new DefaultParameter(type, argumentNames[i]));
}
}
}
return list;
}
static string GuessParameterName(ResolveResult rr)
{
MemberResolveResult mrr = rr as MemberResolveResult;
if (mrr != null)
return mrr.Member.Name;
UnknownMemberResolveResult umrr = rr as UnknownMemberResolveResult;
if (umrr != null)
return umrr.MemberName;
MethodGroupResolveResult mgrr = rr as MethodGroupResolveResult;
if (mgrr != null)
return mgrr.MethodName;
LocalResolveResult vrr = rr as LocalResolveResult;
if (vrr != null)
return MakeParameterName(vrr.Variable.Name);
if (rr.Type.Kind != TypeKind.Unknown && !string.IsNullOrEmpty(rr.Type.Name)) {
return MakeParameterName(rr.Type.Name);
} else {
return "parameter";
}
}
static string MakeParameterName(string variableName)
{
if (string.IsNullOrEmpty(variableName))
return "parameter";
if (variableName.Length > 1 && variableName[0] == '_')
variableName = variableName.Substring(1);
return char.ToLower(variableName[0]) + variableName.Substring(1);
}
OverloadResolution CreateOverloadResolution(ResolveResult[] arguments, string[] argumentNames = null, IType[] typeArguments = null)
{
var or = new OverloadResolution(compilation, arguments, argumentNames, typeArguments, conversions);
or.CheckForOverflow = checkForOverflow;
return or;
}
#endregion
#region ResolveIndexer
/// <summary>
/// Resolves an indexer access.
/// </summary>
/// <param name="target">Target expression.</param>
/// <param name="arguments">
/// Arguments passed to the indexer.
/// The resolver may mutate this array to wrap elements in <see cref="ConversionResolveResult"/>s!
/// </param>
/// <param name="argumentNames">
/// The argument names. Pass the null string for positional arguments.
/// </param>
/// <returns>ArrayAccessResolveResult, InvocationResolveResult, or ErrorResolveResult</returns>
public ResolveResult ResolveIndexer(ResolveResult target, ResolveResult[] arguments, string[] argumentNames = null)
{
switch (target.Type.Kind) {
case TypeKind.Dynamic:
return new DynamicInvocationResolveResult(target, DynamicInvocationType.Indexing, AddArgumentNamesIfNecessary(arguments, argumentNames));
case TypeKind.Array:
case TypeKind.Pointer:
// §7.6.6.1 Array access / §18.5.3 Pointer element access
AdjustArrayAccessArguments(arguments);
return new ArrayAccessResolveResult(((TypeWithElementType)target.Type).ElementType, target, arguments);
}
// §7.6.6.2 Indexer access
MemberLookup lookup = CreateMemberLookup();
var indexers = lookup.LookupIndexers(target.Type);
if (arguments.Any(a => a.Type.Kind == TypeKind.Dynamic)) {
// If we have dynamic arguments, we need to represent the invocation as a dynamic invocation if there is more than one applicable indexer.
var or2 = CreateOverloadResolution(arguments, argumentNames, null);
var applicableIndexers = indexers.SelectMany(x => x).Where(m => OverloadResolution.IsApplicable(or2.AddCandidate(m))).ToList();
if (applicableIndexers.Count > 1) {
return new DynamicInvocationResolveResult(target, DynamicInvocationType.Indexing, AddArgumentNamesIfNecessary(arguments, argumentNames));
}
}
OverloadResolution or = CreateOverloadResolution(arguments, argumentNames);
or.AddMethodLists(indexers);
if (or.BestCandidate != null) {
return or.CreateResolveResult(target);
} else {
return ErrorResult;
}
}
/// <summary>
/// Converts all arguments to int,uint,long or ulong.
/// </summary>
void AdjustArrayAccessArguments(ResolveResult[] arguments)
{
for (int i = 0; i < arguments.Length; i++) {
if (!(TryConvert(ref arguments[i], compilation.FindType(KnownTypeCode.Int32)) ||
TryConvert(ref arguments[i], compilation.FindType(KnownTypeCode.UInt32)) ||
TryConvert(ref arguments[i], compilation.FindType(KnownTypeCode.Int64)) ||
TryConvert(ref arguments[i], compilation.FindType(KnownTypeCode.UInt64))))
{
// conversion failed
arguments[i] = Convert(arguments[i], compilation.FindType(KnownTypeCode.Int32), Conversion.None);
}
}
}
#endregion
#region ResolveObjectCreation
/// <summary>
/// Resolves an object creation.
/// </summary>
/// <param name="type">Type of the object to create.</param>
/// <param name="arguments">
/// Arguments passed to the constructor.
/// The resolver may mutate this array to wrap elements in <see cref="ConversionResolveResult"/>s!
/// </param>
/// <param name="argumentNames">
/// The argument names. Pass the null string for positional arguments.
/// </param>
/// <param name="allowProtectedAccess">
/// Whether to allow calling protected constructors.
/// This should be false except when resolving constructor initializers.
/// </param>
/// <param name="initializerStatements">
/// Statements for Objects/Collections initializer.
/// <see cref="InvocationResolveResult.InitializerStatements"/>
/// </param>
/// <returns>InvocationResolveResult or ErrorResolveResult</returns>
public ResolveResult ResolveObjectCreation(IType type, ResolveResult[] arguments, string[] argumentNames = null, bool allowProtectedAccess = false, IList<ResolveResult> initializerStatements = null)
{
if (type.Kind == TypeKind.Delegate && arguments.Length == 1) {
ResolveResult input = arguments[0];
IMethod invoke = input.Type.GetDelegateInvokeMethod();
if (invoke != null) {
input = new MethodGroupResolveResult(
input, invoke.Name,
methods: new[] { new MethodListWithDeclaringType(invoke.DeclaringType) { invoke } },
typeArguments: EmptyList<IType>.Instance
);
}
return Convert(input, type);
}
OverloadResolution or = CreateOverloadResolution(arguments, argumentNames);
MemberLookup lookup = CreateMemberLookup();
var allApplicable = (arguments.Any(a => a.Type.Kind == TypeKind.Dynamic) ? new List<IMethod>() : null);
foreach (IMethod ctor in type.GetConstructors()) {
if (lookup.IsAccessible(ctor, allowProtectedAccess)) {
var orErrors = or.AddCandidate(ctor);
if (allApplicable != null && OverloadResolution.IsApplicable(orErrors))
allApplicable.Add(ctor);
}
else
or.AddCandidate(ctor, OverloadResolutionErrors.Inaccessible);
}
if (allApplicable != null && allApplicable.Count > 1) {
// If we have dynamic arguments, we need to represent the invocation as a dynamic invocation if there is more than one applicable constructor.
return new DynamicInvocationResolveResult(new MethodGroupResolveResult(null, allApplicable[0].Name, new[] { new MethodListWithDeclaringType(type, allApplicable) }, null), DynamicInvocationType.ObjectCreation, AddArgumentNamesIfNecessary(arguments, argumentNames), initializerStatements);
}
if (or.BestCandidate != null) {
return or.CreateResolveResult(null, initializerStatements);
} else {
return new ErrorResolveResult(type);
}
}
#endregion
#region ResolveSizeOf
/// <summary>
/// Resolves 'sizeof(type)'.
/// </summary>
public ResolveResult ResolveSizeOf(IType type)
{
IType int32 = compilation.FindType(KnownTypeCode.Int32);
int? size = null;
var typeForConstant = (type.Kind == TypeKind.Enum) ? type.GetDefinition().EnumUnderlyingType : type;
switch (ReflectionHelper.GetTypeCode(typeForConstant)) {
case TypeCode.Boolean:
case TypeCode.SByte:
case TypeCode.Byte:
size = 1;
break;
case TypeCode.Char:
case TypeCode.Int16:
case TypeCode.UInt16:
size = 2;
break;
case TypeCode.Int32:
case TypeCode.UInt32:
case TypeCode.Single:
size = 4;
break;
case TypeCode.Int64:
case TypeCode.UInt64:
case TypeCode.Double:
size = 8;
break;
}
return new SizeOfResolveResult(int32, type, size);
}
#endregion
#region Resolve This/Base Reference
/// <summary>
/// Resolves 'this'.
/// </summary>
public ResolveResult ResolveThisReference()
{
ITypeDefinition t = CurrentTypeDefinition;
if (t != null) {
if (t.TypeParameterCount != 0) {
// Self-parameterize the type
return new ThisResolveResult(new ParameterizedType(t, t.TypeParameters));
} else {
return new ThisResolveResult(t);
}
}
return ErrorResult;
}
/// <summary>
/// Resolves 'base'.
/// </summary>
public ResolveResult ResolveBaseReference()
{
ITypeDefinition t = CurrentTypeDefinition;
if (t != null) {
foreach (IType baseType in t.DirectBaseTypes) {
if (baseType.Kind != TypeKind.Unknown && baseType.Kind != TypeKind.Interface) {
return new ThisResolveResult(baseType, causesNonVirtualInvocation: true);
}
}
}
return ErrorResult;
}
#endregion
#region ResolveConditional
/// <summary>
/// Converts the input to <c>bool</c> using the rules for boolean expressions.
/// That is, <c>operator true</c> is used if a regular conversion to <c>bool</c> is not possible.
/// </summary>
public ResolveResult ResolveCondition(ResolveResult input)
{
if (input == null)
throw new ArgumentNullException("input");
IType boolean = compilation.FindType(KnownTypeCode.Boolean);
Conversion c = conversions.ImplicitConversion(input, boolean);
if (!c.IsValid) {
var opTrue = input.Type.GetMethods(m => m.IsOperator && m.Name == "op_True").FirstOrDefault();
if (opTrue != null) {
c = Conversion.UserDefinedConversion(opTrue, isImplicit: true, conversionBeforeUserDefinedOperator: Conversion.None, conversionAfterUserDefinedOperator: Conversion.None);
}
}
return Convert(input, boolean, c);
}
/// <summary>
/// Converts the negated input to <c>bool</c> using the rules for boolean expressions.
/// Computes <c>!(bool)input</c> if the implicit cast to bool is valid; otherwise
/// computes <c>input.operator false()</c>.
/// </summary>
public ResolveResult ResolveConditionFalse(ResolveResult input)
{
if (input == null)
throw new ArgumentNullException("input");
IType boolean = compilation.FindType(KnownTypeCode.Boolean);
Conversion c = conversions.ImplicitConversion(input, boolean);
if (!c.IsValid) {
var opFalse = input.Type.GetMethods(m => m.IsOperator && m.Name == "op_False").FirstOrDefault();
if (opFalse != null) {
c = Conversion.UserDefinedConversion(opFalse, isImplicit: true, conversionBeforeUserDefinedOperator: Conversion.None, conversionAfterUserDefinedOperator: Conversion.None);
return Convert(input, boolean, c);
}
}
return ResolveUnaryOperator(UnaryOperatorType.Not, Convert(input, boolean, c));
}
public ResolveResult ResolveConditional(ResolveResult condition, ResolveResult trueExpression, ResolveResult falseExpression)
{
// C# 4.0 spec §7.14: Conditional operator
bool isValid;
IType resultType;
if (trueExpression.Type.Kind == TypeKind.Dynamic || falseExpression.Type.Kind == TypeKind.Dynamic) {
resultType = SpecialType.Dynamic;
isValid = TryConvert(ref trueExpression, resultType) & TryConvert(ref falseExpression, resultType);
} else if (HasType(trueExpression) && HasType(falseExpression)) {
Conversion t2f = conversions.ImplicitConversion(trueExpression, falseExpression.Type);
Conversion f2t = conversions.ImplicitConversion(falseExpression, trueExpression.Type);
// The operator is valid:
// a) if there's a conversion in one direction but not the other
// b) if there are conversions in both directions, and the types are equivalent
if (IsBetterConditionalConversion(t2f, f2t)) {
resultType = falseExpression.Type;
isValid = true;
trueExpression = Convert(trueExpression, resultType, t2f);
} else if (IsBetterConditionalConversion(f2t, t2f)) {
resultType = trueExpression.Type;
isValid = true;
falseExpression = Convert(falseExpression, resultType, f2t);
} else {
resultType = trueExpression.Type;
isValid = trueExpression.Type.Equals(falseExpression.Type);
}
} else if (HasType(trueExpression)) {
resultType = trueExpression.Type;
isValid = TryConvert(ref falseExpression, resultType);
} else if (HasType(falseExpression)) {
resultType = falseExpression.Type;
isValid = TryConvert(ref trueExpression, resultType);
} else {
return ErrorResult;
}
condition = ResolveCondition(condition);
if (isValid) {
if (condition.IsCompileTimeConstant && trueExpression.IsCompileTimeConstant && falseExpression.IsCompileTimeConstant) {
bool? val = condition.ConstantValue as bool?;
if (val == true)
return trueExpression;
else if (val == false)
return falseExpression;
}
return new OperatorResolveResult(resultType, System.Linq.Expressions.ExpressionType.Conditional,
condition, trueExpression, falseExpression);
} else {
return new ErrorResolveResult(resultType);
}
}
bool IsBetterConditionalConversion(Conversion c1, Conversion c2)
{
// Valid is better than ImplicitConstantExpressionConversion is better than invalid
if (!c1.IsValid)
return false;
if (c1 != Conversion.ImplicitConstantExpressionConversion && c2 == Conversion.ImplicitConstantExpressionConversion)
return true;
return !c2.IsValid;
}
bool HasType(ResolveResult r)
{
return r.Type.Kind != TypeKind.Unknown && r.Type.Kind != TypeKind.Null;
}
#endregion
#region ResolvePrimitive
public ResolveResult ResolvePrimitive(object value)
{
if (value == null) {
return new ResolveResult(SpecialType.NullType);
} else {
TypeCode typeCode = Type.GetTypeCode(value.GetType());
IType type = compilation.FindType(typeCode);
return new ConstantResolveResult(type, value);
}
}
#endregion
#region ResolveDefaultValue
public ResolveResult ResolveDefaultValue(IType type)
{
return new ConstantResolveResult(type, GetDefaultValue(type));
}
public static object GetDefaultValue(IType type)
{
ITypeDefinition typeDef = type.GetDefinition();
if (typeDef == null)
return null;
if (typeDef.Kind == TypeKind.Enum) {
typeDef = typeDef.EnumUnderlyingType.GetDefinition();
if (typeDef == null)
return null;
}
switch (typeDef.KnownTypeCode) {
case KnownTypeCode.Boolean:
return false;
case KnownTypeCode.Char:
return '\0';
case KnownTypeCode.SByte:
return (sbyte)0;
case KnownTypeCode.Byte:
return (byte)0;
case KnownTypeCode.Int16:
return (short)0;
case KnownTypeCode.UInt16:
return (ushort)0;
case KnownTypeCode.Int32:
return 0;
case KnownTypeCode.UInt32:
return 0U;
case KnownTypeCode.Int64:
return 0L;
case KnownTypeCode.UInt64:
return 0UL;
case KnownTypeCode.Single:
return 0f;
case KnownTypeCode.Double:
return 0.0;
case KnownTypeCode.Decimal:
return 0m;
default:
return null;
}
}
#endregion
#region ResolveArrayCreation
/// <summary>
/// Resolves an array creation.
/// </summary>
/// <param name="elementType">
/// The array element type.
/// Pass null to resolve an implicitly-typed array creation.
/// </param>
/// <param name="sizeArguments">
/// The size arguments.
/// The length of this array will be used as the number of dimensions of the array type.
/// Negative values will be treated as errors.
/// </param>
/// <param name="initializerElements">
/// The initializer elements. May be null if no array initializer was specified.
/// The resolver may mutate this array to wrap elements in <see cref="ConversionResolveResult"/>s!
/// </param>
public ArrayCreateResolveResult ResolveArrayCreation(IType elementType, int[] sizeArguments, ResolveResult[] initializerElements = null)
{
ResolveResult[] sizeArgResults = new ResolveResult[sizeArguments.Length];
for (int i = 0; i < sizeArguments.Length; i++) {
if (sizeArguments[i] < 0)
sizeArgResults[i] = ErrorResolveResult.UnknownError;
else
sizeArgResults[i] = new ConstantResolveResult(compilation.FindType(KnownTypeCode.Int32), sizeArguments[i]);
}
return ResolveArrayCreation(elementType, sizeArgResults, initializerElements);
}
/// <summary>
/// Resolves an array creation.
/// </summary>
/// <param name="elementType">
/// The array element type.
/// Pass null to resolve an implicitly-typed array creation.
/// </param>
/// <param name="sizeArguments">
/// The size arguments.
/// The length of this array will be used as the number of dimensions of the array type.
/// The resolver may mutate this array to wrap elements in <see cref="ConversionResolveResult"/>s!
/// </param>
/// <param name="initializerElements">
/// The initializer elements. May be null if no array initializer was specified.
/// The resolver may mutate this array to wrap elements in <see cref="ConversionResolveResult"/>s!
/// </param>
public ArrayCreateResolveResult ResolveArrayCreation(IType elementType, ResolveResult[] sizeArguments, ResolveResult[] initializerElements = null)
{
int dimensions = sizeArguments.Length;
if (dimensions == 0)
throw new ArgumentException("sizeArguments.Length must not be 0");
if (elementType == null) {
TypeInference typeInference = new TypeInference(compilation, conversions);
bool success;
elementType = typeInference.GetBestCommonType(initializerElements, out success);
}
IType arrayType = new ArrayType(compilation, elementType, dimensions);
AdjustArrayAccessArguments(sizeArguments);
if (initializerElements != null) {
for (int i = 0; i < initializerElements.Length; i++) {
initializerElements[i] = Convert(initializerElements[i], elementType);
}
}
return new ArrayCreateResolveResult(arrayType, sizeArguments, initializerElements);
}
#endregion
public ResolveResult ResolveTypeOf(IType referencedType)
{
return new TypeOfResolveResult(compilation.FindType(KnownTypeCode.Type), referencedType);
}
#region ResolveAssignment
public ResolveResult ResolveAssignment(AssignmentOperatorType op, ResolveResult lhs, ResolveResult rhs)
{
var linqOp = AssignmentExpression.GetLinqNodeType(op, this.CheckForOverflow);
var bop = AssignmentExpression.GetCorrespondingBinaryOperator(op);
if (bop == null) {
return new OperatorResolveResult(lhs.Type, linqOp, lhs, this.Convert(rhs, lhs.Type));
}
ResolveResult bopResult = ResolveBinaryOperator(bop.Value, lhs, rhs);
OperatorResolveResult opResult = bopResult as OperatorResolveResult;
if (opResult == null || opResult.Operands.Count != 2)
return bopResult;
return new OperatorResolveResult(lhs.Type, linqOp, opResult.UserDefinedOperatorMethod, opResult.IsLiftedOperator,
new [] { lhs, opResult.Operands[1] });
}
#endregion
}
}
|