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
|
//
// Expression.cs
//
// Author:
// Jb Evain (jbevain@novell.com)
// Miguel de Icaza (miguel@novell.com)
//
// (C) 2008 Novell, Inc. (http://www.novell.com)
//
// 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;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
namespace System.Linq.Expressions {
public abstract class Expression {
ExpressionType node_type;
Type type;
internal const BindingFlags PublicInstance = BindingFlags.Public | BindingFlags.Instance | BindingFlags.FlattenHierarchy;
internal const BindingFlags NonPublicInstance = BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy;
internal const BindingFlags PublicStatic = BindingFlags.Public | BindingFlags.Static | BindingFlags.FlattenHierarchy;
internal const BindingFlags AllInstance = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.FlattenHierarchy;
internal const BindingFlags AllStatic = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.FlattenHierarchy;
internal const BindingFlags All = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance | BindingFlags.FlattenHierarchy;
public ExpressionType NodeType {
get { return node_type; }
}
public Type Type {
get { return type; }
}
protected Expression (ExpressionType node_type, Type type)
{
this.node_type = node_type;
this.type = type;
}
public override string ToString ()
{
return ExpressionPrinter.ToString (this);
}
#region Binary Expressions
static MethodInfo GetUnaryOperator (string oper_name, Type declaring, Type param)
{
return GetUnaryOperator (oper_name, declaring, param, null);
}
static MethodInfo GetUnaryOperator (string oper_name, Type declaring, Type param, Type ret)
{
var methods = declaring.GetNotNullableType ().GetMethods (PublicStatic);
foreach (var method in methods) {
if (method.Name != oper_name)
continue;
var parameters = method.GetParameters ();
if (parameters.Length != 1)
continue;
if (method.IsGenericMethod)
continue;
if (!IsAssignableToParameterType (param.GetNotNullableType (), parameters [0]))
continue;
if (ret != null && method.ReturnType != ret.GetNotNullableType ())
continue;
return method;
}
return null;
}
internal static MethodInfo GetTrueOperator (Type self)
{
return GetBooleanOperator ("op_True", self);
}
internal static MethodInfo GetFalseOperator (Type self)
{
return GetBooleanOperator ("op_False", self);
}
static MethodInfo GetBooleanOperator (string op, Type self)
{
return GetUnaryOperator (op, self, self, typeof (bool));
}
static bool IsAssignableToParameterType (Type type, ParameterInfo param)
{
var ptype = param.ParameterType;
if (ptype.IsByRef)
ptype = ptype.GetElementType ();
return type.GetNotNullableType ().IsAssignableTo (ptype);
}
static MethodInfo CheckUnaryMethod (MethodInfo method, Type param)
{
if (method.ReturnType == typeof (void))
throw new ArgumentException ("Specified method must return a value", "method");
if (!method.IsStatic)
throw new ArgumentException ("Method must be static", "method");
var parameters = method.GetParameters ();
if (parameters.Length != 1)
throw new ArgumentException ("Must have only one parameters", "method");
if (!IsAssignableToParameterType (param.GetNotNullableType (), parameters [0]))
throw new InvalidOperationException ("left-side argument type does not match expression type");
return method;
}
static MethodInfo UnaryCoreCheck (string oper_name, Expression expression, MethodInfo method, Func<Type, bool> validator)
{
if (expression == null)
throw new ArgumentNullException ("expression");
if (method != null)
return CheckUnaryMethod (method, expression.Type);
var type = expression.Type.GetNotNullableType ();
if (validator (type))
return null;
if (oper_name != null) {
method = GetUnaryOperator (oper_name, type, expression.Type);
if (method != null)
return method;
}
throw new InvalidOperationException (
string.Format ("Operation {0} not defined for {1}", oper_name != null ? oper_name.Substring (3) : "is", expression.Type));
}
static MethodInfo GetBinaryOperator (string oper_name, Type on_type, Expression left, Expression right)
{
MethodInfo [] methods = on_type.GetMethods (PublicStatic);
foreach (var method in methods) {
if (method.Name != oper_name)
continue;
var parameters = method.GetParameters ();
if (parameters.Length != 2)
continue;
if (method.IsGenericMethod)
continue;
if (!IsAssignableToParameterType (left.Type, parameters [0]))
continue;
if (!IsAssignableToParameterType (right.Type, parameters [1]))
continue;
// Method has papers in order.
return method;
}
return null;
}
//
// Performs basic checks on the incoming expressions for binary expressions
// and any provided MethodInfo.
//
static MethodInfo BinaryCoreCheck (string oper_name, Expression left, Expression right, MethodInfo method)
{
if (left == null)
throw new ArgumentNullException ("left");
if (right == null)
throw new ArgumentNullException ("right");
if (method != null){
if (method.ReturnType == typeof (void))
throw new ArgumentException ("Specified method must return a value", "method");
if (!method.IsStatic)
throw new ArgumentException ("Method must be static", "method");
var parameters = method.GetParameters ();
if (parameters.Length != 2)
throw new ArgumentException ("Must have only two parameters", "method");
if (!IsAssignableToParameterType (left.Type, parameters [0]))
throw new InvalidOperationException ("left-side argument type does not match left expression type");
if (!IsAssignableToParameterType (right.Type, parameters [1]))
throw new InvalidOperationException ("right-side argument type does not match right expression type");
return method;
} else {
Type ltype = left.Type;
Type rtype = right.Type;
Type ultype = ltype.GetNotNullableType ();
Type urtype = rtype.GetNotNullableType ();
if (oper_name == "op_BitwiseOr" || oper_name == "op_BitwiseAnd") {
if (ultype == typeof (bool)) {
if (ultype == urtype && ltype == rtype)
return null;
}
}
// Use IsNumber to avoid expensive reflection.
if (IsNumber (ultype)) {
if (ultype == urtype && ltype == rtype)
return null;
if (oper_name != null){
method = GetBinaryOperator (oper_name, urtype, left, right);
if (method != null)
return method;
}
}
if (oper_name != null){
method = GetBinaryOperator (oper_name, ultype, left, right);
if (method != null)
return method;
}
if (oper_name == "op_Equality" || oper_name == "op_Inequality") {
//
// == and != allow reference types without operators defined.
//
if (!ltype.IsValueType && !rtype.IsValueType)
return null;
if (ltype == rtype && ultype.IsEnum)
return null;
if (ltype == rtype && ultype == typeof (bool))
return null;
}
if (oper_name == "op_LeftShift" || oper_name == "op_RightShift") {
if (IsInt (ultype) && urtype == typeof (int))
return null;
}
throw new InvalidOperationException (
String.Format ("Operation {0} not defined for {1} and {2}", oper_name != null ? oper_name.Substring (3) : "is", ltype, rtype));
}
}
//
// This is like BinaryCoreCheck, but if no method is used adds the restriction that
// only ints and bools are allowed
//
static MethodInfo BinaryBitwiseCoreCheck (string oper_name, Expression left, Expression right, MethodInfo method)
{
if (left == null)
throw new ArgumentNullException ("left");
if (right == null)
throw new ArgumentNullException ("right");
if (method == null) {
// avoid reflection shortcut and catches Ints/bools before we check Numbers in general
if (left.Type == right.Type && IsIntOrBool (left.Type))
return null;
}
method = BinaryCoreCheck (oper_name, left, right, method);
if (method == null) {
// The check in BinaryCoreCheck allows a bit more than we do
// (floats and doubles). Catch this here
if (left.Type == typeof (double) || left.Type == typeof (float))
throw new InvalidOperationException ("Types not supported");
}
return method;
}
static BinaryExpression MakeSimpleBinary (ExpressionType et, Expression left, Expression right, MethodInfo method)
{
bool is_lifted;
Type type;
if (method == null) {
is_lifted = left.Type.IsNullable ();
type = left.Type;
} else {
var parameters = method.GetParameters ();
var lp = parameters [0];
var rp = parameters [1];
if (IsAssignableToOperatorParameter (left, lp) && IsAssignableToOperatorParameter (right, rp)) {
is_lifted = false;
type = method.ReturnType;
} else if (left.Type.IsNullable ()
&& right.Type.IsNullable ()
&& left.Type.GetNotNullableType () == lp.ParameterType
&& right.Type.GetNotNullableType () == rp.ParameterType
&& !method.ReturnType.IsNullable ()) {
is_lifted = true;
type = method.ReturnType.MakeNullableType ();
} else
throw new InvalidOperationException ();
}
return new BinaryExpression (et, type, left, right, is_lifted, is_lifted, method, null);
}
static bool IsAssignableToOperatorParameter (Expression expression, ParameterInfo parameter)
{
if (expression.Type == parameter.ParameterType)
return true;
if ((!expression.Type.IsNullable () && !parameter.ParameterType.IsNullable ())
&& IsAssignableToParameterType (expression.Type, parameter))
return true;
return false;
}
static UnaryExpression MakeSimpleUnary (ExpressionType et, Expression expression, MethodInfo method)
{
bool is_lifted;
Type type;
if (method == null) {
type = expression.Type;
is_lifted = type.IsNullable ();
} else {
var parameter = method.GetParameters () [0];
if (IsAssignableToOperatorParameter (expression, parameter)) {
is_lifted = false;
type = method.ReturnType;
} else if (expression.Type.IsNullable ()
&& expression.Type.GetNotNullableType () == parameter.ParameterType
&& !method.ReturnType.IsNullable ()) {
is_lifted = true;
type = method.ReturnType.MakeNullableType ();
} else
throw new InvalidOperationException ();
}
return new UnaryExpression (et, expression, type, method, is_lifted);
}
static BinaryExpression MakeBoolBinary (ExpressionType et, Expression left, Expression right, bool liftToNull, MethodInfo method)
{
bool is_lifted;
Type type;
if (method == null) {
if (!left.Type.IsNullable () && !right.Type.IsNullable ()) {
is_lifted = false;
liftToNull = false;
type = typeof (bool);
} else if (left.Type.IsNullable () && right.Type.IsNullable ()) {
is_lifted = true;
type = liftToNull ? typeof (bool?) : typeof (bool);
} else
throw new InvalidOperationException ();
} else {
var parameters = method.GetParameters ();
var lp = parameters [0];
var rp = parameters [1];
if (IsAssignableToOperatorParameter (left, lp) && IsAssignableToOperatorParameter (right, rp)) {
is_lifted = false;
liftToNull = false;
type = method.ReturnType;
} else if (left.Type.IsNullable ()
&& right.Type.IsNullable ()
&& left.Type.GetNotNullableType () == lp.ParameterType
&& right.Type.GetNotNullableType () == rp.ParameterType) {
is_lifted = true;
if (method.ReturnType == typeof (bool))
type = liftToNull ? typeof (bool?) : typeof (bool);
else if (!method.ReturnType.IsNullable ()) {
//
// This behavior is not documented: what
// happens if the result is not typeof(bool), but
// the parameters are nullable: the result
// becomes nullable<returntype>
//
// See:
// https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=323139
type = method.ReturnType.MakeNullableType ();
} else
throw new InvalidOperationException ();
} else
throw new InvalidOperationException ();
}
return new BinaryExpression (et, type, left, right, liftToNull, is_lifted, method, null);
}
//
// Arithmetic
//
public static BinaryExpression Add (Expression left, Expression right)
{
return Add (left, right, null);
}
public static BinaryExpression Add (Expression left, Expression right, MethodInfo method)
{
method = BinaryCoreCheck ("op_Addition", left, right, method);
return MakeSimpleBinary (ExpressionType.Add, left, right, method);
}
public static BinaryExpression AddChecked (Expression left, Expression right)
{
return AddChecked (left, right, null);
}
public static BinaryExpression AddChecked (Expression left, Expression right, MethodInfo method)
{
method = BinaryCoreCheck ("op_Addition", left, right, method);
// The check in BinaryCoreCheck allows a bit more than we do
// (byte, sbyte). Catch that here
if (method == null) {
if (left.Type == typeof (byte) || left.Type == typeof (sbyte))
throw new InvalidOperationException (String.Format ("AddChecked not defined for {0} and {1}", left.Type, right.Type));
}
return MakeSimpleBinary (ExpressionType.AddChecked, left, right, method);
}
public static BinaryExpression Subtract (Expression left, Expression right)
{
return Subtract (left, right, null);
}
public static BinaryExpression Subtract (Expression left, Expression right, MethodInfo method)
{
method = BinaryCoreCheck ("op_Subtraction", left, right, method);
return MakeSimpleBinary (ExpressionType.Subtract, left, right, method);
}
public static BinaryExpression SubtractChecked (Expression left, Expression right)
{
return SubtractChecked (left, right, null);
}
public static BinaryExpression SubtractChecked (Expression left, Expression right, MethodInfo method)
{
method = BinaryCoreCheck ("op_Subtraction", left, right, method);
// The check in BinaryCoreCheck allows a bit more than we do
// (byte, sbyte). Catch that here
if (method == null) {
if (left.Type == typeof (byte) || left.Type == typeof (sbyte))
throw new InvalidOperationException (String.Format ("SubtractChecked not defined for {0} and {1}", left.Type, right.Type));
}
return MakeSimpleBinary (ExpressionType.SubtractChecked, left, right, method);
}
public static BinaryExpression Modulo (Expression left, Expression right)
{
return Modulo (left, right, null);
}
public static BinaryExpression Modulo (Expression left, Expression right, MethodInfo method)
{
method = BinaryCoreCheck ("op_Modulus", left, right, method);
return MakeSimpleBinary (ExpressionType.Modulo, left, right, method);
}
public static BinaryExpression Multiply (Expression left, Expression right)
{
return Multiply (left, right, null);
}
public static BinaryExpression Multiply (Expression left, Expression right, MethodInfo method)
{
method = BinaryCoreCheck ("op_Multiply", left, right, method);
return MakeSimpleBinary (ExpressionType.Multiply, left, right, method);
}
public static BinaryExpression MultiplyChecked (Expression left, Expression right)
{
return MultiplyChecked (left, right, null);
}
public static BinaryExpression MultiplyChecked (Expression left, Expression right, MethodInfo method)
{
method = BinaryCoreCheck ("op_Multiply", left, right, method);
return MakeSimpleBinary (ExpressionType.MultiplyChecked, left, right, method);
}
public static BinaryExpression Divide (Expression left, Expression right)
{
return Divide (left, right, null);
}
public static BinaryExpression Divide (Expression left, Expression right, MethodInfo method)
{
method = BinaryCoreCheck ("op_Division", left, right, method);
return MakeSimpleBinary (ExpressionType.Divide, left, right, method);
}
public static BinaryExpression Power (Expression left, Expression right)
{
return Power (left, right, null);
}
public static BinaryExpression Power (Expression left, Expression right, MethodInfo method)
{
method = BinaryCoreCheck (null, left, right, method);
if (left.Type.GetNotNullableType () != typeof (double))
throw new InvalidOperationException ("Power only supports double arguments");
return MakeSimpleBinary (ExpressionType.Power, left, right, method);
}
//
// Bitwise
//
public static BinaryExpression And (Expression left, Expression right)
{
return And (left, right, null);
}
public static BinaryExpression And (Expression left, Expression right, MethodInfo method)
{
method = BinaryBitwiseCoreCheck ("op_BitwiseAnd", left, right, method);
return MakeSimpleBinary (ExpressionType.And, left, right, method);
}
public static BinaryExpression Or (Expression left, Expression right)
{
return Or (left, right, null);
}
public static BinaryExpression Or (Expression left, Expression right, MethodInfo method)
{
method = BinaryBitwiseCoreCheck ("op_BitwiseOr", left, right, method);
return MakeSimpleBinary (ExpressionType.Or, left, right, method);
}
public static BinaryExpression ExclusiveOr (Expression left, Expression right)
{
return ExclusiveOr (left, right, null);
}
public static BinaryExpression ExclusiveOr (Expression left, Expression right, MethodInfo method)
{
method = BinaryBitwiseCoreCheck ("op_ExclusiveOr", left, right, method);
return MakeSimpleBinary (ExpressionType.ExclusiveOr, left, right, method);
}
public static BinaryExpression LeftShift (Expression left, Expression right)
{
return LeftShift (left, right, null);
}
public static BinaryExpression LeftShift (Expression left, Expression right, MethodInfo method)
{
method = BinaryBitwiseCoreCheck ("op_LeftShift", left, right, method);
return MakeSimpleBinary (ExpressionType.LeftShift, left, right, method);
}
public static BinaryExpression RightShift (Expression left, Expression right)
{
return RightShift (left, right, null);
}
public static BinaryExpression RightShift (Expression left, Expression right, MethodInfo method)
{
method = BinaryCoreCheck ("op_RightShift", left, right, method);
return MakeSimpleBinary (ExpressionType.RightShift, left, right, method);
}
//
// Short-circuit
//
public static BinaryExpression AndAlso (Expression left, Expression right)
{
return AndAlso (left, right, null);
}
public static BinaryExpression AndAlso (Expression left, Expression right, MethodInfo method)
{
method = ConditionalBinaryCheck ("op_BitwiseAnd", left, right, method);
return MakeBoolBinary (ExpressionType.AndAlso, left, right, true, method);
}
static MethodInfo ConditionalBinaryCheck (string oper, Expression left, Expression right, MethodInfo method)
{
method = BinaryCoreCheck (oper, left, right, method);
if (method == null) {
if (left.Type.GetNotNullableType () != typeof (bool))
throw new InvalidOperationException ("Only booleans are allowed");
} else {
var type = left.Type.GetNotNullableType ();
// The method should have identical parameter and return types.
if (left.Type != right.Type || method.ReturnType != type)
throw new ArgumentException ("left, right and return type must match");
var optrue = GetTrueOperator (type);
var opfalse = GetFalseOperator (type);
if (optrue == null || opfalse == null)
throw new ArgumentException ("Operators true and false are required but not defined");
}
return method;
}
public static BinaryExpression OrElse (Expression left, Expression right)
{
return OrElse (left, right, null);
}
public static BinaryExpression OrElse (Expression left, Expression right, MethodInfo method)
{
method = ConditionalBinaryCheck ("op_BitwiseOr", left, right, method);
return MakeBoolBinary (ExpressionType.OrElse, left, right, true, method);
}
//
// Comparison
//
public static BinaryExpression Equal (Expression left, Expression right)
{
return Equal (left, right, false, null);
}
public static BinaryExpression Equal (Expression left, Expression right, bool liftToNull, MethodInfo method)
{
method = BinaryCoreCheck ("op_Equality", left, right, method);
return MakeBoolBinary (ExpressionType.Equal, left, right, liftToNull, method);
}
public static BinaryExpression NotEqual (Expression left, Expression right)
{
return NotEqual (left, right, false, null);
}
public static BinaryExpression NotEqual (Expression left, Expression right, bool liftToNull, MethodInfo method)
{
method = BinaryCoreCheck ("op_Inequality", left, right, method);
return MakeBoolBinary (ExpressionType.NotEqual, left, right, liftToNull, method);
}
public static BinaryExpression GreaterThan (Expression left, Expression right)
{
return GreaterThan (left, right, false, null);
}
public static BinaryExpression GreaterThan (Expression left, Expression right, bool liftToNull, MethodInfo method)
{
method = BinaryCoreCheck ("op_GreaterThan", left, right, method);
return MakeBoolBinary (ExpressionType.GreaterThan, left, right, liftToNull, method);
}
public static BinaryExpression GreaterThanOrEqual (Expression left, Expression right)
{
return GreaterThanOrEqual (left, right, false, null);
}
public static BinaryExpression GreaterThanOrEqual (Expression left, Expression right, bool liftToNull, MethodInfo method)
{
method = BinaryCoreCheck ("op_GreaterThanOrEqual", left, right, method);
return MakeBoolBinary (ExpressionType.GreaterThanOrEqual, left, right, liftToNull, method);
}
public static BinaryExpression LessThan (Expression left, Expression right)
{
return LessThan (left, right, false, null);
}
public static BinaryExpression LessThan (Expression left, Expression right, bool liftToNull, MethodInfo method)
{
method = BinaryCoreCheck ("op_LessThan", left, right, method);
return MakeBoolBinary (ExpressionType.LessThan, left, right, liftToNull, method);
}
public static BinaryExpression LessThanOrEqual (Expression left, Expression right)
{
return LessThanOrEqual (left, right, false, null);
}
public static BinaryExpression LessThanOrEqual (Expression left, Expression right, bool liftToNull, MethodInfo method)
{
method = BinaryCoreCheck ("op_LessThanOrEqual", left, right, method);
return MakeBoolBinary (ExpressionType.LessThanOrEqual, left, right, liftToNull, method);
}
//
// Miscelaneous
//
static void CheckArray (Expression array)
{
if (array == null)
throw new ArgumentNullException ("array");
if (!array.Type.IsArray)
throw new ArgumentException ("The array argument must be of type array");
}
public static BinaryExpression ArrayIndex (Expression array, Expression index)
{
CheckArray (array);
if (index == null)
throw new ArgumentNullException ("index");
if (array.Type.GetArrayRank () != 1)
throw new ArgumentException ("The array argument must be a single dimensional array");
if (index.Type != typeof (int))
throw new ArgumentException ("The index must be of type int");
return new BinaryExpression (ExpressionType.ArrayIndex, array.Type.GetElementType (), array, index);
}
public static BinaryExpression Coalesce (Expression left, Expression right)
{
return Coalesce (left, right, null);
}
static BinaryExpression MakeCoalesce (Expression left, Expression right)
{
Type result = null;
if (left.Type.IsNullable ()) {
Type lbase = left.Type.GetNotNullableType ();
if (!right.Type.IsNullable () && right.Type.IsAssignableTo (lbase))
result = lbase;
}
if (result == null && right.Type.IsAssignableTo (left.Type))
result = left.Type;
if (result == null) {
if (left.Type.IsNullable () && left.Type.GetNotNullableType ().IsAssignableTo (right.Type))
result = right.Type;
}
if (result == null)
throw new ArgumentException ("Incompatible argument types");
return new BinaryExpression (ExpressionType.Coalesce, result, left, right, false, false, null, null);
}
static BinaryExpression MakeConvertedCoalesce (Expression left, Expression right, LambdaExpression conversion)
{
var invoke = conversion.Type.GetInvokeMethod ();
CheckNotVoid (invoke.ReturnType);
if (invoke.ReturnType != right.Type)
throw new InvalidOperationException ("Conversion return type doesn't march right type");
var parameters = invoke.GetParameters ();
if (parameters.Length != 1)
throw new ArgumentException ("Conversion has wrong number of parameters");
if (!IsAssignableToParameterType (left.Type, parameters [0]))
throw new InvalidOperationException ("Conversion argument doesn't marcht left type");
return new BinaryExpression (ExpressionType.Coalesce, right.Type, left, right, false, false, null, conversion);
}
public static BinaryExpression Coalesce (Expression left, Expression right, LambdaExpression conversion)
{
if (left == null)
throw new ArgumentNullException ("left");
if (right == null)
throw new ArgumentNullException ("right");
//
// First arg must ne nullable (either Nullable<T> or a reference type
//
if (left.Type.IsValueType && !left.Type.IsNullable ())
throw new InvalidOperationException ("Left expression can never be null");
if (conversion != null)
return MakeConvertedCoalesce (left, right, conversion);
return MakeCoalesce (left, right);
}
//
// MakeBinary constructors
//
public static BinaryExpression MakeBinary (ExpressionType binaryType, Expression left, Expression right)
{
return MakeBinary (binaryType, left, right, false, null);
}
public static BinaryExpression MakeBinary (ExpressionType binaryType, Expression left, Expression right, bool liftToNull, MethodInfo method)
{
return MakeBinary (binaryType, left, right, liftToNull, method, null);
}
public static BinaryExpression MakeBinary (ExpressionType binaryType, Expression left, Expression right, bool liftToNull, MethodInfo method, LambdaExpression conversion)
{
switch (binaryType) {
case ExpressionType.Add:
return Add (left, right, method);
case ExpressionType.AddChecked:
return AddChecked (left, right, method);
case ExpressionType.AndAlso:
return AndAlso (left, right);
case ExpressionType.Coalesce:
return Coalesce (left, right, conversion);
case ExpressionType.Divide:
return Divide (left, right, method);
case ExpressionType.Equal:
return Equal (left, right, liftToNull, method);
case ExpressionType.ExclusiveOr:
return ExclusiveOr (left, right, method);
case ExpressionType.GreaterThan:
return GreaterThan (left, right, liftToNull, method);
case ExpressionType.GreaterThanOrEqual:
return GreaterThanOrEqual (left, right, liftToNull, method);
case ExpressionType.LeftShift:
return LeftShift (left, right, method);
case ExpressionType.LessThan:
return LessThan (left, right, liftToNull, method);
case ExpressionType.LessThanOrEqual:
return LessThanOrEqual (left, right, liftToNull, method);
case ExpressionType.Modulo:
return Modulo (left, right, method);
case ExpressionType.Multiply:
return Multiply (left, right, method);
case ExpressionType.MultiplyChecked:
return MultiplyChecked (left, right, method);
case ExpressionType.NotEqual:
return NotEqual (left, right, liftToNull, method);
case ExpressionType.OrElse:
return OrElse (left, right);
case ExpressionType.Power:
return Power (left, right, method);
case ExpressionType.RightShift:
return RightShift (left, right, method);
case ExpressionType.Subtract:
return Subtract (left, right, method);
case ExpressionType.SubtractChecked:
return SubtractChecked (left, right, method);
case ExpressionType.And:
return And (left, right, method);
case ExpressionType.Or:
return Or (left, right, method);
}
throw new ArgumentException ("MakeBinary expect a binary node type");
}
#endregion
public static MethodCallExpression ArrayIndex (Expression array, params Expression [] indexes)
{
return ArrayIndex (array, indexes as IEnumerable<Expression>);
}
public static MethodCallExpression ArrayIndex (Expression array, IEnumerable<Expression> indexes)
{
CheckArray (array);
if (indexes == null)
throw new ArgumentNullException ("indexes");
var args = indexes.ToReadOnlyCollection ();
if (array.Type.GetArrayRank () != args.Count)
throw new ArgumentException ("The number of arguments doesn't match the rank of the array");
foreach (var arg in args)
if (arg.Type != typeof (int))
throw new ArgumentException ("The index must be of type int");
return Call (array, array.Type.GetMethod ("Get", PublicInstance), args);
}
public static UnaryExpression ArrayLength (Expression array)
{
if (array == null)
throw new ArgumentNullException ("array");
if (!array.Type.IsArray)
throw new ArgumentException ("The type of the expression must me Array");
if (array.Type.GetArrayRank () != 1)
throw new ArgumentException ("The array must be a single dimensional array");
return new UnaryExpression (ExpressionType.ArrayLength, array, typeof (int));
}
public static MemberAssignment Bind (MemberInfo member, Expression expression)
{
if (member == null)
throw new ArgumentNullException ("member");
if (expression == null)
throw new ArgumentNullException ("expression");
Type type = null;
var prop = member as PropertyInfo;
if (prop != null && prop.GetSetMethod (true) != null)
type = prop.PropertyType;
var field = member as FieldInfo;
if (field != null)
type = field.FieldType;
if (type == null)
throw new ArgumentException ("member");
if (!expression.Type.IsAssignableTo (type))
throw new ArgumentException ("member");
return new MemberAssignment (member, expression);
}
public static MemberAssignment Bind (MethodInfo propertyAccessor, Expression expression)
{
if (propertyAccessor == null)
throw new ArgumentNullException ("propertyAccessor");
if (expression == null)
throw new ArgumentNullException ("expression");
CheckNonGenericMethod (propertyAccessor);
var prop = GetAssociatedProperty (propertyAccessor);
if (prop == null)
throw new ArgumentException ("propertyAccessor");
var setter = prop.GetSetMethod (true);
if (setter == null)
throw new ArgumentException ("setter");
if (!expression.Type.IsAssignableTo (prop.PropertyType))
throw new ArgumentException ("member");
return new MemberAssignment (prop, expression);
}
public static MethodCallExpression Call (Expression instance, MethodInfo method)
{
return Call (instance, method, null as IEnumerable<Expression>);
}
public static MethodCallExpression Call (MethodInfo method, params Expression [] arguments)
{
return Call (null, method, arguments as IEnumerable<Expression>);
}
public static MethodCallExpression Call (Expression instance, MethodInfo method, params Expression [] arguments)
{
return Call (instance, method, arguments as IEnumerable<Expression>);
}
public static MethodCallExpression Call (Expression instance, MethodInfo method, IEnumerable<Expression> arguments)
{
if (method == null)
throw new ArgumentNullException ("method");
if (instance == null && !method.IsStatic)
throw new ArgumentNullException ("instance");
if (method.IsStatic && instance != null)
throw new ArgumentException ("instance");
if (!method.IsStatic && !instance.Type.IsAssignableTo (method.DeclaringType))
throw new ArgumentException ("Type is not assignable to the declaring type of the method");
var args = CheckMethodArguments (method, arguments);
return new MethodCallExpression (instance, method, args);
}
static Type [] CollectTypes (IEnumerable<Expression> expressions)
{
return (from arg in expressions select arg.Type).ToArray ();
}
static MethodInfo TryMakeGeneric (MethodInfo method, Type [] args)
{
if (method == null)
return null;
if (!method.IsGenericMethod && (args == null || args.Length == 0))
return method;
if (args.Length == method.GetGenericArguments ().Length)
return method.MakeGenericMethod (args);
return null;
}
public static MethodCallExpression Call (Expression instance, string methodName, Type [] typeArguments, params Expression [] arguments)
{
if (instance == null)
throw new ArgumentNullException ("instance");
if (methodName == null)
throw new ArgumentNullException ("methodName");
var method = TryGetMethod (instance.Type, methodName, AllInstance,
CollectTypes (arguments), typeArguments);
var args = CheckMethodArguments (method, arguments);
return new MethodCallExpression (instance, method, args);
}
static bool MethodMatch (MethodInfo method, string name, Type [] parameterTypes, Type [] argumentTypes)
{
if (method.Name != name)
return false;
var parameters = method.GetParameters ();
if (parameters.Length != parameterTypes.Length)
return false;
if (method.IsGenericMethod && method.IsGenericMethodDefinition) {
var closed = TryMakeGeneric (method, argumentTypes);
if (closed == null)
return false;
return MethodMatch (closed, name, parameterTypes, argumentTypes);
} else if (!method.IsGenericMethod && (argumentTypes != null && argumentTypes.Length > 0))
return false;
for (int i = 0; i < parameters.Length; i++) {
var type = parameterTypes [i];
var parameter = parameters [i];
if (!IsAssignableToParameterType (type, parameter)
&& !IsExpressionOfParameter (type, parameter.ParameterType))
return false;
}
return true;
}
static bool IsExpressionOfParameter (Type type, Type ptype)
{
return ptype.IsGenericInstanceOf (typeof (Expression<>)) && ptype.GetFirstGenericArgument () == type;
}
static MethodInfo TryGetMethod (Type type, string methodName, BindingFlags flags, Type [] parameterTypes, Type [] argumentTypes)
{
var methods = from meth in type.GetMethods (flags)
where MethodMatch (meth, methodName, parameterTypes, argumentTypes)
select meth;
if (methods.Count () > 1)
throw new InvalidOperationException ("Too many method candidates");
var method = TryMakeGeneric (methods.FirstOrDefault (), argumentTypes);
if (method != null)
return method;
throw new InvalidOperationException ("No such method");
}
public static MethodCallExpression Call (Type type, string methodName, Type [] typeArguments, params Expression [] arguments)
{
if (type == null)
throw new ArgumentNullException ("type");
if (methodName == null)
throw new ArgumentNullException ("methodName");
var method = TryGetMethod (type, methodName, AllStatic,
CollectTypes (arguments), typeArguments);
var args = CheckMethodArguments (method, arguments);
return new MethodCallExpression (method, args);
}
public static ConditionalExpression Condition (Expression test, Expression ifTrue, Expression ifFalse)
{
if (test == null)
throw new ArgumentNullException ("test");
if (ifTrue == null)
throw new ArgumentNullException ("ifTrue");
if (ifFalse == null)
throw new ArgumentNullException ("ifFalse");
if (test.Type != typeof (bool))
throw new ArgumentException ("Test expression should be of type bool");
if (ifTrue.Type != ifFalse.Type)
throw new ArgumentException ("The ifTrue and ifFalse type do not match");
return new ConditionalExpression (test, ifTrue, ifFalse);
}
public static ConstantExpression Constant (object value)
{
if (value == null)
return new ConstantExpression (null, typeof (object));
return Constant (value, value.GetType ());
}
public static ConstantExpression Constant (object value, Type type)
{
if (type == null)
throw new ArgumentNullException ("type");
//
// value must be compatible with type, no conversions
// are allowed
//
if (value == null){
if (type.IsValueType && !type.IsNullable ())
throw new ArgumentException ();
} else {
if (!(type.IsValueType && type.IsNullable ()) && !value.GetType ().IsAssignableTo (type))
throw new ArgumentException ();
}
return new ConstantExpression (value, type);
}
static bool IsConvertiblePrimitive (Type type)
{
var t = type.GetNotNullableType ();
if (t == typeof (bool))
return false;
if (t.IsEnum)
return true;
return t.IsPrimitive;
}
internal static bool IsPrimitiveConversion (Type type, Type target)
{
if (type == target)
return true;
if (type.IsNullable () && target == type.GetNotNullableType ())
return true;
if (target.IsNullable () && type == target.GetNotNullableType ())
return true;
if (IsConvertiblePrimitive (type) && IsConvertiblePrimitive (target))
return true;
return false;
}
internal static bool IsReferenceConversion (Type type, Type target)
{
if (type == target)
return true;
if (type == typeof (object) || target == typeof (object))
return true;
if (type.IsInterface || target.IsInterface)
return true;
if (type.IsValueType || target.IsValueType)
return false;
if (type.IsAssignableTo (target) || target.IsAssignableTo (type))
return true;
return false;
}
public static UnaryExpression Convert (Expression expression, Type type)
{
return Convert (expression, type, null);
}
static MethodInfo GetUserConversionMethod (Type type, Type target)
{
var method = GetUnaryOperator ("op_Explicit", type, type, target);
if (method == null)
method = GetUnaryOperator ("op_Implicit", type, type, target);
if (method == null)
method = GetUnaryOperator ("op_Explicit", target, type, target);
if (method == null)
method = GetUnaryOperator ("op_Implicit", target, type, target);
if (method == null)
throw new InvalidOperationException ();
return method;
}
public static UnaryExpression Convert (Expression expression, Type type, MethodInfo method)
{
if (expression == null)
throw new ArgumentNullException ("expression");
if (type == null)
throw new ArgumentNullException ("type");
var et = expression.Type;
if (method != null)
CheckUnaryMethod (method, et);
else if (!IsPrimitiveConversion (et, type) && !IsReferenceConversion (et, type))
method = GetUserConversionMethod (et, type);
return new UnaryExpression (ExpressionType.Convert,
expression, type, method,
IsConvertNodeLifted (method, expression, type));
}
static bool IsConvertNodeLifted (MethodInfo method, Expression operand, Type target)
{
if (method == null)
return operand.Type.IsNullable () || target.IsNullable ();
if (operand.Type.IsNullable () && !ParameterMatch (method, operand.Type))
return true;
if (target.IsNullable () && !ReturnTypeMatch (method, target))
return true;
return false;
}
static bool ParameterMatch (MethodInfo method, Type type)
{
return method.GetParameters () [0].ParameterType == type;
}
static bool ReturnTypeMatch (MethodInfo method, Type type)
{
return method.ReturnType == type;
}
public static UnaryExpression ConvertChecked (Expression expression, Type type)
{
return ConvertChecked (expression, type, null);
}
public static UnaryExpression ConvertChecked (Expression expression, Type type, MethodInfo method)
{
if (expression == null)
throw new ArgumentNullException ("expression");
if (type == null)
throw new ArgumentNullException ("type");
var et = expression.Type;
if (method != null)
CheckUnaryMethod (method, et);
else if (IsReferenceConversion (et, type))
return Convert (expression, type, method);
else if (!IsPrimitiveConversion (et, type))
method = GetUserConversionMethod (et, type);
return new UnaryExpression (ExpressionType.ConvertChecked,
expression, type, method,
IsConvertNodeLifted (method, expression, type));
}
public static ElementInit ElementInit (MethodInfo addMethod, params Expression [] arguments)
{
return ElementInit (addMethod, arguments as IEnumerable<Expression>);
}
public static ElementInit ElementInit (MethodInfo addMethod, IEnumerable<Expression> arguments)
{
if (addMethod == null)
throw new ArgumentNullException ("addMethod");
if (arguments == null)
throw new ArgumentNullException ("arguments");
if (addMethod.Name.ToLower (CultureInfo.InvariantCulture) != "add")
throw new ArgumentException ("addMethod");
if (addMethod.IsStatic)
throw new ArgumentException ("addMethod must be an instance method", "addMethod");
var args = CheckMethodArguments (addMethod, arguments);
return new ElementInit (addMethod, args);
}
public static MemberExpression Field (Expression expression, FieldInfo field)
{
if (field == null)
throw new ArgumentNullException ("field");
if (!field.IsStatic) {
if (expression == null)
throw new ArgumentNullException ("expression");
if (!expression.Type.IsAssignableTo (field.DeclaringType))
throw new ArgumentException ("field");
} else if (expression != null)
throw new ArgumentException ("expression");
return new MemberExpression (expression, field, field.FieldType);
}
public static MemberExpression Field (Expression expression, string fieldName)
{
if (expression == null)
throw new ArgumentNullException ("expression");
var field = expression.Type.GetField (fieldName, AllInstance);
if (field == null)
throw new ArgumentException (string.Format ("No field named {0} on {1}", fieldName, expression.Type));
return new MemberExpression (expression, field, field.FieldType);
}
public static Type GetActionType (params Type [] typeArgs)
{
if (typeArgs == null)
throw new ArgumentNullException ("typeArgs");
if (typeArgs.Length > 4)
throw new ArgumentException ("No Action type of this arity");
if (typeArgs.Length == 0)
return typeof (Action);
Type action = null;
switch (typeArgs.Length) {
case 1:
action = typeof (Action<>);
break;
case 2:
action = typeof (Action<,>);
break;
case 3:
action = typeof (Action<,,>);
break;
case 4:
action = typeof (Action<,,,>);
break;
}
return action.MakeGenericType (typeArgs);
}
public static Type GetFuncType (params Type [] typeArgs)
{
if (typeArgs == null)
throw new ArgumentNullException ("typeArgs");
if (typeArgs.Length < 1 || typeArgs.Length > 5)
throw new ArgumentException ("No Func type of this arity");
Type func = null;
switch (typeArgs.Length) {
case 1:
func = typeof (Func<>);
break;
case 2:
func = typeof (Func<,>);
break;
case 3:
func = typeof (Func<,,>);
break;
case 4:
func = typeof (Func<,,,>);
break;
case 5:
func = typeof (Func<,,,,>);
break;
}
return func.MakeGenericType (typeArgs);
}
public static InvocationExpression Invoke (Expression expression, params Expression [] arguments)
{
return Invoke (expression, arguments as IEnumerable<Expression>);
}
static Type GetInvokableType (Type t)
{
if (t.IsAssignableTo (typeof (Delegate)))
return t;
return GetGenericType (t, typeof (Expression<>));
}
static Type GetGenericType (Type t, Type def)
{
if (t == null)
return null;
if (t.IsGenericType && t.GetGenericTypeDefinition () == def)
return t;
return GetGenericType (t.BaseType, def);
}
public static InvocationExpression Invoke (Expression expression, IEnumerable<Expression> arguments)
{
if (expression == null)
throw new ArgumentNullException ("expression");
var type = GetInvokableType (expression.Type);
if (type == null)
throw new ArgumentException ("The type of the expression is not invokable");
var args = arguments.ToReadOnlyCollection ();
CheckForNull (args, "arguments");
var invoke = type.GetInvokeMethod ();
if (invoke == null)
throw new ArgumentException ("expression");
if (invoke.GetParameters ().Length != args.Count)
throw new InvalidOperationException ("Arguments count doesn't match parameters length");
args = CheckMethodArguments (invoke, args);
return new InvocationExpression (expression, invoke.ReturnType, args);
}
static bool CanAssign (Type target, Type source)
{
// This catches object and value type mixage, type compatibility is handled later
if (target.IsValueType ^ source.IsValueType)
return false;
return source.IsAssignableTo (target);
}
static Expression CheckLambda (Type delegateType, Expression body, ReadOnlyCollection<ParameterExpression> parameters)
{
if (!delegateType.IsSubclassOf (typeof (System.Delegate)))
throw new ArgumentException ("delegateType");
var invoke = delegateType.GetInvokeMethod ();
if (invoke == null)
throw new ArgumentException ("delegate must contain an Invoke method", "delegateType");
var invoke_parameters = invoke.GetParameters ();
if (invoke_parameters.Length != parameters.Count)
throw new ArgumentException (string.Format ("Different number of arguments in delegate {0}", delegateType), "delegateType");
for (int i = 0; i < invoke_parameters.Length; i++) {
var parameter = parameters [i];
if (parameter == null)
throw new ArgumentNullException ("parameters");
if (!CanAssign (parameter.Type, invoke_parameters [i].ParameterType))
throw new ArgumentException (String.Format ("Can not assign a {0} to a {1}", invoke_parameters [i].ParameterType, parameter.Type));
}
if (invoke.ReturnType != typeof (void)) {
if (!CanAssign (invoke.ReturnType, body.Type)) {
if (invoke.ReturnType.IsExpression ())
return Expression.Quote (body);
throw new ArgumentException (String.Format ("body type {0} can not be assigned to {1}", body.Type, invoke.ReturnType));
}
}
return body;
}
public static Expression<TDelegate> Lambda<TDelegate> (Expression body, params ParameterExpression [] parameters)
{
return Lambda<TDelegate> (body, parameters as IEnumerable<ParameterExpression>);
}
public static Expression<TDelegate> Lambda<TDelegate> (Expression body, IEnumerable<ParameterExpression> parameters)
{
if (body == null)
throw new ArgumentNullException ("body");
var ps = parameters.ToReadOnlyCollection ();
body = CheckLambda (typeof (TDelegate), body, ps);
return new Expression<TDelegate> (body, ps);
}
public static LambdaExpression Lambda (Expression body, params ParameterExpression [] parameters)
{
if (body == null)
throw new ArgumentNullException ("body");
if (parameters.Length > 4)
throw new ArgumentException ("Too many parameters");
return Lambda (GetDelegateType (body.Type, parameters), body, parameters);
}
static Type GetDelegateType (Type return_type, ParameterExpression [] parameters)
{
if (parameters == null)
parameters = new ParameterExpression [0];
if (return_type == typeof (void))
return GetActionType (parameters.Select (p => p.Type).ToArray ());
var types = new Type [parameters.Length + 1];
for (int i = 0; i < types.Length - 1; i++)
types [i] = parameters [i].Type;
types [types.Length - 1] = return_type;
return GetFuncType (types);
}
public static LambdaExpression Lambda (Type delegateType, Expression body, params ParameterExpression [] parameters)
{
return Lambda (delegateType, body, parameters as IEnumerable<ParameterExpression>);
}
static LambdaExpression CreateExpressionOf (Type type, Expression body, ReadOnlyCollection<ParameterExpression> parameters)
{
return (LambdaExpression) typeof (Expression<>).MakeGenericType (type).GetConstructor (
NonPublicInstance, null, new [] { typeof (Expression), typeof (ReadOnlyCollection<ParameterExpression>) }, null).Invoke (new object [] { body, parameters } );
}
public static LambdaExpression Lambda (Type delegateType, Expression body, IEnumerable<ParameterExpression> parameters)
{
if (delegateType == null)
throw new ArgumentNullException ("delegateType");
if (body == null)
throw new ArgumentNullException ("body");
var ps = parameters.ToReadOnlyCollection ();
body = CheckLambda (delegateType, body, ps);
return CreateExpressionOf (delegateType, body, ps);
}
public static MemberListBinding ListBind (MemberInfo member, params ElementInit [] initializers)
{
return ListBind (member, initializers as IEnumerable<ElementInit>);
}
static void CheckIsAssignableToIEnumerable (Type t)
{
if (!t.IsAssignableTo (typeof (IEnumerable)))
throw new ArgumentException (string.Format ("Type {0} doesn't implemen IEnumerable", t));
}
public static MemberListBinding ListBind (MemberInfo member, IEnumerable<ElementInit> initializers)
{
if (member == null)
throw new ArgumentNullException ("member");
if (initializers == null)
throw new ArgumentNullException ("initializers");
var inits = initializers.ToReadOnlyCollection ();
CheckForNull (inits, "initializers");
member.OnFieldOrProperty (
field => CheckIsAssignableToIEnumerable (field.FieldType),
prop => CheckIsAssignableToIEnumerable (prop.PropertyType));
return new MemberListBinding (member, inits);
}
public static MemberListBinding ListBind (MethodInfo propertyAccessor, params ElementInit [] initializers)
{
return ListBind (propertyAccessor, initializers as IEnumerable<ElementInit>);
}
static void CheckForNull<T> (ReadOnlyCollection<T> collection, string name) where T : class
{
foreach (var t in collection)
if (t == null)
throw new ArgumentNullException (name);
}
public static MemberListBinding ListBind (MethodInfo propertyAccessor, IEnumerable<ElementInit> initializers)
{
if (propertyAccessor == null)
throw new ArgumentNullException ("propertyAccessor");
if (initializers == null)
throw new ArgumentNullException ("initializers");
var inits = initializers.ToReadOnlyCollection ();
CheckForNull (inits, "initializers");
var prop = GetAssociatedProperty (propertyAccessor);
if (prop == null)
throw new ArgumentException ("propertyAccessor");
CheckIsAssignableToIEnumerable (prop.PropertyType);
return new MemberListBinding (prop, inits);
}
public static ListInitExpression ListInit (NewExpression newExpression, params ElementInit [] initializers)
{
return ListInit (newExpression, initializers as IEnumerable<ElementInit>);
}
public static ListInitExpression ListInit (NewExpression newExpression, IEnumerable<ElementInit> initializers)
{
var inits = CheckListInit (newExpression, initializers);
return new ListInitExpression (newExpression, inits);
}
public static ListInitExpression ListInit (NewExpression newExpression, params Expression [] initializers)
{
return ListInit (newExpression, initializers as IEnumerable<Expression>);
}
public static ListInitExpression ListInit (NewExpression newExpression, IEnumerable<Expression> initializers)
{
var inits = CheckListInit (newExpression, initializers);
var add_method = GetAddMethod (newExpression.Type, inits [0].Type);
if (add_method == null)
throw new InvalidOperationException ("No suitable add method found");
return new ListInitExpression (newExpression, CreateInitializers (add_method, inits));
}
static ReadOnlyCollection<ElementInit> CreateInitializers (MethodInfo add_method, ReadOnlyCollection<Expression> initializers)
{
return (from init in initializers select Expression.ElementInit (add_method, init)).ToReadOnlyCollection ();
}
static MethodInfo GetAddMethod (Type type, Type arg)
{
return type.GetMethod ("Add", PublicInstance | BindingFlags.IgnoreCase, null, new [] { arg }, null);
}
public static ListInitExpression ListInit (NewExpression newExpression, MethodInfo addMethod, params Expression [] initializers)
{
return ListInit (newExpression, addMethod, initializers as IEnumerable<Expression>);
}
static ReadOnlyCollection<T> CheckListInit<T> (NewExpression newExpression, IEnumerable<T> initializers) where T : class
{
if (newExpression == null)
throw new ArgumentNullException ("newExpression");
if (initializers == null)
throw new ArgumentNullException ("initializers");
if (!newExpression.Type.IsAssignableTo (typeof (IEnumerable)))
throw new InvalidOperationException ("The type of the new expression does not implement IEnumerable");
var inits = initializers.ToReadOnlyCollection ();
if (inits.Count == 0)
throw new ArgumentException ("Empty initializers");
CheckForNull (inits, "initializers");
return inits;
}
public static ListInitExpression ListInit (NewExpression newExpression, MethodInfo addMethod, IEnumerable<Expression> initializers)
{
var inits = CheckListInit (newExpression, initializers);
if (addMethod != null) {
if (addMethod.Name.ToLower (CultureInfo.InvariantCulture) != "add")
throw new ArgumentException ("addMethod");
var parameters = addMethod.GetParameters ();
if (parameters.Length != 1)
throw new ArgumentException ("addMethod");
foreach (var expression in inits)
if (!IsAssignableToParameterType (expression.Type, parameters [0]))
throw new InvalidOperationException ("Initializer not assignable to the add method parameter type");
}
if (addMethod == null)
addMethod = GetAddMethod (newExpression.Type, inits [0].Type);
if (addMethod == null)
throw new InvalidOperationException ("No suitable add method found");
return new ListInitExpression (newExpression, CreateInitializers (addMethod, inits));
}
public static MemberExpression MakeMemberAccess (Expression expression, MemberInfo member)
{
if (expression == null)
throw new ArgumentNullException ("expression");
if (member == null)
throw new ArgumentNullException ("member");
var field = member as FieldInfo;
if (field != null)
return Field (expression, field);
var property = member as PropertyInfo;
if (property != null)
return Property (expression, property);
throw new ArgumentException ("Member should either be a field or a property");
}
public static UnaryExpression MakeUnary (ExpressionType unaryType, Expression operand, Type type)
{
return MakeUnary (unaryType, operand, type, null);
}
public static UnaryExpression MakeUnary (ExpressionType unaryType, Expression operand, Type type, MethodInfo method)
{
switch (unaryType) {
case ExpressionType.ArrayLength:
return ArrayLength (operand);
case ExpressionType.Convert:
return Convert (operand, type, method);
case ExpressionType.ConvertChecked:
return ConvertChecked (operand, type, method);
case ExpressionType.Negate:
return Negate (operand, method);
case ExpressionType.NegateChecked:
return NegateChecked (operand, method);
case ExpressionType.Not:
return Not (operand, method);
case ExpressionType.Quote:
return Quote (operand);
case ExpressionType.TypeAs:
return TypeAs (operand, type);
case ExpressionType.UnaryPlus:
return UnaryPlus (operand, method);
}
throw new ArgumentException ("MakeUnary expect an unary operator");
}
public static MemberMemberBinding MemberBind (MemberInfo member, params MemberBinding [] bindings)
{
return MemberBind (member, bindings as IEnumerable<MemberBinding>);
}
public static MemberMemberBinding MemberBind (MemberInfo member, IEnumerable<MemberBinding> bindings)
{
if (member == null)
throw new ArgumentNullException ("member");
var type = member.OnFieldOrProperty (
field => field.FieldType,
prop => prop.PropertyType);
return new MemberMemberBinding (member, CheckMemberBindings (type, bindings));
}
public static MemberMemberBinding MemberBind (MethodInfo propertyAccessor, params MemberBinding [] bindings)
{
return MemberBind (propertyAccessor, bindings as IEnumerable<MemberBinding>);
}
public static MemberMemberBinding MemberBind (MethodInfo propertyAccessor, IEnumerable<MemberBinding> bindings)
{
if (propertyAccessor == null)
throw new ArgumentNullException ("propertyAccessor");
var bds = bindings.ToReadOnlyCollection ();
CheckForNull (bds, "bindings");
var prop = GetAssociatedProperty (propertyAccessor);
if (prop == null)
throw new ArgumentException ("propertyAccessor");
return new MemberMemberBinding (prop, CheckMemberBindings (prop.PropertyType, bindings));
}
static ReadOnlyCollection<MemberBinding> CheckMemberBindings (Type type, IEnumerable<MemberBinding> bindings)
{
if (bindings == null)
throw new ArgumentNullException ("bindings");
var bds = bindings.ToReadOnlyCollection ();
CheckForNull (bds, "bindings");
foreach (var binding in bds)
if (!type.IsAssignableTo (binding.Member.DeclaringType))
throw new ArgumentException ("Type not assignable to member type");
return bds;
}
public static MemberInitExpression MemberInit (NewExpression newExpression, params MemberBinding [] bindings)
{
return MemberInit (newExpression, bindings as IEnumerable<MemberBinding>);
}
public static MemberInitExpression MemberInit (NewExpression newExpression, IEnumerable<MemberBinding> bindings)
{
if (newExpression == null)
throw new ArgumentNullException ("newExpression");
return new MemberInitExpression (newExpression, CheckMemberBindings (newExpression.Type, bindings));
}
public static UnaryExpression Negate (Expression expression)
{
return Negate (expression, null);
}
public static UnaryExpression Negate (Expression expression, MethodInfo method)
{
method = UnaryCoreCheck ("op_UnaryNegation", expression, method, type => IsSignedNumber (type));
return MakeSimpleUnary (ExpressionType.Negate, expression, method);
}
public static UnaryExpression NegateChecked (Expression expression)
{
return NegateChecked (expression, null);
}
public static UnaryExpression NegateChecked (Expression expression, MethodInfo method)
{
method = UnaryCoreCheck ("op_UnaryNegation", expression, method, type => IsSignedNumber (type));
return MakeSimpleUnary (ExpressionType.NegateChecked, expression, method);
}
public static NewExpression New (ConstructorInfo constructor)
{
if (constructor == null)
throw new ArgumentNullException ("constructor");
if (constructor.GetParameters ().Length > 0)
throw new ArgumentException ("Constructor must be parameter less");
return new NewExpression (constructor, (null as IEnumerable<Expression>).ToReadOnlyCollection (), null);
}
public static NewExpression New (Type type)
{
if (type == null)
throw new ArgumentNullException ("type");
CheckNotVoid (type);
var args = (null as IEnumerable<Expression>).ToReadOnlyCollection ();
if (type.IsValueType)
return new NewExpression (type, args);
var ctor = type.GetConstructor (Type.EmptyTypes);
if (ctor == null)
throw new ArgumentException ("Type doesn't have a parameter less constructor");
return new NewExpression (ctor, args, null);
}
public static NewExpression New (ConstructorInfo constructor, params Expression [] arguments)
{
return New (constructor, arguments as IEnumerable<Expression>);
}
public static NewExpression New (ConstructorInfo constructor, IEnumerable<Expression> arguments)
{
if (constructor == null)
throw new ArgumentNullException ("constructor");
var args = CheckMethodArguments (constructor, arguments);
return new NewExpression (constructor, args, null);
}
static IList<Expression> CreateArgumentList (IEnumerable<Expression> arguments)
{
if (arguments == null)
return arguments.ToReadOnlyCollection ();
return arguments.ToList ();
}
static void CheckNonGenericMethod (MethodBase method)
{
if (method.IsGenericMethodDefinition || method.ContainsGenericParameters)
throw new ArgumentException ("Can not used open generic methods");
}
static ReadOnlyCollection<Expression> CheckMethodArguments (MethodBase method, IEnumerable<Expression> args)
{
CheckNonGenericMethod (method);
var arguments = CreateArgumentList (args);
var parameters = method.GetParameters ();
if (arguments.Count != parameters.Length)
throw new ArgumentException ("The number of arguments doesn't match the number of parameters");
for (int i = 0; i < parameters.Length; i++) {
if (arguments [i] == null)
throw new ArgumentNullException ("arguments");
if (!IsAssignableToParameterType (arguments [i].Type, parameters [i])) {
if (!parameters [i].ParameterType.IsExpression ())
throw new ArgumentException ("arguments");
arguments [i] = Expression.Quote (arguments [i]);
}
}
return arguments.ToReadOnlyCollection ();
}
public static NewExpression New (ConstructorInfo constructor, IEnumerable<Expression> arguments, params MemberInfo [] members)
{
return New (constructor, arguments, members as IEnumerable<MemberInfo>);
}
public static NewExpression New (ConstructorInfo constructor, IEnumerable<Expression> arguments, IEnumerable<MemberInfo> members)
{
if (constructor == null)
throw new ArgumentNullException ("constructor");
var args = arguments.ToReadOnlyCollection ();
var mmbs = members.ToReadOnlyCollection ();
CheckForNull (args, "arguments");
CheckForNull (mmbs, "members");
args = CheckMethodArguments (constructor, arguments);
if (args.Count != mmbs.Count)
throw new ArgumentException ("Arguments count does not match members count");
for (int i = 0; i < mmbs.Count; i++) {
var member = mmbs [i];
Type type = null;
switch (member.MemberType) {
case MemberTypes.Field:
type = (member as FieldInfo).FieldType;
break;
case MemberTypes.Method:
type = (member as MethodInfo).ReturnType;
break;
case MemberTypes.Property:
var prop = member as PropertyInfo;
if (prop.GetGetMethod (true) == null)
throw new ArgumentException ("Property must have a getter");
type = (member as PropertyInfo).PropertyType;
break;
default:
throw new ArgumentException ("Member type not allowed");
}
if (!args [i].Type.IsAssignableTo (type))
throw new ArgumentException ("Argument type not assignable to member type");
}
return new NewExpression (constructor, args, mmbs);
}
public static NewArrayExpression NewArrayBounds (Type type, params Expression [] bounds)
{
return NewArrayBounds (type, bounds as IEnumerable<Expression>);
}
public static NewArrayExpression NewArrayBounds (Type type, IEnumerable<Expression> bounds)
{
if (type == null)
throw new ArgumentNullException ("type");
if (bounds == null)
throw new ArgumentNullException ("bounds");
CheckNotVoid (type);
var array_bounds = bounds.ToReadOnlyCollection ();
foreach (var expression in array_bounds)
if (!IsInt (expression.Type))
throw new ArgumentException ("The bounds collection can only contain expression of integers types");
return new NewArrayExpression (ExpressionType.NewArrayBounds, type.MakeArrayType (array_bounds.Count), array_bounds);
}
public static NewArrayExpression NewArrayInit (Type type, params Expression [] initializers)
{
return NewArrayInit (type, initializers as IEnumerable<Expression>);
}
public static NewArrayExpression NewArrayInit (Type type, IEnumerable<Expression> initializers)
{
if (type == null)
throw new ArgumentNullException ("type");
if (initializers == null)
throw new ArgumentNullException ("initializers");
CheckNotVoid (type);
var inits = initializers.ToReadOnlyCollection ();
foreach (var expression in inits) {
if (expression == null)
throw new ArgumentNullException ("initializers");
if (!expression.Type.IsAssignableTo (type))
throw new InvalidOperationException (
string.Format ("{0} IsAssignableTo {1}, expression [ {2} ] : {3}", expression.Type, type, expression.NodeType, expression));
// TODO: Quote elements if type == typeof (Expression)
}
return new NewArrayExpression (ExpressionType.NewArrayInit, type.MakeArrayType (), inits);
}
public static UnaryExpression Not (Expression expression)
{
return Not (expression, null);
}
public static UnaryExpression Not (Expression expression, MethodInfo method)
{
Func<Type, bool> validator = type => IsIntOrBool (type);
method = UnaryCoreCheck ("op_LogicalNot", expression, method, validator);
if (method == null)
method = UnaryCoreCheck ("op_OnesComplement", expression, method, validator);
return MakeSimpleUnary (ExpressionType.Not, expression, method);
}
static void CheckNotVoid (Type type)
{
if (type == typeof (void))
throw new ArgumentException ("Type can't be void");
}
public static ParameterExpression Parameter (Type type, string name)
{
if (type == null)
throw new ArgumentNullException ("type");
CheckNotVoid (type);
return new ParameterExpression (type, name);
}
public static MemberExpression Property (Expression expression, MethodInfo propertyAccessor)
{
if (propertyAccessor == null)
throw new ArgumentNullException ("propertyAccessor");
CheckNonGenericMethod (propertyAccessor);
if (!propertyAccessor.IsStatic) {
if (expression == null)
throw new ArgumentNullException ("expression");
if (!expression.Type.IsAssignableTo (propertyAccessor.DeclaringType))
throw new ArgumentException ("expression");
}
//
// .NET does not mandate that if the property is static, that the expression must be null
// fixes a bug exposed by Orchard's ContentItemRecordAlteration.Alteration
// else if (expression != null)
// throw new ArgumentException ("expression");
var prop = GetAssociatedProperty (propertyAccessor);
if (prop == null)
throw new ArgumentException (string.Format ("Method {0} has no associated property", propertyAccessor));
return new MemberExpression (expression, prop, prop.PropertyType);
}
static PropertyInfo GetAssociatedProperty (MethodInfo method)
{
if (method == null)
return null;
foreach (var prop in method.DeclaringType.GetProperties (All)) {
if (method.Equals (prop.GetGetMethod (true)))
return prop;
if (method.Equals (prop.GetSetMethod (true)))
return prop;
}
return null;
}
public static MemberExpression Property (Expression expression, PropertyInfo property)
{
if (property == null)
throw new ArgumentNullException ("property");
var getter = property.GetGetMethod (true);
if (getter == null)
throw new ArgumentException ("getter");
if (!getter.IsStatic) {
if (expression == null)
throw new ArgumentNullException ("expression");
if (!expression.Type.IsAssignableTo (property.DeclaringType))
throw new ArgumentException ("expression");
} else if (expression != null)
throw new ArgumentException ("expression");
return new MemberExpression (expression, property, property.PropertyType);
}
public static MemberExpression Property (Expression expression, string propertyName)
{
if (expression == null)
throw new ArgumentNullException ("expression");
var prop = expression.Type.GetProperty (propertyName, AllInstance);
if (prop == null)
throw new ArgumentException (string.Format ("No property named {0} on {1}", propertyName, expression.Type));
return new MemberExpression (expression, prop, prop.PropertyType);
}
public static MemberExpression PropertyOrField (Expression expression, string propertyOrFieldName)
{
if (expression == null)
throw new ArgumentNullException ("expression");
if (propertyOrFieldName == null)
throw new ArgumentNullException ("propertyOrFieldName");
var prop = expression.Type.GetProperty (propertyOrFieldName, AllInstance);
if (prop != null)
return new MemberExpression (expression, prop, prop.PropertyType);
var field = expression.Type.GetField (propertyOrFieldName, AllInstance);
if (field != null)
return new MemberExpression (expression, field, field.FieldType);
throw new ArgumentException (string.Format ("No field or property named {0} on {1}", propertyOrFieldName, expression.Type));
}
public static UnaryExpression Quote (Expression expression)
{
if (expression == null)
throw new ArgumentNullException ("expression");
return new UnaryExpression (ExpressionType.Quote, expression, expression.GetType ());
}
public static UnaryExpression TypeAs (Expression expression, Type type)
{
if (expression == null)
throw new ArgumentNullException ("expression");
if (type == null)
throw new ArgumentNullException ("type");
if (type.IsValueType && !type.IsNullable ())
throw new ArgumentException ("TypeAs expect a reference or a nullable type");
return new UnaryExpression (ExpressionType.TypeAs, expression, type);
}
public static TypeBinaryExpression TypeIs (Expression expression, Type type)
{
if (expression == null)
throw new ArgumentNullException ("expression");
if (type == null)
throw new ArgumentNullException ("type");
CheckNotVoid (type);
return new TypeBinaryExpression (ExpressionType.TypeIs, expression, type, typeof (bool));
}
public static UnaryExpression UnaryPlus (Expression expression)
{
return UnaryPlus (expression, null);
}
public static UnaryExpression UnaryPlus (Expression expression, MethodInfo method)
{
method = UnaryCoreCheck ("op_UnaryPlus", expression, method, type => IsNumber (type));
return MakeSimpleUnary (ExpressionType.UnaryPlus, expression, method);
}
static bool IsInt (Type t)
{
return t == typeof (byte) || t == typeof (sbyte) ||
t == typeof (short) || t == typeof (ushort) ||
t == typeof (int) || t == typeof (uint) ||
t == typeof (long) || t == typeof (ulong);
}
static bool IsIntOrBool (Type t)
{
return IsInt (t) || t == typeof (bool);
}
static bool IsNumber (Type t)
{
if (IsInt (t))
return true;
return t == typeof (float) || t == typeof (double);
}
static bool IsSignedNumber (Type t)
{
return IsNumber (t) && !IsUnsigned (t);
}
internal static bool IsUnsigned (Type t)
{
#if !TARGET_JVM
if (t.IsPointer)
return IsUnsigned (t.GetElementType ());
#endif
return t == typeof (ushort) ||
t == typeof (uint) ||
t == typeof (ulong) ||
t == typeof (byte);
}
//
// This method must be overwritten by derived classes to
// compile the expression
//
internal virtual void Emit (EmitContext ec)
{
throw new NotImplementedException (String.Format ("Emit method is not implemented in expression type {0}", GetType ()));
}
}
}
|