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
|
//
// anonymous.cs: Support for anonymous methods and types
//
// Author:
// Miguel de Icaza (miguel@ximain.com)
// Marek Safar (marek.safar@gmail.com)
//
// Dual licensed under the terms of the MIT X11 or GNU GPL
// Copyright 2003-2011 Novell, Inc.
// Copyright 2011 Xamarin Inc
//
using System;
using System.Collections.Generic;
using Mono.CompilerServices.SymbolWriter;
using System.Diagnostics;
#if STATIC
using IKVM.Reflection;
using IKVM.Reflection.Emit;
using System.Diagnostics;
#else
using System.Reflection;
using System.Reflection.Emit;
#endif
namespace Mono.CSharp {
public abstract class CompilerGeneratedContainer : ClassOrStruct
{
protected CompilerGeneratedContainer (TypeContainer parent, MemberName name, Modifiers mod)
: this (parent, name, mod, MemberKind.Class)
{
}
protected CompilerGeneratedContainer (TypeContainer parent, MemberName name, Modifiers mod, MemberKind kind)
: base (parent, name, null, kind)
{
Debug.Assert ((mod & Modifiers.AccessibilityMask) != 0);
ModFlags = mod | Modifiers.COMPILER_GENERATED | Modifiers.SEALED;
spec = new TypeSpec (Kind, null, this, null, ModFlags);
}
protected void CheckMembersDefined ()
{
if (HasMembersDefined)
throw new InternalErrorException ("Helper class already defined!");
}
protected override bool DoDefineMembers ()
{
if (Kind == MemberKind.Class && !IsStatic && !PartialContainer.HasInstanceConstructor) {
DefineDefaultConstructor (false);
}
return base.DoDefineMembers ();
}
protected static MemberName MakeMemberName (MemberBase host, string name, int unique_id, TypeParameters tparams, Location loc)
{
string host_name = host == null ? null : host is InterfaceMemberBase ? ((InterfaceMemberBase)host).GetFullName (host.MemberName) : host.MemberName.Name;
string tname = MakeName (host_name, "c", name, unique_id);
TypeParameters args = null;
if (tparams != null) {
args = new TypeParameters (tparams.Count);
// Type parameters will be filled later when we have TypeContainer
// instance, for now we need only correct arity to create valid name
for (int i = 0; i < tparams.Count; ++i)
args.Add ((TypeParameter) null);
}
return new MemberName (tname, args, loc);
}
public static string MakeName (string host, string typePrefix, string name, int id)
{
return "<" + host + ">" + typePrefix + "__" + name + id.ToString ("X");
}
protected override TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class)
{
base_type = Compiler.BuiltinTypes.Object;
base_class = null;
return null;
}
}
public class HoistedStoreyClass : CompilerGeneratedContainer
{
public sealed class HoistedField : Field
{
public HoistedField (HoistedStoreyClass parent, FullNamedExpression type, Modifiers mod, string name,
Attributes attrs, Location loc)
: base (parent, type, mod, new MemberName (name, loc), attrs)
{
}
protected override bool ResolveMemberType ()
{
if (!base.ResolveMemberType ())
return false;
HoistedStoreyClass parent = ((HoistedStoreyClass) Parent).GetGenericStorey ();
if (parent != null && parent.Mutator != null)
member_type = parent.Mutator.Mutate (MemberType);
return true;
}
}
protected TypeParameterMutator mutator;
public HoistedStoreyClass (TypeDefinition parent, MemberName name, TypeParameters tparams, Modifiers mods, MemberKind kind)
: base (parent, name, mods | Modifiers.PRIVATE, kind)
{
if (tparams != null) {
var type_params = name.TypeParameters;
var src = new TypeParameterSpec[tparams.Count];
var dst = new TypeParameterSpec[tparams.Count];
for (int i = 0; i < tparams.Count; ++i) {
type_params[i] = tparams[i].CreateHoistedCopy (spec);
src[i] = tparams[i].Type;
dst[i] = type_params[i].Type;
}
// A copy is not enough, inflate any type parameter constraints
// using a new type parameters
var inflator = new TypeParameterInflator (this, null, src, dst);
for (int i = 0; i < tparams.Count; ++i) {
src[i].InflateConstraints (inflator, dst[i]);
}
mutator = new TypeParameterMutator (tparams, type_params);
}
}
#region Properties
public TypeParameterMutator Mutator {
get {
return mutator;
}
set {
mutator = value;
}
}
#endregion
public HoistedStoreyClass GetGenericStorey ()
{
TypeContainer storey = this;
while (storey != null && storey.CurrentTypeParameters == null)
storey = storey.Parent;
return storey as HoistedStoreyClass;
}
}
//
// Anonymous method storey is created when an anonymous method uses
// variable or parameter from outer scope. They are then hoisted to
// anonymous method storey (captured)
//
public class AnonymousMethodStorey : HoistedStoreyClass
{
struct StoreyFieldPair
{
public readonly AnonymousMethodStorey Storey;
public readonly Field Field;
public StoreyFieldPair (AnonymousMethodStorey storey, Field field)
{
this.Storey = storey;
this.Field = field;
}
}
//
// Needed to delay hoisted _this_ initialization. When an anonymous
// method is used inside ctor and _this_ is hoisted, base ctor has to
// be called first, otherwise _this_ will be initialized with
// uninitialized value.
//
sealed class ThisInitializer : Statement
{
readonly HoistedThis hoisted_this;
public ThisInitializer (HoistedThis hoisted_this)
{
this.hoisted_this = hoisted_this;
}
protected override void DoEmit (EmitContext ec)
{
hoisted_this.EmitAssign (ec, new CompilerGeneratedThis (ec.CurrentType, loc), false, false);
}
protected override void CloneTo (CloneContext clonectx, Statement target)
{
// Nothing to clone
}
}
// Unique storey ID
public readonly int ID;
public readonly ExplicitBlock OriginalSourceBlock;
// A list of StoreyFieldPair with local field keeping parent storey instance
List<StoreyFieldPair> used_parent_storeys;
List<ExplicitBlock> children_references;
// A list of hoisted parameters
protected List<HoistedParameter> hoisted_params;
List<HoistedParameter> hoisted_local_params;
protected List<HoistedVariable> hoisted_locals;
// Hoisted this
protected HoistedThis hoisted_this;
// Local variable which holds this storey instance
public Expression Instance;
bool initialize_hoisted_this;
public AnonymousMethodStorey (ExplicitBlock block, TypeDefinition parent, MemberBase host, TypeParameters tparams, string name, MemberKind kind)
: base (parent, MakeMemberName (host, name, parent.Module.CounterAnonymousContainers, tparams, block.StartLocation),
tparams, 0, kind)
{
OriginalSourceBlock = block;
ID = parent.Module.CounterAnonymousContainers++;
}
public void AddCapturedThisField (EmitContext ec)
{
TypeExpr type_expr = new TypeExpression (ec.CurrentType, Location);
Field f = AddCompilerGeneratedField ("$this", type_expr);
hoisted_this = new HoistedThis (this, f);
initialize_hoisted_this = true;
}
public Field AddCapturedVariable (string name, TypeSpec type)
{
CheckMembersDefined ();
FullNamedExpression field_type = new TypeExpression (type, Location);
if (!spec.IsGenericOrParentIsGeneric)
return AddCompilerGeneratedField (name, field_type);
const Modifiers mod = Modifiers.INTERNAL | Modifiers.COMPILER_GENERATED;
Field f = new HoistedField (this, field_type, mod, name, null, Location);
AddField (f);
return f;
}
protected Field AddCompilerGeneratedField (string name, FullNamedExpression type)
{
return AddCompilerGeneratedField (name, type, false);
}
protected Field AddCompilerGeneratedField (string name, FullNamedExpression type, bool privateAccess)
{
Modifiers mod = Modifiers.COMPILER_GENERATED | (privateAccess ? Modifiers.PRIVATE : Modifiers.INTERNAL);
Field f = new Field (this, type, mod, new MemberName (name, Location), null);
AddField (f);
return f;
}
//
// Creates a link between hoisted variable block and the anonymous method storey
//
// An anonymous method can reference variables from any outer block, but they are
// hoisted in their own ExplicitBlock. When more than one block is referenced we
// need to create another link between those variable storeys
//
public void AddReferenceFromChildrenBlock (ExplicitBlock block)
{
if (children_references == null)
children_references = new List<ExplicitBlock> ();
if (!children_references.Contains (block))
children_references.Add (block);
}
public void AddParentStoreyReference (EmitContext ec, AnonymousMethodStorey storey)
{
CheckMembersDefined ();
if (used_parent_storeys == null)
used_parent_storeys = new List<StoreyFieldPair> ();
else if (used_parent_storeys.Exists (i => i.Storey == storey))
return;
TypeExpr type_expr = storey.CreateStoreyTypeExpression (ec);
Field f = AddCompilerGeneratedField ("<>f__ref$" + storey.ID, type_expr);
used_parent_storeys.Add (new StoreyFieldPair (storey, f));
}
public void CaptureLocalVariable (ResolveContext ec, LocalVariable localVariable)
{
if (this is StateMachine) {
if (ec.CurrentBlock.ParametersBlock != localVariable.Block.ParametersBlock)
ec.CurrentBlock.Explicit.HasCapturedVariable = true;
} else {
ec.CurrentBlock.Explicit.HasCapturedVariable = true;
}
var hoisted = localVariable.HoistedVariant;
if (hoisted != null && hoisted.Storey != this && hoisted.Storey is StateMachine) {
//
// Variable is already hoisted but we need it in storey which can be shared
//
hoisted.Storey.hoisted_locals.Remove (hoisted);
hoisted.Storey.Members.Remove (hoisted.Field);
hoisted = null;
}
if (hoisted == null) {
hoisted = new HoistedLocalVariable (this, localVariable, GetVariableMangledName (localVariable));
localVariable.HoistedVariant = hoisted;
if (hoisted_locals == null)
hoisted_locals = new List<HoistedVariable> ();
hoisted_locals.Add (hoisted);
}
if (ec.CurrentBlock.Explicit != localVariable.Block.Explicit && !(hoisted.Storey is StateMachine))
hoisted.Storey.AddReferenceFromChildrenBlock (ec.CurrentBlock.Explicit);
}
public void CaptureParameter (ResolveContext ec, ParametersBlock.ParameterInfo parameterInfo, ParameterReference parameterReference)
{
if (!(this is StateMachine)) {
ec.CurrentBlock.Explicit.HasCapturedVariable = true;
}
var hoisted = parameterInfo.Parameter.HoistedVariant;
if (parameterInfo.Block.StateMachine != null) {
//
// Another storey in same block exists but state machine does not
// have parameter captured. We need to add it there as well to
// proxy parameter value correctly.
//
if (hoisted == null && parameterInfo.Block.StateMachine != this) {
var storey = parameterInfo.Block.StateMachine;
hoisted = new HoistedParameter (storey, parameterReference);
parameterInfo.Parameter.HoistedVariant = hoisted;
if (storey.hoisted_params == null)
storey.hoisted_params = new List<HoistedParameter> ();
storey.hoisted_params.Add (hoisted);
}
//
// Lift captured parameter from value type storey to reference type one. Otherwise
// any side effects would be done on a copy
//
if (hoisted != null && hoisted.Storey != this && hoisted.Storey is StateMachine) {
if (hoisted_local_params == null)
hoisted_local_params = new List<HoistedParameter> ();
hoisted_local_params.Add (hoisted);
hoisted = null;
}
}
if (hoisted == null) {
hoisted = new HoistedParameter (this, parameterReference);
parameterInfo.Parameter.HoistedVariant = hoisted;
if (hoisted_params == null)
hoisted_params = new List<HoistedParameter> ();
hoisted_params.Add (hoisted);
}
//
// Register link between current block and parameter storey. It will
// be used when setting up storey definition to deploy storey reference
// when parameters are used from multiple blocks
//
if (ec.CurrentBlock.Explicit != parameterInfo.Block) {
hoisted.Storey.AddReferenceFromChildrenBlock (ec.CurrentBlock.Explicit);
}
}
TypeExpr CreateStoreyTypeExpression (EmitContext ec)
{
//
// Create an instance of storey type
//
TypeExpr storey_type_expr;
if (CurrentTypeParameters != null) {
//
// Use current method type parameter (MVAR) for top level storey only. All
// nested storeys use class type parameter (VAR)
//
var tparams = ec.CurrentAnonymousMethod != null && ec.CurrentAnonymousMethod.Storey != null ?
ec.CurrentAnonymousMethod.Storey.CurrentTypeParameters :
ec.CurrentTypeParameters;
TypeArguments targs = new TypeArguments ();
//
// Use type parameter name instead of resolved type parameter
// specification to resolve to correctly nested type parameters
//
for (int i = 0; i < tparams.Count; ++i)
targs.Add (new SimpleName (tparams [i].Name, Location)); // new TypeParameterExpr (tparams[i], Location));
storey_type_expr = new GenericTypeExpr (Definition, targs, Location);
} else {
storey_type_expr = new TypeExpression (CurrentType, Location);
}
return storey_type_expr;
}
public void SetNestedStoryParent (AnonymousMethodStorey parentStorey)
{
Parent = parentStorey;
spec.IsGeneric = false;
spec.DeclaringType = parentStorey.CurrentType;
MemberName.TypeParameters = null;
}
protected override bool DoResolveTypeParameters ()
{
// Although any storey can have type parameters they are all clones of method type
// parameters therefore have to mutate MVAR references in any of cloned constraints
if (CurrentTypeParameters != null) {
for (int i = 0; i < CurrentTypeParameters.Count; ++i) {
var spec = CurrentTypeParameters[i].Type;
spec.BaseType = mutator.Mutate (spec.BaseType);
if (spec.InterfacesDefined != null) {
var mutated = new TypeSpec[spec.InterfacesDefined.Length];
for (int ii = 0; ii < mutated.Length; ++ii) {
mutated[ii] = mutator.Mutate (spec.InterfacesDefined[ii]);
}
spec.InterfacesDefined = mutated;
}
if (spec.TypeArguments != null) {
spec.TypeArguments = mutator.Mutate (spec.TypeArguments);
}
}
}
//
// Update parent cache as we most likely passed the point
// where the cache was constructed
//
Parent.CurrentType.MemberCache.AddMember (this.spec);
return true;
}
//
// Initializes all hoisted variables
//
public void EmitStoreyInstantiation (EmitContext ec, ExplicitBlock block)
{
// There can be only one instance variable for each storey type
if (Instance != null)
throw new InternalErrorException ();
//
// Create an instance of this storey
//
ResolveContext rc = new ResolveContext (ec.MemberContext);
rc.CurrentBlock = block;
var storey_type_expr = CreateStoreyTypeExpression (ec);
var source = new New (storey_type_expr, null, Location).Resolve (rc);
//
// When the current context is async (or iterator) lift local storey
// instantiation to the currect storey
//
if (ec.CurrentAnonymousMethod is StateMachineInitializer && (block.HasYield || block.HasAwait)) {
//
// Unfortunately, normal capture mechanism could not be used because we are
// too late in the pipeline and standart assign cannot be used either due to
// recursive nature of GetStoreyInstanceExpression
//
var field = ec.CurrentAnonymousMethod.Storey.AddCompilerGeneratedField (
LocalVariable.GetCompilerGeneratedName (block), storey_type_expr, true);
field.Define ();
field.Emit ();
var fexpr = new FieldExpr (field, Location);
fexpr.InstanceExpression = new CompilerGeneratedThis (ec.CurrentType, Location);
fexpr.EmitAssign (ec, source, false, false);
Instance = fexpr;
} else {
var local = TemporaryVariableReference.Create (source.Type, block, Location);
if (source.Type.IsStruct) {
local.LocalInfo.CreateBuilder (ec);
} else {
local.EmitAssign (ec, source);
}
Instance = local;
}
EmitHoistedFieldsInitialization (rc, ec);
// TODO: Implement properly
//SymbolWriter.DefineScopeVariable (ID, Instance.Builder);
}
void EmitHoistedFieldsInitialization (ResolveContext rc, EmitContext ec)
{
//
// Initialize all storey reference fields by using local or hoisted variables
//
if (used_parent_storeys != null) {
foreach (StoreyFieldPair sf in used_parent_storeys) {
//
// Get instance expression of storey field
//
Expression instace_expr = GetStoreyInstanceExpression (ec);
var fs = sf.Field.Spec;
if (TypeManager.IsGenericType (instace_expr.Type))
fs = MemberCache.GetMember (instace_expr.Type, fs);
FieldExpr f_set_expr = new FieldExpr (fs, Location);
f_set_expr.InstanceExpression = instace_expr;
// TODO: CompilerAssign expression
SimpleAssign a = new SimpleAssign (f_set_expr, sf.Storey.GetStoreyInstanceExpression (ec));
if (a.Resolve (rc) != null)
a.EmitStatement (ec);
}
}
//
// Initialize hoisted `this' only once, everywhere else will be
// referenced indirectly
//
if (initialize_hoisted_this) {
rc.CurrentBlock.AddScopeStatement (new ThisInitializer (hoisted_this));
}
//
// Setting currect anonymous method to null blocks any further variable hoisting
//
AnonymousExpression ae = ec.CurrentAnonymousMethod;
ec.CurrentAnonymousMethod = null;
if (hoisted_params != null) {
EmitHoistedParameters (ec, hoisted_params);
}
ec.CurrentAnonymousMethod = ae;
}
protected virtual void EmitHoistedParameters (EmitContext ec, List<HoistedParameter> hoisted)
{
foreach (HoistedParameter hp in hoisted) {
if (hp == null)
continue;
//
// Parameters could be proxied via local fields for value type storey
//
if (hoisted_local_params != null) {
var local_param = hoisted_local_params.Find (l => l.Parameter.Parameter == hp.Parameter.Parameter);
var source = new FieldExpr (local_param.Field, Location);
source.InstanceExpression = new CompilerGeneratedThis (CurrentType, Location);
hp.EmitAssign (ec, source, false, false);
continue;
}
hp.EmitHoistingAssignment (ec);
}
}
//
// Returns a field which holds referenced storey instance
//
Field GetReferencedStoreyField (AnonymousMethodStorey storey)
{
if (used_parent_storeys == null)
return null;
foreach (StoreyFieldPair sf in used_parent_storeys) {
if (sf.Storey == storey)
return sf.Field;
}
return null;
}
//
// Creates storey instance expression regardless of currect IP
//
public Expression GetStoreyInstanceExpression (EmitContext ec)
{
AnonymousExpression am = ec.CurrentAnonymousMethod;
//
// Access from original block -> storey
//
if (am == null)
return Instance;
//
// Access from anonymous method implemented as a static -> storey
//
if (am.Storey == null)
return Instance;
Field f = am.Storey.GetReferencedStoreyField (this);
if (f == null) {
if (am.Storey == this) {
//
// Access from inside of same storey (S -> S)
//
return new CompilerGeneratedThis (CurrentType, Location);
}
//
// External field access
//
return Instance;
}
//
// Storey was cached to local field
//
FieldExpr f_ind = new FieldExpr (f, Location);
f_ind.InstanceExpression = new CompilerGeneratedThis (CurrentType, Location);
return f_ind;
}
protected virtual string GetVariableMangledName (LocalVariable local_info)
{
//
// No need to mangle anonymous method hoisted variables cause they
// are hoisted in their own scopes
//
return local_info.Name;
}
public HoistedThis HoistedThis {
get {
return hoisted_this;
}
set {
hoisted_this = value;
}
}
public IList<ExplicitBlock> ReferencesFromChildrenBlock {
get { return children_references; }
}
}
public abstract class HoistedVariable
{
//
// Hoisted version of variable references used in expression
// tree has to be delayed until we know its location. The variable
// doesn't know its location until all stories are calculated
//
class ExpressionTreeVariableReference : Expression
{
readonly HoistedVariable hv;
public ExpressionTreeVariableReference (HoistedVariable hv)
{
this.hv = hv;
}
public override bool ContainsEmitWithAwait ()
{
return false;
}
public override Expression CreateExpressionTree (ResolveContext ec)
{
return hv.CreateExpressionTree ();
}
protected override Expression DoResolve (ResolveContext ec)
{
eclass = ExprClass.Value;
type = ec.Module.PredefinedTypes.Expression.Resolve ();
return this;
}
public override void Emit (EmitContext ec)
{
ResolveContext rc = new ResolveContext (ec.MemberContext);
Expression e = hv.GetFieldExpression (ec).CreateExpressionTree (rc, false);
// This should never fail
e = e.Resolve (rc);
if (e != null)
e.Emit (ec);
}
}
protected readonly AnonymousMethodStorey storey;
protected Field field;
Dictionary<AnonymousExpression, FieldExpr> cached_inner_access; // TODO: Hashtable is too heavyweight
FieldExpr cached_outer_access;
protected HoistedVariable (AnonymousMethodStorey storey, string name, TypeSpec type)
: this (storey, storey.AddCapturedVariable (name, type))
{
}
protected HoistedVariable (AnonymousMethodStorey storey, Field field)
{
this.storey = storey;
this.field = field;
}
public Field Field {
get {
return field;
}
}
public AnonymousMethodStorey Storey {
get {
return storey;
}
}
public void AddressOf (EmitContext ec, AddressOp mode)
{
GetFieldExpression (ec).AddressOf (ec, mode);
}
public Expression CreateExpressionTree ()
{
return new ExpressionTreeVariableReference (this);
}
public void Emit (EmitContext ec)
{
GetFieldExpression (ec).Emit (ec);
}
public Expression EmitToField (EmitContext ec)
{
return GetFieldExpression (ec);
}
//
// Creates field access expression for hoisted variable
//
protected virtual FieldExpr GetFieldExpression (EmitContext ec)
{
if (ec.CurrentAnonymousMethod == null || ec.CurrentAnonymousMethod.Storey == null) {
if (cached_outer_access != null)
return cached_outer_access;
//
// When setting top-level hoisted variable in generic storey
// change storey generic types to method generic types (VAR -> MVAR)
//
if (storey.Instance.Type.IsGenericOrParentIsGeneric) {
var fs = MemberCache.GetMember (storey.Instance.Type, field.Spec);
cached_outer_access = new FieldExpr (fs, field.Location);
} else {
cached_outer_access = new FieldExpr (field, field.Location);
}
cached_outer_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
return cached_outer_access;
}
FieldExpr inner_access;
if (cached_inner_access != null) {
if (!cached_inner_access.TryGetValue (ec.CurrentAnonymousMethod, out inner_access))
inner_access = null;
} else {
inner_access = null;
cached_inner_access = new Dictionary<AnonymousExpression, FieldExpr> (4);
}
if (inner_access == null) {
if (field.Parent.IsGenericOrParentIsGeneric) {
var fs = MemberCache.GetMember (field.Parent.CurrentType, field.Spec);
inner_access = new FieldExpr (fs, field.Location);
} else {
inner_access = new FieldExpr (field, field.Location);
}
inner_access.InstanceExpression = storey.GetStoreyInstanceExpression (ec);
cached_inner_access.Add (ec.CurrentAnonymousMethod, inner_access);
}
return inner_access;
}
public void Emit (EmitContext ec, bool leave_copy)
{
GetFieldExpression (ec).Emit (ec, leave_copy);
}
public void EmitAssign (EmitContext ec, Expression source, bool leave_copy, bool isCompound)
{
GetFieldExpression (ec).EmitAssign (ec, source, leave_copy, false);
}
}
public class HoistedParameter : HoistedVariable
{
sealed class HoistedFieldAssign : CompilerAssign
{
public HoistedFieldAssign (Expression target, Expression source)
: base (target, source, target.Location)
{
}
protected override Expression ResolveConversions (ResolveContext ec)
{
//
// Implicit conversion check fails for hoisted type arguments
// as they are of different types (!!0 x !0)
//
return this;
}
}
readonly ParameterReference parameter;
public HoistedParameter (AnonymousMethodStorey scope, ParameterReference par)
: base (scope, par.Name, par.Type)
{
this.parameter = par;
}
public HoistedParameter (HoistedParameter hp, string name)
: base (hp.storey, name, hp.parameter.Type)
{
this.parameter = hp.parameter;
}
#region Properties
public bool IsAssigned { get; set; }
public ParameterReference Parameter {
get {
return parameter;
}
}
#endregion
public void EmitHoistingAssignment (EmitContext ec)
{
//
// Remove hoisted redirection to emit assignment from original parameter
//
var temp = parameter.Parameter.HoistedVariant;
parameter.Parameter.HoistedVariant = null;
var a = new HoistedFieldAssign (GetFieldExpression (ec), parameter);
a.EmitStatement (ec);
parameter.Parameter.HoistedVariant = temp;
}
}
class HoistedLocalVariable : HoistedVariable
{
public HoistedLocalVariable (AnonymousMethodStorey storey, LocalVariable local, string name)
: base (storey, name, local.Type)
{
}
}
public class HoistedThis : HoistedVariable
{
public HoistedThis (AnonymousMethodStorey storey, Field field)
: base (storey, field)
{
}
}
//
// Anonymous method expression as created by parser
//
public class AnonymousMethodExpression : Expression
{
//
// Special conversion for nested expression tree lambdas
//
class Quote : ShimExpression
{
public Quote (Expression expr)
: base (expr)
{
}
public override Expression CreateExpressionTree (ResolveContext ec)
{
var args = new Arguments (1);
args.Add (new Argument (expr.CreateExpressionTree (ec)));
return CreateExpressionFactoryCall (ec, "Quote", args);
}
protected override Expression DoResolve (ResolveContext rc)
{
expr = expr.Resolve (rc);
if (expr == null)
return null;
eclass = expr.eclass;
type = expr.Type;
return this;
}
}
readonly Dictionary<TypeSpec, Expression> compatibles;
public ParametersBlock Block;
public AnonymousMethodExpression (Location loc)
{
this.loc = loc;
this.compatibles = new Dictionary<TypeSpec, Expression> ();
}
#region Properties
public override string ExprClassName {
get {
return "anonymous method";
}
}
public virtual bool HasExplicitParameters {
get {
return Parameters != ParametersCompiled.Undefined;
}
}
public ParametersCompiled Parameters {
get {
return Block.Parameters;
}
}
public bool IsAsync {
get;
internal set;
}
public ReportPrinter TypeInferenceReportPrinter {
get; set;
}
#endregion
//
// Returns true if the body of lambda expression can be implicitly
// converted to the delegate of type `delegate_type'
//
public bool ImplicitStandardConversionExists (ResolveContext ec, TypeSpec delegate_type)
{
using (ec.With (ResolveContext.Options.InferReturnType, false)) {
using (ec.Set (ResolveContext.Options.ProbingMode)) {
var prev = ec.Report.SetPrinter (TypeInferenceReportPrinter ?? new NullReportPrinter ());
var res = Compatible (ec, delegate_type) != null;
ec.Report.SetPrinter (prev);
return res;
}
}
}
TypeSpec CompatibleChecks (ResolveContext ec, TypeSpec delegate_type)
{
if (delegate_type.IsDelegate)
return delegate_type;
if (delegate_type.IsExpressionTreeType) {
delegate_type = delegate_type.TypeArguments [0];
if (delegate_type.IsDelegate)
return delegate_type;
ec.Report.Error (835, loc, "Cannot convert `{0}' to an expression tree of non-delegate type `{1}'",
GetSignatureForError (), delegate_type.GetSignatureForError ());
return null;
}
ec.Report.Error (1660, loc, "Cannot convert `{0}' to non-delegate type `{1}'",
GetSignatureForError (), delegate_type.GetSignatureForError ());
return null;
}
protected bool VerifyExplicitParameters (ResolveContext ec, TypeSpec delegate_type, AParametersCollection parameters)
{
if (VerifyParameterCompatibility (ec, delegate_type, parameters, ec.IsInProbingMode))
return true;
if (!ec.IsInProbingMode)
ec.Report.Error (1661, loc,
"Cannot convert `{0}' to delegate type `{1}' since there is a parameter mismatch",
GetSignatureForError (), delegate_type.GetSignatureForError ());
return false;
}
protected bool VerifyParameterCompatibility (ResolveContext ec, TypeSpec delegate_type, AParametersCollection invoke_pd, bool ignore_errors)
{
if (Parameters.Count != invoke_pd.Count) {
if (ignore_errors)
return false;
ec.Report.Error (1593, loc, "Delegate `{0}' does not take `{1}' arguments",
delegate_type.GetSignatureForError (), Parameters.Count.ToString ());
return false;
}
bool has_implicit_parameters = !HasExplicitParameters;
bool error = false;
for (int i = 0; i < Parameters.Count; ++i) {
Parameter.Modifier p_mod = invoke_pd.FixedParameters [i].ModFlags;
if (Parameters.FixedParameters [i].ModFlags != p_mod && p_mod != Parameter.Modifier.PARAMS) {
if (ignore_errors)
return false;
if (p_mod == Parameter.Modifier.NONE)
ec.Report.Error (1677, Parameters[i].Location, "Parameter `{0}' should not be declared with the `{1}' keyword",
(i + 1).ToString (), Parameter.GetModifierSignature (Parameters [i].ModFlags));
else
ec.Report.Error (1676, Parameters[i].Location, "Parameter `{0}' must be declared with the `{1}' keyword",
(i+1).ToString (), Parameter.GetModifierSignature (p_mod));
error = true;
}
if (has_implicit_parameters)
continue;
TypeSpec type = invoke_pd.Types [i];
//
// Assumes that generic mvar parameters are always inflated
//
if (ImplicitDelegateCreation.ContainsMethodTypeParameter (type))
continue;
if (!TypeSpecComparer.IsEqual (invoke_pd.Types [i], Parameters.Types [i])) {
if (ignore_errors)
return false;
ec.Report.Error (1678, Parameters [i].Location, "Parameter `{0}' is declared as type `{1}' but should be `{2}'",
(i+1).ToString (),
Parameters.Types [i].GetSignatureForError (),
invoke_pd.Types [i].GetSignatureForError ());
error = true;
}
}
return !error;
}
//
// Infers type arguments based on explicit arguments
//
public bool ExplicitTypeInference (ResolveContext ec, TypeInferenceContext type_inference, TypeSpec delegate_type)
{
if (!HasExplicitParameters)
return false;
if (!delegate_type.IsDelegate) {
if (!delegate_type.IsExpressionTreeType)
return false;
delegate_type = TypeManager.GetTypeArguments (delegate_type) [0];
if (!delegate_type.IsDelegate)
return false;
}
AParametersCollection d_params = Delegate.GetParameters (delegate_type);
if (d_params.Count != Parameters.Count)
return false;
var ptypes = Parameters.Types;
var dtypes = d_params.Types;
for (int i = 0; i < Parameters.Count; ++i) {
if (type_inference.ExactInference (ptypes[i], dtypes[i]) == 0) {
//
// Continue when 0 (quick path) does not mean inference failure. Checking for
// same type handles cases like int -> int
//
if (ptypes[i] == dtypes[i])
continue;
return false;
}
}
return true;
}
public TypeSpec InferReturnType (ResolveContext ec, TypeInferenceContext tic, TypeSpec delegate_type)
{
Expression expr;
AnonymousExpression am;
if (compatibles.TryGetValue (delegate_type, out expr)) {
am = expr as AnonymousExpression;
return am == null ? null : am.ReturnType;
}
using (ec.Set (ResolveContext.Options.ProbingMode | ResolveContext.Options.InferReturnType)) {
ReportPrinter prev;
if (TypeInferenceReportPrinter != null) {
prev = ec.Report.SetPrinter (TypeInferenceReportPrinter);
} else {
prev = null;
}
var body = CompatibleMethodBody (ec, tic, null, delegate_type);
if (body != null) {
am = body.Compatible (ec, body);
} else {
am = null;
}
if (TypeInferenceReportPrinter != null) {
ec.Report.SetPrinter (prev);
}
}
if (am == null)
return null;
// compatibles.Add (delegate_type, am);
return am.ReturnType;
}
public override bool ContainsEmitWithAwait ()
{
return false;
}
//
// Returns AnonymousMethod container if this anonymous method
// expression can be implicitly converted to the delegate type `delegate_type'
//
public Expression Compatible (ResolveContext ec, TypeSpec type)
{
Expression am;
if (compatibles.TryGetValue (type, out am))
return am;
TypeSpec delegate_type = CompatibleChecks (ec, type);
if (delegate_type == null)
return null;
//
// At this point its the first time we know the return type that is
// needed for the anonymous method. We create the method here.
//
var invoke_mb = Delegate.GetInvokeMethod (delegate_type);
TypeSpec return_type = invoke_mb.ReturnType;
//
// Second: the return type of the delegate must be compatible with
// the anonymous type. Instead of doing a pass to examine the block
// we satisfy the rule by setting the return type on the EmitContext
// to be the delegate type return type.
//
var body = CompatibleMethodBody (ec, null, return_type, delegate_type);
if (body == null)
return null;
bool etree_conversion = delegate_type != type;
try {
if (etree_conversion) {
if (ec.HasSet (ResolveContext.Options.ExpressionTreeConversion)) {
//
// Nested expression tree lambda use same scope as parent
// lambda, this also means no variable capturing between this
// and parent scope
//
am = body.Compatible (ec, ec.CurrentAnonymousMethod);
//
// Quote nested expression tree
//
if (am != null)
am = new Quote (am);
} else {
int errors = ec.Report.Errors;
if (Block.IsAsync) {
ec.Report.Error (1989, loc, "Async lambda expressions cannot be converted to expression trees");
}
using (ec.Set (ResolveContext.Options.ExpressionTreeConversion)) {
am = body.Compatible (ec);
}
//
// Rewrite expressions into expression tree when targeting Expression<T>
//
if (am != null && errors == ec.Report.Errors)
am = CreateExpressionTree (ec, delegate_type);
}
} else {
am = body.Compatible (ec);
if (body.DirectMethodGroupConversion != null) {
var errors_printer = new SessionReportPrinter ();
var old = ec.Report.SetPrinter (errors_printer);
var expr = new ImplicitDelegateCreation (delegate_type, body.DirectMethodGroupConversion, loc) {
AllowSpecialMethodsInvocation = true
}.Resolve (ec);
ec.Report.SetPrinter (old);
if (expr != null && errors_printer.ErrorsCount == 0)
am = expr;
}
}
} catch (CompletionResult) {
throw;
} catch (FatalException) {
throw;
} catch (Exception e) {
throw new InternalErrorException (e, loc);
}
if (!ec.IsInProbingMode) {
compatibles.Add (type, am ?? EmptyExpression.Null);
}
return am;
}
protected virtual Expression CreateExpressionTree (ResolveContext ec, TypeSpec delegate_type)
{
return CreateExpressionTree (ec);
}
public override Expression CreateExpressionTree (ResolveContext ec)
{
ec.Report.Error (1946, loc, "An anonymous method cannot be converted to an expression tree");
return null;
}
protected virtual ParametersCompiled ResolveParameters (ResolveContext ec, TypeInferenceContext tic, TypeSpec delegate_type)
{
var delegate_parameters = Delegate.GetParameters (delegate_type);
if (Parameters == ParametersCompiled.Undefined) {
//
// We provide a set of inaccessible parameters
//
Parameter[] fixedpars = new Parameter[delegate_parameters.Count];
for (int i = 0; i < delegate_parameters.Count; i++) {
Parameter.Modifier i_mod = delegate_parameters.FixedParameters [i].ModFlags;
if ((i_mod & Parameter.Modifier.OUT) != 0) {
if (!ec.IsInProbingMode) {
ec.Report.Error (1688, loc,
"Cannot convert anonymous method block without a parameter list to delegate type `{0}' because it has one or more `out' parameters",
delegate_type.GetSignatureForError ());
}
return null;
}
fixedpars[i] = new Parameter (
new TypeExpression (delegate_parameters.Types [i], loc), null,
delegate_parameters.FixedParameters [i].ModFlags, null, loc);
}
return ParametersCompiled.CreateFullyResolved (fixedpars, delegate_parameters.Types);
}
if (!VerifyExplicitParameters (ec, delegate_type, delegate_parameters)) {
return null;
}
return Parameters;
}
protected override Expression DoResolve (ResolveContext ec)
{
if (ec.HasSet (ResolveContext.Options.ConstantScope)) {
ec.Report.Error (1706, loc, "Anonymous methods and lambda expressions cannot be used in the current context");
return null;
}
//
// Set class type, set type
//
eclass = ExprClass.Value;
//
// This hack means `The type is not accessible
// anywhere', we depend on special conversion
// rules.
//
type = InternalType.AnonymousMethod;
if (!DoResolveParameters (ec))
return null;
#if !STATIC
// FIXME: The emitted code isn't very careful about reachability
// so, ensure we have a 'ret' at the end
BlockContext bc = ec as BlockContext;
if (bc != null && bc.CurrentBranching != null && bc.CurrentBranching.CurrentUsageVector.IsUnreachable)
bc.NeedReturnLabel ();
#endif
return this;
}
protected virtual bool DoResolveParameters (ResolveContext rc)
{
return Parameters.Resolve (rc);
}
public override void Emit (EmitContext ec)
{
// nothing, as we only exist to not do anything.
}
public static void Error_AddressOfCapturedVar (ResolveContext ec, IVariableReference var, Location loc)
{
ec.Report.Error (1686, loc,
"Local variable or parameter `{0}' cannot have their address taken and be used inside an anonymous method, lambda expression or query expression",
var.Name);
}
public override string GetSignatureForError ()
{
return ExprClassName;
}
AnonymousMethodBody CompatibleMethodBody (ResolveContext ec, TypeInferenceContext tic, TypeSpec return_type, TypeSpec delegate_type)
{
ParametersCompiled p = ResolveParameters (ec, tic, delegate_type);
if (p == null)
return null;
ParametersBlock b = ec.IsInProbingMode ? (ParametersBlock) Block.PerformClone () : Block;
if (b.IsAsync) {
var rt = return_type;
if (rt != null && rt.Kind != MemberKind.Void && rt != ec.Module.PredefinedTypes.Task.TypeSpec && !rt.IsGenericTask) {
ec.Report.Error (4010, loc, "Cannot convert async {0} to delegate type `{1}'",
GetSignatureForError (), delegate_type.GetSignatureForError ());
return null;
}
b = b.ConvertToAsyncTask (ec, ec.CurrentMemberDefinition.Parent.PartialContainer, p, return_type, delegate_type, loc);
}
return CompatibleMethodFactory (return_type ?? InternalType.ErrorType, delegate_type, p, b);
}
protected virtual AnonymousMethodBody CompatibleMethodFactory (TypeSpec return_type, TypeSpec delegate_type, ParametersCompiled p, ParametersBlock b)
{
return new AnonymousMethodBody (p, b, return_type, delegate_type, loc);
}
protected override void CloneTo (CloneContext clonectx, Expression t)
{
AnonymousMethodExpression target = (AnonymousMethodExpression) t;
target.Block = (ParametersBlock) clonectx.LookupBlock (Block);
}
public override object Accept (StructuralVisitor visitor)
{
return visitor.Visit (this);
}
}
//
// Abstract expression for any block which requires variables hoisting
//
public abstract class AnonymousExpression : ExpressionStatement
{
protected class AnonymousMethodMethod : Method
{
public readonly AnonymousExpression AnonymousMethod;
public readonly AnonymousMethodStorey Storey;
public AnonymousMethodMethod (TypeDefinition parent, AnonymousExpression am, AnonymousMethodStorey storey,
TypeExpr return_type,
Modifiers mod, MemberName name,
ParametersCompiled parameters)
: base (parent, return_type, mod | Modifiers.COMPILER_GENERATED,
name, parameters, null)
{
this.AnonymousMethod = am;
this.Storey = storey;
Parent.PartialContainer.Members.Add (this);
Block = new ToplevelBlock (am.block, parameters);
}
public override EmitContext CreateEmitContext (ILGenerator ig, SourceMethodBuilder sourceMethod)
{
EmitContext ec = new EmitContext (this, ig, ReturnType, sourceMethod);
ec.CurrentAnonymousMethod = AnonymousMethod;
return ec;
}
protected override void DefineTypeParameters ()
{
// Type parameters were cloned
}
protected override bool ResolveMemberType ()
{
if (!base.ResolveMemberType ())
return false;
if (Storey != null && Storey.Mutator != null) {
if (!parameters.IsEmpty) {
var mutated = Storey.Mutator.Mutate (parameters.Types);
if (mutated != parameters.Types)
parameters = ParametersCompiled.CreateFullyResolved ((Parameter[]) parameters.FixedParameters, mutated);
}
member_type = Storey.Mutator.Mutate (member_type);
}
return true;
}
public override void Emit ()
{
if (MethodBuilder == null) {
Define ();
}
base.Emit ();
}
}
protected readonly ParametersBlock block;
public TypeSpec ReturnType;
protected AnonymousExpression (ParametersBlock block, TypeSpec return_type, Location loc)
{
this.ReturnType = return_type;
this.block = block;
this.loc = loc;
}
public abstract string ContainerType { get; }
public abstract bool IsIterator { get; }
public abstract AnonymousMethodStorey Storey { get; }
//
// The block that makes up the body for the anonymous method
//
public ParametersBlock Block {
get {
return block;
}
}
public AnonymousExpression Compatible (ResolveContext ec)
{
return Compatible (ec, this);
}
public AnonymousExpression Compatible (ResolveContext ec, AnonymousExpression ae)
{
if (block.Resolved)
return this;
// TODO: Implement clone
BlockContext aec = new BlockContext (ec, block, ReturnType);
aec.CurrentAnonymousMethod = ae;
var am = this as AnonymousMethodBody;
if (ec.HasSet (ResolveContext.Options.InferReturnType) && am != null) {
am.ReturnTypeInference = new TypeInferenceContext ();
}
var bc = ec as BlockContext;
if (bc != null)
aec.FlowOffset = bc.FlowOffset;
var errors = ec.Report.Errors;
bool res = Block.Resolve (ec.CurrentBranching, aec, null);
if (am != null && am.ReturnTypeInference != null) {
am.ReturnTypeInference.FixAllTypes (ec);
ReturnType = am.ReturnTypeInference.InferredTypeArguments [0];
am.ReturnTypeInference = null;
//
// If e is synchronous the inferred return type is T
// If e is asynchronous the inferred return type is Task<T>
//
if (block.IsAsync && ReturnType != null) {
ReturnType = ec.Module.PredefinedTypes.TaskGeneric.TypeSpec.MakeGenericType (ec, new [] { ReturnType });
}
}
if (res && errors != ec.Report.Errors)
return null;
return res ? this : null;
}
public override bool ContainsEmitWithAwait ()
{
return false;
}
public void SetHasThisAccess ()
{
ExplicitBlock b = block;
do {
if (b.HasCapturedThis)
return;
b.HasCapturedThis = true;
b = b.Parent == null ? null : b.Parent.Explicit;
} while (b != null);
}
}
public class AnonymousMethodBody : AnonymousExpression
{
protected readonly ParametersCompiled parameters;
AnonymousMethodStorey storey;
AnonymousMethodMethod method;
Field am_cache;
string block_name;
TypeInferenceContext return_inference;
public AnonymousMethodBody (ParametersCompiled parameters,
ParametersBlock block, TypeSpec return_type, TypeSpec delegate_type,
Location loc)
: base (block, return_type, loc)
{
this.type = delegate_type;
this.parameters = parameters;
}
#region Properties
public override string ContainerType {
get { return "anonymous method"; }
}
//
// Method-group instance for lambdas which can be replaced with
// simple method group call
//
public MethodGroupExpr DirectMethodGroupConversion {
get; set;
}
public override bool IsIterator {
get {
return false;
}
}
public ParametersCompiled Parameters {
get {
return parameters;
}
}
public TypeInferenceContext ReturnTypeInference {
get {
return return_inference;
}
set {
return_inference = value;
}
}
public override AnonymousMethodStorey Storey {
get {
return storey;
}
}
#endregion
public override Expression CreateExpressionTree (ResolveContext ec)
{
ec.Report.Error (1945, loc, "An expression tree cannot contain an anonymous method expression");
return null;
}
bool Define (ResolveContext ec)
{
if (!Block.Resolved && Compatible (ec) == null)
return false;
if (block_name == null) {
MemberCore mc = (MemberCore) ec.MemberContext;
block_name = mc.MemberName.Basename;
}
return true;
}
//
// Creates a host for the anonymous method
//
AnonymousMethodMethod DoCreateMethodHost (EmitContext ec)
{
//
// Anonymous method body can be converted to
//
// 1, an instance method in current scope when only `this' is hoisted
// 2, a static method in current scope when neither `this' nor any variable is hoisted
// 3, an instance method in compiler generated storey when any hoisted variable exists
//
Modifiers modifiers;
TypeDefinition parent = null;
var src_block = Block.Original.Explicit;
if (src_block.HasCapturedVariable || src_block.HasCapturedThis) {
parent = storey = FindBestMethodStorey ();
if (storey == null) {
var top_block = src_block.ParametersBlock.TopBlock;
var sm = top_block.StateMachine;
if (src_block.HasCapturedThis) {
//
// Remove hoisted 'this' request when simple instance method is
// enough. No hoisted variables only 'this' and don't need to
// propagate this to value type state machine.
//
StateMachine sm_parent = null;
var pb = src_block.ParametersBlock;
do {
sm_parent = pb.StateMachine;
pb = pb.Parent == null ? null : pb.Parent.ParametersBlock;
} while (sm_parent == null && pb != null);
if (sm_parent == null) {
top_block.RemoveThisReferenceFromChildrenBlock (src_block);
} else if (sm_parent.Kind == MemberKind.Struct) {
//
// Special case where parent class is used to emit instance method
// because currect storey is of value type (async host). We cannot
// use ldftn on non-boxed instances either to share mutated state
//
parent = sm_parent.Parent.PartialContainer;
}
}
//
// For iterators we can host everything in one class
//
if (sm is IteratorStorey)
parent = storey = sm;
}
modifiers = storey != null ? Modifiers.INTERNAL : Modifiers.PRIVATE;
} else {
if (ec.CurrentAnonymousMethod != null)
parent = storey = ec.CurrentAnonymousMethod.Storey;
modifiers = Modifiers.STATIC | Modifiers.PRIVATE;
}
if (parent == null)
parent = ec.CurrentTypeDefinition.Parent.PartialContainer;
string name = CompilerGeneratedContainer.MakeName (parent != storey ? block_name : null,
"m", null, ec.Module.CounterAnonymousMethods++);
MemberName member_name;
if (storey == null && ec.CurrentTypeParameters != null) {
var hoisted_tparams = ec.CurrentTypeParameters;
var type_params = new TypeParameters (hoisted_tparams.Count);
for (int i = 0; i < hoisted_tparams.Count; ++i) {
type_params.Add (hoisted_tparams[i].CreateHoistedCopy (null));
}
member_name = new MemberName (name, type_params, Location);
} else {
member_name = new MemberName (name, Location);
}
return new AnonymousMethodMethod (parent,
this, storey, new TypeExpression (ReturnType, Location), modifiers,
member_name, parameters);
}
protected override Expression DoResolve (ResolveContext ec)
{
if (!Define (ec))
return null;
eclass = ExprClass.Value;
return this;
}
public override void Emit (EmitContext ec)
{
//
// Use same anonymous method implementation for scenarios where same
// code is used from multiple blocks, e.g. field initializers
//
if (method == null) {
//
// Delay an anonymous method definition to avoid emitting unused code
// for unreachable blocks or expression trees
//
method = DoCreateMethodHost (ec);
method.Define ();
method.PrepareEmit ();
}
bool is_static = (method.ModFlags & Modifiers.STATIC) != 0;
if (is_static && am_cache == null) {
//
// Creates a field cache to store delegate instance if it's not generic
//
if (!method.MemberName.IsGeneric) {
var parent = method.Parent.PartialContainer;
int id = parent.AnonymousMethodsCounter++;
var cache_type = storey != null && storey.Mutator != null ? storey.Mutator.Mutate (type) : type;
am_cache = new Field (parent, new TypeExpression (cache_type, loc),
Modifiers.STATIC | Modifiers.PRIVATE | Modifiers.COMPILER_GENERATED,
new MemberName (CompilerGeneratedContainer.MakeName (null, "f", "am$cache", id), loc), null);
am_cache.Define ();
parent.AddField (am_cache);
} else {
// TODO: Implement caching of generated generic static methods
//
// Idea:
//
// Some extra class is needed to capture variable generic type
// arguments. Maybe we could re-use anonymous types, with a unique
// anonymous method id, but they are quite heavy.
//
// Consider : "() => typeof(T);"
//
// We need something like
// static class Wrap<Tn, Tm, DelegateType> {
// public static DelegateType cache;
// }
//
// We then specialize local variable to capture all generic parameters
// and delegate type, e.g. "Wrap<Ta, Tb, DelegateTypeInst> cache;"
//
}
}
Label l_initialized = ec.DefineLabel ();
if (am_cache != null) {
ec.Emit (OpCodes.Ldsfld, am_cache.Spec);
ec.Emit (OpCodes.Brtrue_S, l_initialized);
}
//
// Load method delegate implementation
//
if (is_static) {
ec.EmitNull ();
} else if (storey != null) {
Expression e = storey.GetStoreyInstanceExpression (ec).Resolve (new ResolveContext (ec.MemberContext));
if (e != null) {
e.Emit (ec);
}
} else {
ec.EmitThis ();
//
// Special case for value type storey where this is not lifted but
// droped off to parent class
//
for (var b = Block.Parent; b != null; b = b.Parent) {
if (b.ParametersBlock.StateMachine != null) {
ec.Emit (OpCodes.Ldfld, b.ParametersBlock.StateMachine.HoistedThis.Field.Spec);
break;
}
}
}
var delegate_method = method.Spec;
if (storey != null && storey.MemberName.IsGeneric) {
TypeSpec t = storey.Instance.Type;
//
// Mutate anonymous method instance type if we are in nested
// hoisted generic anonymous method storey
//
if (ec.IsAnonymousStoreyMutateRequired) {
t = storey.Mutator.Mutate (t);
}
ec.Emit (OpCodes.Ldftn, TypeBuilder.GetMethod (t.GetMetaInfo (), (MethodInfo) delegate_method.GetMetaInfo ()));
} else {
if (delegate_method.IsGeneric)
delegate_method = delegate_method.MakeGenericMethod (ec.MemberContext, method.TypeParameters);
ec.Emit (OpCodes.Ldftn, delegate_method);
}
var constructor_method = Delegate.GetConstructor (type);
ec.Emit (OpCodes.Newobj, constructor_method);
if (am_cache != null) {
ec.Emit (OpCodes.Stsfld, am_cache.Spec);
ec.MarkLabel (l_initialized);
ec.Emit (OpCodes.Ldsfld, am_cache.Spec);
}
}
public override void EmitStatement (EmitContext ec)
{
throw new NotImplementedException ();
}
//
// Look for the best storey for this anonymous method
//
AnonymousMethodStorey FindBestMethodStorey ()
{
//
// Use the nearest parent block which has a storey
//
for (Block b = Block.Parent; b != null; b = b.Parent) {
AnonymousMethodStorey s = b.Explicit.AnonymousMethodStorey;
if (s != null)
return s;
}
return null;
}
public override string GetSignatureForError ()
{
return type.GetSignatureForError ();
}
}
//
// Anonymous type container
//
public class AnonymousTypeClass : CompilerGeneratedContainer
{
public const string ClassNamePrefix = "<>__AnonType";
public const string SignatureForError = "anonymous type";
readonly IList<AnonymousTypeParameter> parameters;
private AnonymousTypeClass (ModuleContainer parent, MemberName name, IList<AnonymousTypeParameter> parameters, Location loc)
: base (parent, name, parent.Evaluator != null ? Modifiers.PUBLIC : Modifiers.INTERNAL)
{
this.parameters = parameters;
}
public static AnonymousTypeClass Create (TypeContainer parent, IList<AnonymousTypeParameter> parameters, Location loc)
{
string name = ClassNamePrefix + parent.Module.CounterAnonymousTypes++;
ParametersCompiled all_parameters;
TypeParameters tparams = null;
SimpleName[] t_args;
if (parameters.Count == 0) {
all_parameters = ParametersCompiled.EmptyReadOnlyParameters;
t_args = null;
} else {
t_args = new SimpleName[parameters.Count];
tparams = new TypeParameters ();
Parameter[] ctor_params = new Parameter[parameters.Count];
for (int i = 0; i < parameters.Count; ++i) {
AnonymousTypeParameter p = parameters[i];
for (int ii = 0; ii < i; ++ii) {
if (parameters[ii].Name == p.Name) {
parent.Compiler.Report.Error (833, parameters[ii].Location,
"`{0}': An anonymous type cannot have multiple properties with the same name",
p.Name);
p = new AnonymousTypeParameter (null, "$" + i.ToString (), p.Location);
parameters[i] = p;
break;
}
}
t_args[i] = new SimpleName ("<" + p.Name + ">__T", p.Location);
tparams.Add (new TypeParameter (i, new MemberName (t_args[i].Name, p.Location), null, null, Variance.None));
ctor_params[i] = new Parameter (t_args[i], p.Name, Parameter.Modifier.NONE, null, p.Location);
}
all_parameters = new ParametersCompiled (ctor_params);
}
//
// Create generic anonymous type host with generic arguments
// named upon properties names
//
AnonymousTypeClass a_type = new AnonymousTypeClass (parent.Module, new MemberName (name, tparams, loc), parameters, loc);
Constructor c = new Constructor (a_type, name, Modifiers.PUBLIC | Modifiers.DEBUGGER_HIDDEN,
null, all_parameters, loc);
c.Block = new ToplevelBlock (parent.Module.Compiler, c.ParameterInfo, loc);
//
// Create fields and constructor body with field initialization
//
bool error = false;
for (int i = 0; i < parameters.Count; ++i) {
AnonymousTypeParameter p = parameters [i];
Field f = new Field (a_type, t_args [i], Modifiers.PRIVATE | Modifiers.READONLY | Modifiers.DEBUGGER_HIDDEN,
new MemberName ("<" + p.Name + ">", p.Location), null);
if (!a_type.AddField (f)) {
error = true;
continue;
}
c.Block.AddStatement (new StatementExpression (
new SimpleAssign (new MemberAccess (new This (p.Location), f.Name),
c.Block.GetParameterReference (i, p.Location))));
ToplevelBlock get_block = new ToplevelBlock (parent.Module.Compiler, p.Location);
get_block.AddStatement (new Return (
new MemberAccess (new This (p.Location), f.Name), p.Location));
Property prop = new Property (a_type, t_args [i], Modifiers.PUBLIC,
new MemberName (p.Name, p.Location), null);
prop.Get = new Property.GetMethod (prop, 0, null, p.Location);
prop.Get.Block = get_block;
a_type.AddMember (prop);
}
if (error)
return null;
a_type.AddConstructor (c);
return a_type;
}
protected override bool DoDefineMembers ()
{
if (!base.DoDefineMembers ())
return false;
Location loc = Location;
var equals_parameters = ParametersCompiled.CreateFullyResolved (
new Parameter (new TypeExpression (Compiler.BuiltinTypes.Object, loc), "obj", 0, null, loc), Compiler.BuiltinTypes.Object);
Method equals = new Method (this, new TypeExpression (Compiler.BuiltinTypes.Bool, loc),
Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("Equals", loc),
equals_parameters, null);
equals_parameters[0].Resolve (equals, 0);
Method tostring = new Method (this, new TypeExpression (Compiler.BuiltinTypes.String, loc),
Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN, new MemberName ("ToString", loc),
Mono.CSharp.ParametersCompiled.EmptyReadOnlyParameters, null);
ToplevelBlock equals_block = new ToplevelBlock (Compiler, equals.ParameterInfo, loc);
TypeExpr current_type;
if (CurrentTypeParameters != null) {
var targs = new TypeArguments ();
for (int i = 0; i < CurrentTypeParameters.Count; ++i) {
targs.Add (new TypeParameterExpr (CurrentTypeParameters[i], Location));
}
current_type = new GenericTypeExpr (Definition, targs, loc);
} else {
current_type = new TypeExpression (Definition, loc);
}
var li_other = LocalVariable.CreateCompilerGenerated (CurrentType, equals_block, loc);
equals_block.AddStatement (new BlockVariable (new TypeExpression (li_other.Type, loc), li_other));
var other_variable = new LocalVariableReference (li_other, loc);
MemberAccess system_collections_generic = new MemberAccess (new MemberAccess (
new QualifiedAliasMember ("global", "System", loc), "Collections", loc), "Generic", loc);
Expression rs_equals = null;
Expression string_concat = new StringConstant (Compiler.BuiltinTypes, "{", loc);
Expression rs_hashcode = new IntConstant (Compiler.BuiltinTypes, -2128831035, loc);
for (int i = 0; i < parameters.Count; ++i) {
var p = parameters [i];
var f = (Field) Members [i * 2];
MemberAccess equality_comparer = new MemberAccess (new MemberAccess (
system_collections_generic, "EqualityComparer",
new TypeArguments (new SimpleName (CurrentTypeParameters [i].Name, loc)), loc),
"Default", loc);
Arguments arguments_equal = new Arguments (2);
arguments_equal.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
arguments_equal.Add (new Argument (new MemberAccess (other_variable, f.Name)));
Expression field_equal = new Invocation (new MemberAccess (equality_comparer,
"Equals", loc), arguments_equal);
Arguments arguments_hashcode = new Arguments (1);
arguments_hashcode.Add (new Argument (new MemberAccess (new This (f.Location), f.Name)));
Expression field_hashcode = new Invocation (new MemberAccess (equality_comparer,
"GetHashCode", loc), arguments_hashcode);
IntConstant FNV_prime = new IntConstant (Compiler.BuiltinTypes, 16777619, loc);
rs_hashcode = new Binary (Binary.Operator.Multiply,
new Binary (Binary.Operator.ExclusiveOr, rs_hashcode, field_hashcode),
FNV_prime);
Expression field_to_string = new Conditional (new BooleanExpression (new Binary (Binary.Operator.Inequality,
new MemberAccess (new This (f.Location), f.Name), new NullLiteral (loc))),
new Invocation (new MemberAccess (
new MemberAccess (new This (f.Location), f.Name), "ToString"), null),
new StringConstant (Compiler.BuiltinTypes, string.Empty, loc), loc);
if (rs_equals == null) {
rs_equals = field_equal;
string_concat = new Binary (Binary.Operator.Addition,
string_concat,
new Binary (Binary.Operator.Addition,
new StringConstant (Compiler.BuiltinTypes, " " + p.Name + " = ", loc),
field_to_string));
continue;
}
//
// Implementation of ToString () body using string concatenation
//
string_concat = new Binary (Binary.Operator.Addition,
new Binary (Binary.Operator.Addition,
string_concat,
new StringConstant (Compiler.BuiltinTypes, ", " + p.Name + " = ", loc)),
field_to_string);
rs_equals = new Binary (Binary.Operator.LogicalAnd, rs_equals, field_equal);
}
string_concat = new Binary (Binary.Operator.Addition,
string_concat,
new StringConstant (Compiler.BuiltinTypes, " }", loc));
//
// Equals (object obj) override
//
var other_variable_assign = new TemporaryVariableReference (li_other, loc);
equals_block.AddStatement (new StatementExpression (
new SimpleAssign (other_variable_assign,
new As (equals_block.GetParameterReference (0, loc),
current_type, loc), loc)));
Expression equals_test = new Binary (Binary.Operator.Inequality, other_variable, new NullLiteral (loc));
if (rs_equals != null)
equals_test = new Binary (Binary.Operator.LogicalAnd, equals_test, rs_equals);
equals_block.AddStatement (new Return (equals_test, loc));
equals.Block = equals_block;
equals.Define ();
equals.PrepareEmit ();
Members.Add (equals);
//
// GetHashCode () override
//
Method hashcode = new Method (this, new TypeExpression (Compiler.BuiltinTypes.Int, loc),
Modifiers.PUBLIC | Modifiers.OVERRIDE | Modifiers.DEBUGGER_HIDDEN,
new MemberName ("GetHashCode", loc),
Mono.CSharp.ParametersCompiled.EmptyReadOnlyParameters, null);
//
// Modified FNV with good avalanche behavior and uniform
// distribution with larger hash sizes.
//
// const int FNV_prime = 16777619;
// int hash = (int) 2166136261;
// foreach (int d in data)
// hash = (hash ^ d) * FNV_prime;
// hash += hash << 13;
// hash ^= hash >> 7;
// hash += hash << 3;
// hash ^= hash >> 17;
// hash += hash << 5;
ToplevelBlock hashcode_top = new ToplevelBlock (Compiler, loc);
Block hashcode_block = new Block (hashcode_top, loc, loc);
hashcode_top.AddStatement (new Unchecked (hashcode_block, loc));
var li_hash = LocalVariable.CreateCompilerGenerated (Compiler.BuiltinTypes.Int, hashcode_top, loc);
hashcode_block.AddStatement (new BlockVariable (new TypeExpression (li_hash.Type, loc), li_hash));
LocalVariableReference hash_variable_assign = new LocalVariableReference (li_hash, loc);
hashcode_block.AddStatement (new StatementExpression (
new SimpleAssign (hash_variable_assign, rs_hashcode)));
var hash_variable = new LocalVariableReference (li_hash, loc);
hashcode_block.AddStatement (new StatementExpression (
new CompoundAssign (Binary.Operator.Addition, hash_variable,
new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 13, loc)))));
hashcode_block.AddStatement (new StatementExpression (
new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 7, loc)))));
hashcode_block.AddStatement (new StatementExpression (
new CompoundAssign (Binary.Operator.Addition, hash_variable,
new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 3, loc)))));
hashcode_block.AddStatement (new StatementExpression (
new CompoundAssign (Binary.Operator.ExclusiveOr, hash_variable,
new Binary (Binary.Operator.RightShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 17, loc)))));
hashcode_block.AddStatement (new StatementExpression (
new CompoundAssign (Binary.Operator.Addition, hash_variable,
new Binary (Binary.Operator.LeftShift, hash_variable, new IntConstant (Compiler.BuiltinTypes, 5, loc)))));
hashcode_block.AddStatement (new Return (hash_variable, loc));
hashcode.Block = hashcode_top;
hashcode.Define ();
hashcode.PrepareEmit ();
Members.Add (hashcode);
//
// ToString () override
//
ToplevelBlock tostring_block = new ToplevelBlock (Compiler, loc);
tostring_block.AddStatement (new Return (string_concat, loc));
tostring.Block = tostring_block;
tostring.Define ();
tostring.PrepareEmit ();
Members.Add (tostring);
return true;
}
public override string GetSignatureForError ()
{
return SignatureForError;
}
public override CompilationSourceFile GetCompilationSourceFile ()
{
return null;
}
public IList<AnonymousTypeParameter> Parameters {
get {
return parameters;
}
}
}
}
|