summaryrefslogtreecommitdiff
path: root/mcs/mcs/import.cs
blob: 6529c878fd2c3b687484e9aa425db0a724d8da89 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
//
// import.cs: System.Reflection conversions
//
// Authors: Marek Safar (marek.safar@gmail.com)
//
// Dual licensed under the terms of the MIT X11 or GNU GPL
//
// Copyright 2009-2011 Novell, Inc
// Copyright 2011-2012 Xamarin, Inc (http://www.xamarin.com)
//

using System;
using System.Runtime.CompilerServices;
using System.Linq;
using System.Collections.Generic;

#if STATIC
using MetaType = IKVM.Reflection.Type;
using IKVM.Reflection;
using IKVM.Reflection.Emit;
#else
using MetaType = System.Type;
using System.Reflection;
using System.Reflection.Emit;
#endif

namespace Mono.CSharp
{
	public abstract class MetadataImporter
	{
		//
		// Dynamic types reader with additional logic to reconstruct a dynamic
		// type using DynamicAttribute values
		//
		protected struct DynamicTypeReader
		{
			static readonly bool[] single_attribute = { true };

			public int Position;
			bool[] flags;

			// There is no common type for CustomAttributeData and we cannot
			// use ICustomAttributeProvider
			object provider;

			//
			// A member provider which can be used to get CustomAttributeData
			//
			public DynamicTypeReader (object provider)
			{
				Position = 0;
				flags = null;
				this.provider = provider;
			}

			//
			// Returns true when object at local position has dynamic attribute flag
			//
			public bool IsDynamicObject ()
			{
				if (provider != null)
					ReadAttribute ();

				return flags != null && Position < flags.Length && flags[Position];
			}

			//
			// Returns true when DynamicAttribute exists
			//
			public bool HasDynamicAttribute ()
			{
				if (provider != null)
					ReadAttribute ();

				return flags != null;
			}

			void ReadAttribute ()
			{
				IList<CustomAttributeData> cad;
				if (provider is MemberInfo) {
					cad = CustomAttributeData.GetCustomAttributes ((MemberInfo) provider);
				} else if (provider is ParameterInfo) {
					cad = CustomAttributeData.GetCustomAttributes ((ParameterInfo) provider);
				} else {
					provider = null;
					return;
				}

				if (cad.Count > 0) {
					foreach (var ca in cad) {
						var dt = ca.Constructor.DeclaringType;
						if (dt.Name != "DynamicAttribute" || dt.Namespace != CompilerServicesNamespace)
							continue;

						if (ca.ConstructorArguments.Count == 0) {
							flags = single_attribute;
							break;
						}

						var arg_type = ca.ConstructorArguments[0].ArgumentType;

						if (arg_type.IsArray && MetaType.GetTypeCode (arg_type.GetElementType ()) == TypeCode.Boolean) {
							var carg = (IList<CustomAttributeTypedArgument>) ca.ConstructorArguments[0].Value;
							flags = new bool[carg.Count];
							for (int i = 0; i < flags.Length; ++i) {
								if (MetaType.GetTypeCode (carg[i].ArgumentType) == TypeCode.Boolean)
									flags[i] = (bool) carg[i].Value;
							}

							break;
						}
					}
				}

				provider = null;
			}
		}

		protected readonly Dictionary<MetaType, TypeSpec> import_cache;
		protected readonly Dictionary<MetaType, TypeSpec> compiled_types;
		protected readonly Dictionary<Assembly, IAssemblyDefinition> assembly_2_definition;
		protected readonly ModuleContainer module;

		public static readonly string CompilerServicesNamespace = "System.Runtime.CompilerServices";

		protected MetadataImporter (ModuleContainer module)
		{
			this.module = module;

			import_cache = new Dictionary<MetaType, TypeSpec> (1024, ReferenceEquality<MetaType>.Default);
			compiled_types = new Dictionary<MetaType, TypeSpec> (40, ReferenceEquality<MetaType>.Default);
			assembly_2_definition = new Dictionary<Assembly, IAssemblyDefinition> (ReferenceEquality<Assembly>.Default);
			IgnorePrivateMembers = true;
		}

		#region Properties

		public ICollection<IAssemblyDefinition> Assemblies {
			get {
				return assembly_2_definition.Values;
			}
		}

		public bool IgnorePrivateMembers { get; set; }

		#endregion

		public abstract void AddCompiledType (TypeBuilder builder, TypeSpec spec);
		protected abstract MemberKind DetermineKindFromBaseType (MetaType baseType);
		protected abstract bool HasVolatileModifier (MetaType[] modifiers);

		public FieldSpec CreateField (FieldInfo fi, TypeSpec declaringType)
		{
			Modifiers mod;
			var fa = fi.Attributes;
			switch (fa & FieldAttributes.FieldAccessMask) {
				case FieldAttributes.Public:
					mod = Modifiers.PUBLIC;
					break;
				case FieldAttributes.Assembly:
					mod = Modifiers.INTERNAL;
					break;
				case FieldAttributes.Family:
					mod = Modifiers.PROTECTED;
					break;
				case FieldAttributes.FamORAssem:
					mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
					break;
				default:
					// Ignore private fields (even for error reporting) to not require extra dependencies
					if ((IgnorePrivateMembers && !declaringType.IsStruct) ||
						HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "CompilerGeneratedAttribute", CompilerServicesNamespace))
						return null;

					mod = Modifiers.PRIVATE;
					break;
			}

			TypeSpec field_type;

			try {
				field_type = ImportType (fi.FieldType, new DynamicTypeReader (fi));
			} catch (Exception e) {
				// TODO: I should construct fake TypeSpec based on TypeRef signature
				// but there is no way to do it with System.Reflection
				throw new InternalErrorException (e, "Cannot import field `{0}.{1}' referenced in assembly `{2}'",
					declaringType.GetSignatureForError (), fi.Name, declaringType.MemberDefinition.DeclaringAssembly);
			}

			var definition = new ImportedMemberDefinition (fi, field_type, this);

			if ((fa & FieldAttributes.Literal) != 0) {
				Constant c = field_type.Kind == MemberKind.MissingType ?
					new NullConstant (InternalType.ErrorType, Location.Null) :
					Constant.CreateConstantFromValue (field_type, fi.GetRawConstantValue (), Location.Null);
				return new ConstSpec (declaringType, definition, field_type, fi, mod, c);
			}

			if ((fa & FieldAttributes.InitOnly) != 0) {
				if (field_type.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
					var dc = ReadDecimalConstant (CustomAttributeData.GetCustomAttributes (fi));
					if (dc != null)
						return new ConstSpec (declaringType, definition, field_type, fi, mod, dc);
				}

				mod |= Modifiers.READONLY;
			} else {
				var req_mod = fi.GetRequiredCustomModifiers ();
				if (req_mod.Length > 0 && HasVolatileModifier (req_mod))
					mod |= Modifiers.VOLATILE;
			}

			if ((fa & FieldAttributes.Static) != 0) {
				mod |= Modifiers.STATIC;
			} else {
				// Fixed buffers cannot be static
				if (declaringType.IsStruct && field_type.IsStruct && field_type.IsNested &&
					HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "FixedBufferAttribute", CompilerServicesNamespace)) {

					// TODO: Sanity check on field_type (only few types are allowed)
					var element_field = CreateField (fi.FieldType.GetField (FixedField.FixedElementName), declaringType);
					return new FixedFieldSpec (module, declaringType, definition, fi, element_field, mod);
				}
			}

			return new FieldSpec (declaringType, definition, field_type, fi, mod);
		}

		public EventSpec CreateEvent (EventInfo ei, TypeSpec declaringType, MethodSpec add, MethodSpec remove)
		{
			add.IsAccessor = true;
			remove.IsAccessor = true;

			if (add.Modifiers != remove.Modifiers)
				throw new NotImplementedException ("Different accessor modifiers " + ei.Name);

			var event_type = ImportType (ei.EventHandlerType, new DynamicTypeReader (ei));
			var definition = new ImportedMemberDefinition (ei, event_type,  this);
			return new EventSpec (declaringType, definition, event_type, add.Modifiers, add, remove);
		}

		TypeParameterSpec[] CreateGenericParameters (MetaType type, TypeSpec declaringType)
		{
			var tparams = type.GetGenericArguments ();

			int parent_owned_count;
			if (type.IsNested) {
				parent_owned_count = type.DeclaringType.GetGenericArguments ().Length;

				//
				// System.Reflection duplicates parent type parameters for each
				// nested type with slightly modified properties (eg. different owner)
				// This just makes things more complicated (think of cloned constraints)
				// therefore we remap any nested type owned by parent using `type_cache'
				// to the single TypeParameterSpec
				//
				if (declaringType != null && parent_owned_count > 0) {
					int read_count = 0;
					while (read_count != parent_owned_count) {
						var tparams_count = declaringType.Arity;
						if (tparams_count != 0) {
							var parent_tp = declaringType.MemberDefinition.TypeParameters;
							read_count += tparams_count;
							for (int i = 0; i < tparams_count; i++) {
								import_cache.Add (tparams[parent_owned_count - read_count + i], parent_tp[i]);
							}
						}

						declaringType = declaringType.DeclaringType;
					}
				}			
			} else {
				parent_owned_count = 0;
			}

			if (tparams.Length - parent_owned_count == 0)
				return null;

			return CreateGenericParameters (parent_owned_count, tparams);
		}

		TypeParameterSpec[] CreateGenericParameters (int first, MetaType[] tparams)
		{
			var tspec = new TypeParameterSpec[tparams.Length - first];
			for (int pos = first; pos < tparams.Length; ++pos) {
				var type = tparams[pos];
				int index = pos - first;

				tspec[index] = (TypeParameterSpec) CreateType (type, new DynamicTypeReader (), false);
			}

			return tspec;
		}

		TypeSpec[] CreateGenericArguments (int first, MetaType[] tparams, DynamicTypeReader dtype)
		{
			++dtype.Position;

			var tspec = new TypeSpec [tparams.Length - first];
			for (int pos = first; pos < tparams.Length; ++pos) {
				var type = tparams[pos];
				int index = pos - first;

				TypeSpec spec;
				if (type.HasElementType) {
					var element = type.GetElementType ();
					++dtype.Position;
					spec = ImportType (element, dtype);

					if (!type.IsArray) {
						throw new NotImplementedException ("Unknown element type " + type.ToString ());
					}

					spec = ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
				} else {
					spec = CreateType (type, dtype, true);

					//
					// We treat nested generic types as inflated internally where
					// reflection uses type definition
					//
					// class A<T> {
					//    IFoo<A<T>> foo;	// A<T> is definition in this case
					// }
					//
					if (!IsMissingType (type) && type.IsGenericTypeDefinition) {
						var start_pos = spec.DeclaringType == null ? 0 : spec.DeclaringType.MemberDefinition.TypeParametersCount;
						var targs = CreateGenericArguments (start_pos, type.GetGenericArguments (), dtype);
						spec = spec.MakeGenericType (module, targs);
					}
				}

				++dtype.Position;
				tspec[index] = spec;
			}

			return tspec;
		}

		public MethodSpec CreateMethod (MethodBase mb, TypeSpec declaringType)
		{
			Modifiers mod = ReadMethodModifiers (mb, declaringType);
			TypeParameterSpec[] tparams;

			var parameters = CreateParameters (declaringType, mb.GetParameters (), mb);

			if (mb.IsGenericMethod) {
				if (!mb.IsGenericMethodDefinition)
					throw new NotSupportedException ("assert");

				tparams = CreateGenericParameters (0, mb.GetGenericArguments ());
			} else {
				tparams = null;
			}

			MemberKind kind;
			TypeSpec returnType;
			if (mb.MemberType == MemberTypes.Constructor) {
				kind = MemberKind.Constructor;
				returnType = module.Compiler.BuiltinTypes.Void;
			} else {
				//
				// Detect operators and destructors
				//
				string name = mb.Name;
				kind = MemberKind.Method;
				if (tparams == null && !mb.DeclaringType.IsInterface && name.Length > 6) {
					if ((mod & (Modifiers.STATIC | Modifiers.PUBLIC)) == (Modifiers.STATIC | Modifiers.PUBLIC)) {
						if (name[2] == '_' && name[1] == 'p' && name[0] == 'o') {
							var op_type = Operator.GetType (name);
							if (op_type.HasValue && parameters.Count > 0 && parameters.Count < 3) {
								kind = MemberKind.Operator;
							}
						}
					} else if (parameters.IsEmpty && name == Destructor.MetadataName) {
						kind = MemberKind.Destructor;
						if (declaringType.BuiltinType == BuiltinTypeSpec.Type.Object) {
							mod &= ~Modifiers.OVERRIDE;
							mod |= Modifiers.VIRTUAL;
						}
					}
				}

				var mi = (MethodInfo) mb;
				returnType = ImportType (mi.ReturnType, new DynamicTypeReader (mi.ReturnParameter));

				// Cannot set to OVERRIDE without full hierarchy checks
				// this flag indicates that the method could be override
				// but further validation is needed
				if ((mod & Modifiers.OVERRIDE) != 0) {
					bool is_real_override = false;
					if (kind == MemberKind.Method && declaringType.BaseType != null) {
						var btype = declaringType.BaseType;
						if (IsOverrideMethodBaseTypeAccessible (btype)) {
							var filter = MemberFilter.Method (name, tparams != null ? tparams.Length : 0, parameters, null);
							var candidate = MemberCache.FindMember (btype, filter, BindingRestriction.None);

							//
							// For imported class method do additional validation to be sure that metadata
							// override flag was correct
							// 
							// Difference between protected internal and protected is ok
							//
							const Modifiers conflict_mask = Modifiers.AccessibilityMask & ~Modifiers.INTERNAL;
							if (candidate != null && (candidate.Modifiers & conflict_mask) == (mod & conflict_mask) && !candidate.IsStatic) {
								is_real_override = true;
							}
						}
					}

					if (!is_real_override) {
						mod &= ~Modifiers.OVERRIDE;
						if ((mod & Modifiers.SEALED) != 0)
							mod &= ~Modifiers.SEALED;
						else
							mod |= Modifiers.VIRTUAL;
					}
				}
			}

			IMethodDefinition definition;
			if (tparams != null) {
				var gmd = new ImportedGenericMethodDefinition ((MethodInfo) mb, returnType, parameters, tparams, this);
				foreach (var tp in gmd.TypeParameters) {
					ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
				}

				definition = gmd;
			} else {
				definition = new ImportedMethodDefinition (mb, returnType, parameters, this);
			}

			MethodSpec ms = new MethodSpec (kind, declaringType, definition, returnType, parameters, mod);
			if (tparams != null)
				ms.IsGeneric = true;

			return ms;
		}

		bool IsOverrideMethodBaseTypeAccessible (TypeSpec baseType)
		{
			switch (baseType.Modifiers & Modifiers.AccessibilityMask) {
			case Modifiers.PUBLIC:
				return true;
			case Modifiers.INTERNAL:
				//
				// Check whether imported method in base type is accessible from compiled
				// context
				//
				return baseType.MemberDefinition.IsInternalAsPublic (module.DeclaringAssembly);
			case Modifiers.PRIVATE:
				return false;
			default:
				// protected
				// protected internal
				// 
				// Method accessibility checks will be done later based on context
				// where the method is called (CS0122 error will be reported for inaccessible)
				//
				return true;
			}
		}

		//
		// Imports System.Reflection parameters
		//
		AParametersCollection CreateParameters (TypeSpec parent, ParameterInfo[] pi, MethodBase method)
		{
			int varargs = method != null && (method.CallingConvention & CallingConventions.VarArgs) != 0 ? 1 : 0;

			if (pi.Length == 0 && varargs == 0)
				return ParametersCompiled.EmptyReadOnlyParameters;

			TypeSpec[] types = new TypeSpec[pi.Length + varargs];
			IParameterData[] par = new IParameterData[pi.Length + varargs];
			bool is_params = false;
			for (int i = 0; i < pi.Length; i++) {
				ParameterInfo p = pi[i];
				Parameter.Modifier mod = 0;
				Expression default_value = null;
				if (p.ParameterType.IsByRef) {
					if ((p.Attributes & (ParameterAttributes.Out | ParameterAttributes.In)) == ParameterAttributes.Out)
						mod = Parameter.Modifier.OUT;
					else
						mod = Parameter.Modifier.REF;

					//
					// Strip reference wrapping
					//
					var el = p.ParameterType.GetElementType ();
					types[i] = ImportType (el, new DynamicTypeReader (p));	// TODO: 1-based positio to be csc compatible
				} else if (i == 0 && method.IsStatic && (parent.Modifiers & Modifiers.METHOD_EXTENSION) != 0 &&
					HasAttribute (CustomAttributeData.GetCustomAttributes (method), "ExtensionAttribute", CompilerServicesNamespace)) {
					mod = Parameter.Modifier.This;
					types[i] = ImportType (p.ParameterType);
				} else {
					types[i] = ImportType (p.ParameterType, new DynamicTypeReader (p));

					if (i >= pi.Length - 2 && types[i] is ArrayContainer) {
						if (HasAttribute (CustomAttributeData.GetCustomAttributes (p), "ParamArrayAttribute", "System")) {
							mod = Parameter.Modifier.PARAMS;
							is_params = true;
						}
					}

					if (!is_params && p.IsOptional) {
						object value = p.RawDefaultValue;
						var ptype = types[i];
						if ((p.Attributes & ParameterAttributes.HasDefault) != 0 && ptype.Kind != MemberKind.TypeParameter && (value != null || TypeSpec.IsReferenceType (ptype))) {
							if (value == null) {
								default_value = Constant.CreateConstantFromValue (ptype, null, Location.Null);
							} else {
								default_value = ImportParameterConstant (value);

								if (ptype.IsEnum) {
									default_value = new EnumConstant ((Constant) default_value, ptype);
								}
							}

							var attrs = CustomAttributeData.GetCustomAttributes (p);
							for (int ii = 0; ii < attrs.Count; ++ii) {
								var attr = attrs[ii];
								var dt = attr.Constructor.DeclaringType;
								if (dt.Namespace != CompilerServicesNamespace)
									continue;

								if (dt.Name == "CallerLineNumberAttribute" && (ptype.BuiltinType == BuiltinTypeSpec.Type.Int || Convert.ImplicitNumericConversionExists (module.Compiler.BuiltinTypes.Int, ptype)))
									mod |= Parameter.Modifier.CallerLineNumber;
								else if (dt.Name == "CallerFilePathAttribute" && Convert.ImplicitReferenceConversionExists (module.Compiler.BuiltinTypes.String, ptype))
									mod |= Parameter.Modifier.CallerFilePath;
								else if (dt.Name == "CallerMemberNameAttribute" && Convert.ImplicitReferenceConversionExists (module.Compiler.BuiltinTypes.String, ptype))
									mod |= Parameter.Modifier.CallerMemberName;
							}
						} else if (value == Missing.Value) {
							default_value = EmptyExpression.MissingValue;
						} else if (value == null) {
							default_value = new DefaultValueExpression (new TypeExpression (ptype, Location.Null), Location.Null);
						} else if (ptype.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
							default_value = ImportParameterConstant (value);
						}
					}
				}

				par[i] = new ParameterData (p.Name, mod, default_value);
			}

			if (varargs != 0) {
				par[par.Length - 1] = new ArglistParameter (Location.Null);
				types[types.Length - 1] = InternalType.Arglist;
			}

			return method != null ?
				new ParametersImported (par, types, varargs != 0, is_params) :
				new ParametersImported (par, types, is_params);
		}

		//
		// Returns null when the property is not valid C# property
		//
		public PropertySpec CreateProperty (PropertyInfo pi, TypeSpec declaringType, MethodSpec get, MethodSpec set)
		{
			Modifiers mod = 0;
			AParametersCollection param = null;
			TypeSpec type = null;
			if (get != null) {
				mod = get.Modifiers;
				param = get.Parameters;
				type = get.ReturnType;
			}

			bool is_valid_property = true;
			if (set != null) {
				if (set.ReturnType.Kind != MemberKind.Void)
					is_valid_property = false;

				var set_param_count = set.Parameters.Count - 1;

				if (set_param_count < 0) {
					set_param_count = 0;
					is_valid_property = false;
				}

				var set_type = set.Parameters.Types[set_param_count];

				if (mod == 0) {
					AParametersCollection set_based_param;

					if (set_param_count == 0) {
						set_based_param = ParametersCompiled.EmptyReadOnlyParameters;
					} else {
						//
						// Create indexer parameters based on setter method parameters (the last parameter has to be removed)
						//
						var data = new IParameterData[set_param_count];
						var types = new TypeSpec[set_param_count];
						Array.Copy (set.Parameters.FixedParameters, data, set_param_count);
						Array.Copy (set.Parameters.Types, types, set_param_count);
						set_based_param = new ParametersImported (data, types, set.Parameters.HasParams);
					}

					mod = set.Modifiers;
					param = set_based_param;
					type = set_type;
				} else {
					if (set_param_count != get.Parameters.Count)
						is_valid_property = false;

					if (get.ReturnType != set_type)
						is_valid_property = false;

					// Possible custom accessor modifiers
					if ((mod & Modifiers.AccessibilityMask) != (set.Modifiers & Modifiers.AccessibilityMask)) {
						var get_acc = mod & Modifiers.AccessibilityMask;
						if (get_acc != Modifiers.PUBLIC) {
							var set_acc = set.Modifiers & Modifiers.AccessibilityMask;
							// If the accessor modifiers are not same, do extra restriction checks
							if (get_acc != set_acc) {
								var get_restr = ModifiersExtensions.IsRestrictedModifier (get_acc, set_acc);
								var set_restr = ModifiersExtensions.IsRestrictedModifier (set_acc, get_acc);
								if (get_restr && set_restr) {
									is_valid_property = false; // Neither is more restrictive
								}

								if (get_restr) {
									mod &= ~Modifiers.AccessibilityMask;
									mod |= set_acc;
								}
							}
						}
					}
				}
			}

			PropertySpec spec = null;
			if (!param.IsEmpty) {
				if (is_valid_property) {
					var index_name = declaringType.MemberDefinition.GetAttributeDefaultMember ();
					if (index_name == null) {
						is_valid_property = false;
					} else {
						if (get != null) {
							if (get.IsStatic)
								is_valid_property = false;
							if (get.Name.IndexOf (index_name, StringComparison.Ordinal) != 4)
								is_valid_property = false;
						}
						if (set != null) {
							if (set.IsStatic)
								is_valid_property = false;
							if (set.Name.IndexOf (index_name, StringComparison.Ordinal) != 4)
								is_valid_property = false;
						}
					}

					if (is_valid_property) {
						spec = new IndexerSpec (declaringType, new ImportedParameterMemberDefinition (pi, type, param, this), type, param, pi, mod);
					} else if (declaringType.MemberDefinition.IsComImport && param.FixedParameters[0].HasDefaultValue) {
						//
						// Enables support for properties with parameters (must have default value) of COM-imported types
						//
						is_valid_property = true;

						for (int i = 0; i < param.FixedParameters.Length; ++i) {
							if (!param.FixedParameters[i].HasDefaultValue) {
								is_valid_property = false;
								break;
							}
						}
					}
				}
			}

			if (spec == null)
				spec = new PropertySpec (MemberKind.Property, declaringType, new ImportedMemberDefinition (pi, type, this), type, pi, mod);

			if (!is_valid_property) {
				spec.IsNotCSharpCompatible = true;
				return spec;
			}

			if (set != null)
				spec.Set = set;
			if (get != null)
				spec.Get = get;

			return spec;
		}

		public TypeSpec CreateType (MetaType type)
		{
			return CreateType (type, new DynamicTypeReader (), true);
		}

		public TypeSpec CreateNestedType (MetaType type, TypeSpec declaringType)
		{
			return CreateType (type, declaringType, new DynamicTypeReader (type), false);
		}

		TypeSpec CreateType (MetaType type, DynamicTypeReader dtype, bool canImportBaseType)
		{
			TypeSpec declaring_type;
			if (type.IsNested && !type.IsGenericParameter)
				declaring_type = CreateType (type.DeclaringType, new DynamicTypeReader (type.DeclaringType), true);
			else
				declaring_type = null;

			return CreateType (type, declaring_type, dtype, canImportBaseType);
		}

		protected TypeSpec CreateType (MetaType type, TypeSpec declaringType, DynamicTypeReader dtype, bool canImportBaseType)
		{
			TypeSpec spec;
			if (import_cache.TryGetValue (type, out spec)) {
				if (spec.BuiltinType == BuiltinTypeSpec.Type.Object) {
					if (dtype.IsDynamicObject ())
						return module.Compiler.BuiltinTypes.Dynamic;

					return spec;
				}

				if (!spec.IsGeneric || type.IsGenericTypeDefinition)
					return spec;

				if (!dtype.HasDynamicAttribute ())
					return spec;

				// We've found same object in the cache but this one has a dynamic custom attribute
				// and it's most likely dynamic version of same type IFoo<object> agains IFoo<dynamic>
				// Do type resolve process again in that case

				// TODO: Handle cases where they still unify
			}

			if (IsMissingType (type)) {
				spec = new TypeSpec (MemberKind.MissingType, declaringType, new ImportedTypeDefinition (type, this), type, Modifiers.PUBLIC);
				spec.MemberCache = MemberCache.Empty;
				import_cache.Add (type, spec);
				return spec;
			}

			if (type.IsGenericType && !type.IsGenericTypeDefinition) {
				var type_def = type.GetGenericTypeDefinition ();

				// Generic type definition can also be forwarded
				if (compiled_types.TryGetValue (type_def, out spec))
					return spec;

				var targs = CreateGenericArguments (0, type.GetGenericArguments (), dtype);
				if (declaringType == null) {
					// Simple case, no nesting
					spec = CreateType (type_def, null, new DynamicTypeReader (), canImportBaseType);
					spec = spec.MakeGenericType (module, targs);
				} else {
					//
					// Nested type case, converting .NET types like
					// A`1.B`1.C`1<int, long, string> to typespec like
					// A<int>.B<long>.C<string>
					//
					var nested_hierarchy = new List<TypeSpec> ();
					while (declaringType.IsNested) {
						nested_hierarchy.Add (declaringType);
						declaringType = declaringType.DeclaringType;
					}

					int targs_pos = 0;
					if (declaringType.Arity > 0) {
						spec = declaringType.MakeGenericType (module, targs.Skip (targs_pos).Take (declaringType.Arity).ToArray ());
						targs_pos = spec.Arity;
					} else {
						spec = declaringType;
					}

					for (int i = nested_hierarchy.Count; i != 0; --i) {
						var t = nested_hierarchy [i - 1];
						if (t.Kind == MemberKind.MissingType)
							spec = t;
						else
							spec = MemberCache.FindNestedType (spec, t.Name, t.Arity);

						if (t.Arity > 0) {
							spec = spec.MakeGenericType (module, targs.Skip (targs_pos).Take (spec.Arity).ToArray ());
							targs_pos += t.Arity;
						}
					}

					if (spec.Kind == MemberKind.MissingType) {
						spec = new TypeSpec (MemberKind.MissingType, spec, new ImportedTypeDefinition (type_def, this), type_def, Modifiers.PUBLIC);
						spec.MemberCache = MemberCache.Empty;
					} else {
						if ((type_def.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && IgnorePrivateMembers)
							return null;

						string name = type.Name;
						int index = name.IndexOf ('`');
						if (index > 0)
							name = name.Substring (0, index);

						spec = MemberCache.FindNestedType (spec, name, targs.Length - targs_pos);

						if (spec.Arity > 0) {
							spec = spec.MakeGenericType (module, targs.Skip (targs_pos).ToArray ());
						}
					}
				}

				// Don't add generic type with dynamic arguments, they can interfere with same type
				// using object type arguments
				if (!spec.HasDynamicElement) {

					// Add to reading cache to speed up reading
					if (!import_cache.ContainsKey (type))
						import_cache.Add (type, spec);
				}

				return spec;
			}

			Modifiers mod;
			MemberKind kind;

			var ma = type.Attributes;
			switch (ma & TypeAttributes.VisibilityMask) {
			case TypeAttributes.Public:
			case TypeAttributes.NestedPublic:
				mod = Modifiers.PUBLIC;
				break;
			case TypeAttributes.NestedPrivate:
				mod = Modifiers.PRIVATE;
				break;
			case TypeAttributes.NestedFamily:
				mod = Modifiers.PROTECTED;
				break;
			case TypeAttributes.NestedFamORAssem:
				mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
				break;
			default:
				mod = Modifiers.INTERNAL;
				break;
			}

			if ((ma & TypeAttributes.Interface) != 0) {
				kind = MemberKind.Interface;
			} else if (type.IsGenericParameter) {
				kind = MemberKind.TypeParameter;
			} else {
				var base_type = type.BaseType;
				if (base_type == null || (ma & TypeAttributes.Abstract) != 0) {
					kind = MemberKind.Class;
				} else {
					kind = DetermineKindFromBaseType (base_type);
					if (kind == MemberKind.Struct || kind == MemberKind.Delegate) {
						mod |= Modifiers.SEALED;
					}
				}

				if (kind == MemberKind.Class) {
					if ((ma & TypeAttributes.Sealed) != 0) {
						if ((ma & TypeAttributes.Abstract) != 0)
							mod |= Modifiers.STATIC;
						else
							mod |= Modifiers.SEALED;
					} else if ((ma & TypeAttributes.Abstract) != 0) {
						mod |= Modifiers.ABSTRACT;
					}
				}
			}

			var definition = new ImportedTypeDefinition (type, this);
			TypeSpec pt;

			if (kind == MemberKind.Enum) {
				const BindingFlags underlying_member = BindingFlags.DeclaredOnly |
					BindingFlags.Instance |
					BindingFlags.Public | BindingFlags.NonPublic;

				var type_members = type.GetFields (underlying_member);
				foreach (var type_member in type_members) {
					spec = new EnumSpec (declaringType, definition, CreateType (type_member.FieldType), type, mod);
					break;
				}

				if (spec == null)
					kind = MemberKind.Class;

			} else if (kind == MemberKind.TypeParameter) {
				spec = CreateTypeParameter (type, declaringType);
			} else if (type.IsGenericTypeDefinition) {
				definition.TypeParameters = CreateGenericParameters (type, declaringType);
			} else if (compiled_types.TryGetValue (type, out pt)) {
				//
				// Same type was found in inside compiled types. It's
				// either build-in type or forward referenced typed
				// which point into just compiled assembly.
				//
				spec = pt;
				BuiltinTypeSpec bts = pt as BuiltinTypeSpec;
				if (bts != null)
					bts.SetDefinition (definition, type, mod);
			}

			if (spec == null)
				spec = new TypeSpec (kind, declaringType, definition, type, mod);

			import_cache.Add (type, spec);

			if (kind == MemberKind.TypeParameter) {
				if (canImportBaseType)
					ImportTypeParameterTypeConstraints ((TypeParameterSpec) spec, type);

				return spec;
			}

			//
			// Two stage setup as the base type can be inflated declaring type or
			// another nested type inside same declaring type which has not been
			// loaded, therefore we can import a base type of nested types once
			// the types have been imported
			//
			if (canImportBaseType)
				ImportTypeBase (spec, type);

			return spec;
		}

		public IAssemblyDefinition GetAssemblyDefinition (Assembly assembly)
		{
			IAssemblyDefinition found;
			if (!assembly_2_definition.TryGetValue (assembly, out found)) {

				// This can happen in dynamic context only
				var def = new ImportedAssemblyDefinition (assembly);
				assembly_2_definition.Add (assembly, def);
				def.ReadAttributes ();
				found = def;
			}

			return found;
		}

		public void ImportTypeBase (MetaType type)
		{
			TypeSpec spec = import_cache[type];
			if (spec != null)
				ImportTypeBase (spec, type);
		}

		TypeParameterSpec CreateTypeParameter (MetaType type, TypeSpec declaringType)
		{
			Variance variance;
			switch (type.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) {
			case GenericParameterAttributes.Covariant:
				variance = Variance.Covariant;
				break;
			case GenericParameterAttributes.Contravariant:
				variance = Variance.Contravariant;
				break;
			default:
				variance = Variance.None;
				break;
			}

			SpecialConstraint special = SpecialConstraint.None;
			var import_special = type.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask;

			if ((import_special & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) {
				special |= SpecialConstraint.Struct;
			} else if ((import_special & GenericParameterAttributes.DefaultConstructorConstraint) != 0) {
				special = SpecialConstraint.Constructor;
			}

			if ((import_special & GenericParameterAttributes.ReferenceTypeConstraint) != 0) {
				special |= SpecialConstraint.Class;
			}

			TypeParameterSpec spec;
			var def = new ImportedTypeParameterDefinition (type, this);
			if (type.DeclaringMethod != null) {
				spec = new TypeParameterSpec (type.GenericParameterPosition, def, special, variance, type);
			} else {
				spec = new TypeParameterSpec (declaringType, type.GenericParameterPosition, def, special, variance, type);
			}

			return spec;
		}

		//
		// Test for a custom attribute type match. Custom attributes are not really predefined globaly 
		// they can be assembly specific therefore we do check based on names only
		//
		public static bool HasAttribute (IList<CustomAttributeData> attributesData, string attrName, string attrNamespace)
		{
			if (attributesData.Count == 0)
				return false;

			foreach (var attr in attributesData) {
				var dt = attr.Constructor.DeclaringType;
				if (dt.Name == attrName && dt.Namespace == attrNamespace)
					return true;
			}

			return false;
		}

		void ImportTypeBase (TypeSpec spec, MetaType type)
		{
			if (spec.Kind == MemberKind.Interface)
				spec.BaseType = module.Compiler.BuiltinTypes.Object;
			else if (type.BaseType != null) {
				TypeSpec base_type;
				if (!IsMissingType (type.BaseType) && type.BaseType.IsGenericType)
					base_type = CreateType (type.BaseType, new DynamicTypeReader (type), true);
				else
					base_type = CreateType (type.BaseType);

				spec.BaseType = base_type;
			}

			if (spec.MemberDefinition.TypeParametersCount > 0) {
				foreach (var tp in spec.MemberDefinition.TypeParameters) {
					ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
				}
			}
		}

		protected void ImportTypes (MetaType[] types, Namespace targetNamespace, bool importExtensionTypes)
		{
			Namespace ns = targetNamespace;
			string prev_namespace = null;
			foreach (var t in types) {
				if (t == null)
					continue;

				// Be careful not to trigger full parent type loading
				if (t.MemberType == MemberTypes.NestedType)
					continue;

				if (t.Name[0] == '<')
					continue;

				var it = CreateType (t, null, new DynamicTypeReader (t), true);
				if (it == null)
					continue;

				if (prev_namespace != t.Namespace) {
					ns = t.Namespace == null ? targetNamespace : targetNamespace.GetNamespace (t.Namespace, true);
					prev_namespace = t.Namespace;
				}

				// Cannot rely on assembly level Extension attribute or static modifier because they
				// are not followed by other compilers (e.g. F#).
				if (it.IsClass && it.Arity == 0 && importExtensionTypes &&
					HasAttribute (CustomAttributeData.GetCustomAttributes (t), "ExtensionAttribute", CompilerServicesNamespace)) {
					it.SetExtensionMethodContainer ();
				}

				ns.AddType (module, it);
			}
		}

		void ImportTypeParameterTypeConstraints (TypeParameterSpec spec, MetaType type)
		{
			var constraints = type.GetGenericParameterConstraints ();
			List<TypeSpec> tparams = null;
			foreach (var ct in constraints) {
				if (ct.IsGenericParameter) {
					if (tparams == null)
						tparams = new List<TypeSpec> ();

					tparams.Add (CreateType (ct));
					continue;
				}

				var constraint_type = CreateType (ct);
				if (constraint_type.IsClass) {
					spec.BaseType = constraint_type;
					continue;
				}

				spec.AddInterface (constraint_type);
			}

			if (spec.BaseType == null)
				spec.BaseType = module.Compiler.BuiltinTypes.Object;

			if (tparams != null)
				spec.TypeArguments = tparams.ToArray ();
		}

		Constant ImportParameterConstant (object value)
		{
			//
			// Get type of underlying value as int constant can be used for object
			// parameter type. This is not allowed in C# but other languages can do that
			//
			var types = module.Compiler.BuiltinTypes;
			switch (System.Type.GetTypeCode (value.GetType ())) {
			case TypeCode.Boolean:
				return new BoolConstant (types, (bool) value, Location.Null);
			case TypeCode.Byte:
				return new ByteConstant (types, (byte) value, Location.Null);
			case TypeCode.Char:
				return new CharConstant (types, (char) value, Location.Null);
			case TypeCode.Decimal:
				return new DecimalConstant (types, (decimal) value, Location.Null);
			case TypeCode.Double:
				return new DoubleConstant (types, (double) value, Location.Null);
			case TypeCode.Int16:
				return new ShortConstant (types, (short) value, Location.Null);
			case TypeCode.Int32:
				return new IntConstant (types, (int) value, Location.Null);
			case TypeCode.Int64:
				return new LongConstant (types, (long) value, Location.Null);
			case TypeCode.SByte:
				return new SByteConstant (types, (sbyte) value, Location.Null);
			case TypeCode.Single:
				return new FloatConstant (types, (float) value, Location.Null);
			case TypeCode.String:
				return new StringConstant (types, (string) value, Location.Null);
			case TypeCode.UInt16:
				return new UShortConstant (types, (ushort) value, Location.Null);
			case TypeCode.UInt32:
				return new UIntConstant (types, (uint) value, Location.Null);
			case TypeCode.UInt64:
				return new ULongConstant (types, (ulong) value, Location.Null);
			}

			throw new NotImplementedException (value.GetType ().ToString ());
		}

		public TypeSpec ImportType (MetaType type)
		{
			return ImportType (type, new DynamicTypeReader (type));
		}

		TypeSpec ImportType (MetaType type, DynamicTypeReader dtype)
		{
			if (type.HasElementType) {
				var element = type.GetElementType ();
				++dtype.Position;
				var spec = ImportType (element, dtype);

				if (type.IsArray)
					return ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
				if (type.IsByRef)
					return ReferenceContainer.MakeType (module, spec);
				if (type.IsPointer)
					return PointerContainer.MakeType (module, spec);

				throw new NotImplementedException ("Unknown element type " + type.ToString ());
			}

			TypeSpec compiled_type;
			if (compiled_types.TryGetValue (type, out compiled_type)) {
				if (compiled_type.BuiltinType == BuiltinTypeSpec.Type.Object && dtype.IsDynamicObject ())
					return module.Compiler.BuiltinTypes.Dynamic;

				return compiled_type;
			}

			return CreateType (type, dtype, true);
		}

		static bool IsMissingType (MetaType type)
		{
#if STATIC
			return type.__IsMissing;
#else
			return false;
#endif
		}

		//
		// Decimal constants cannot be encoded in the constant blob, and thus are marked
		// as IsInitOnly ('readonly' in C# parlance).  We get its value from the 
		// DecimalConstantAttribute metadata.
		//
		Constant ReadDecimalConstant (IList<CustomAttributeData> attrs)
		{
			if (attrs.Count == 0)
				return null;

			foreach (var ca in attrs) {
				var dt = ca.Constructor.DeclaringType;
				if (dt.Name != "DecimalConstantAttribute" || dt.Namespace != CompilerServicesNamespace)
					continue;

				var value = new decimal (
					(int) (uint) ca.ConstructorArguments[4].Value,
					(int) (uint) ca.ConstructorArguments[3].Value,
					(int) (uint) ca.ConstructorArguments[2].Value,
					(byte) ca.ConstructorArguments[1].Value != 0,
					(byte) ca.ConstructorArguments[0].Value);

				return new DecimalConstant (module.Compiler.BuiltinTypes, value, Location.Null);
			}

			return null;
		}

		static Modifiers ReadMethodModifiers (MethodBase mb, TypeSpec declaringType)
		{
			Modifiers mod;
			var ma = mb.Attributes;
			switch (ma & MethodAttributes.MemberAccessMask) {
			case MethodAttributes.Public:
				mod = Modifiers.PUBLIC;
				break;
			case MethodAttributes.Assembly:
				mod = Modifiers.INTERNAL;
				break;
			case MethodAttributes.Family:
				mod = Modifiers.PROTECTED;
				break;
			case MethodAttributes.FamORAssem:
				mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
				break;
			default:
				mod = Modifiers.PRIVATE;
				break;
			}

			if ((ma & MethodAttributes.Static) != 0) {
				mod |= Modifiers.STATIC;
				return mod;
			}
			if ((ma & MethodAttributes.Abstract) != 0 && declaringType.IsClass) {
				mod |= Modifiers.ABSTRACT;
				return mod;
			}

			// It can be sealed and override
			if ((ma & MethodAttributes.Final) != 0)
				mod |= Modifiers.SEALED;

			if ((ma & MethodAttributes.Virtual) != 0) {
				// Not every member can be detected based on MethodAttribute, we
				// set virtual or non-virtual only when we are certain. Further checks
				// to really find out what `virtual' means for this member are done
				// later
				if ((ma & MethodAttributes.NewSlot) != 0) {
					if ((mod & Modifiers.SEALED) != 0) {
						mod &= ~Modifiers.SEALED;
					} else {
						mod |= Modifiers.VIRTUAL;
					}
				} else {
					mod |= Modifiers.OVERRIDE;
				}
			}

			return mod;
		}
	}

	abstract class ImportedDefinition : IMemberDefinition
	{
		protected class AttributesBag
		{
			public static readonly AttributesBag Default = new AttributesBag ();

			public AttributeUsageAttribute AttributeUsage;
			public ObsoleteAttribute Obsolete;
			public string[] Conditionals;
			public string DefaultIndexerName;
			public bool? CLSAttributeValue;
			public TypeSpec CoClass;
			
			public static AttributesBag Read (MemberInfo mi, MetadataImporter importer)
			{
				AttributesBag bag = null;
				List<string> conditionals = null;

				// It should not throw any loading exception
				IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (mi);

				foreach (var a in attrs) {
					var dt = a.Constructor.DeclaringType;
					string name = dt.Name;
					if (name == "ObsoleteAttribute") {
						if (dt.Namespace != "System")
							continue;

						if (bag == null)
							bag = new AttributesBag ();

						var args = a.ConstructorArguments;

						if (args.Count == 1) {
							bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value);
						} else if (args.Count == 2) {
							bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value, (bool) args[1].Value);
						} else {
							bag.Obsolete = new ObsoleteAttribute ();
						}

						continue;
					}

					if (name == "ConditionalAttribute") {
						if (dt.Namespace != "System.Diagnostics")
							continue;

						if (bag == null)
							bag = new AttributesBag ();

						if (conditionals == null)
							conditionals = new List<string> (2);

						conditionals.Add ((string) a.ConstructorArguments[0].Value);
						continue;
					}

					if (name == "CLSCompliantAttribute") {
						if (dt.Namespace != "System")
							continue;

						if (bag == null)
							bag = new AttributesBag ();

						bag.CLSAttributeValue = (bool) a.ConstructorArguments[0].Value;
						continue;
					}

					// Type only attributes
					if (mi.MemberType == MemberTypes.TypeInfo || mi.MemberType == MemberTypes.NestedType) {
						if (name == "DefaultMemberAttribute") {
							if (dt.Namespace != "System.Reflection")
								continue;

							if (bag == null)
								bag = new AttributesBag ();

							bag.DefaultIndexerName = (string) a.ConstructorArguments[0].Value;
							continue;
						}

						if (name == "AttributeUsageAttribute") {
							if (dt.Namespace != "System")
								continue;

							if (bag == null)
								bag = new AttributesBag ();

							bag.AttributeUsage = new AttributeUsageAttribute ((AttributeTargets) a.ConstructorArguments[0].Value);
							foreach (var named in a.NamedArguments) {
								if (named.MemberInfo.Name == "AllowMultiple")
									bag.AttributeUsage.AllowMultiple = (bool) named.TypedValue.Value;
								else if (named.MemberInfo.Name == "Inherited")
									bag.AttributeUsage.Inherited = (bool) named.TypedValue.Value;
							}
							continue;
						}

						// Interface only attribute
						if (name == "CoClassAttribute") {
							if (dt.Namespace != "System.Runtime.InteropServices")
								continue;

							if (bag == null)
								bag = new AttributesBag ();

							bag.CoClass = importer.ImportType ((MetaType) a.ConstructorArguments[0].Value);
							continue;
						}
					}
				}

				if (bag == null)
					return Default;

				if (conditionals != null)
					bag.Conditionals = conditionals.ToArray ();
				
				return bag;
			}
		}

		protected readonly MemberInfo provider;
		protected AttributesBag cattrs;
		protected readonly MetadataImporter importer;

		protected ImportedDefinition (MemberInfo provider, MetadataImporter importer)
		{
			this.provider = provider;
			this.importer = importer;
		}

		#region Properties

		public bool IsImported {
			get {
				return true;
			}
		}

		public virtual string Name {
			get {
				return provider.Name;
			}
		}

		#endregion

		public string[] ConditionalConditions ()
		{
			if (cattrs == null)
				ReadAttributes ();

			return cattrs.Conditionals;
		}

		public ObsoleteAttribute GetAttributeObsolete ()
		{
			if (cattrs == null)
				ReadAttributes ();

			return cattrs.Obsolete;
		}

		public bool? CLSAttributeValue {
			get {
				if (cattrs == null)
					ReadAttributes ();

				return cattrs.CLSAttributeValue;
			}
		}

		protected void ReadAttributes ()
		{
			cattrs = AttributesBag.Read (provider, importer);
		}

		public void SetIsAssigned ()
		{
			// Unused for imported members
		}

		public void SetIsUsed ()
		{
			// Unused for imported members
		}
	}

	public class ImportedModuleDefinition
	{
		readonly Module module;
		bool cls_compliant;
		
		public ImportedModuleDefinition (Module module)
		{
			this.module = module;
		}

		#region Properties

		public bool IsCLSCompliant {
			get {
				return cls_compliant;
			}
		}

		public string Name {
			get {
				return module.Name;
			}
		}

		#endregion

		public void ReadAttributes ()
		{
			IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (module);

			foreach (var a in attrs) {
				var dt = a.Constructor.DeclaringType;
				if (dt.Name == "CLSCompliantAttribute") {
					if (dt.Namespace != "System")
						continue;

					cls_compliant = (bool) a.ConstructorArguments[0].Value;
					continue;
				}
			}
		}

		//
		// Reads assembly attributes which where attached to a special type because
		// module does have assembly manifest
		//
		public List<Attribute> ReadAssemblyAttributes ()
		{
			var t = module.GetType (AssemblyAttributesPlaceholder.GetGeneratedName (Name));
			if (t == null)
				return null;

			var field = t.GetField (AssemblyAttributesPlaceholder.AssemblyFieldName, BindingFlags.NonPublic | BindingFlags.Static);
			if (field == null)
				return null;

			// TODO: implement, the idea is to fabricate specil Attribute class and
			// add it to OptAttributes before resolving the source code attributes
			// Need to build module location as well for correct error reporting

			//var assembly_attributes = CustomAttributeData.GetCustomAttributes (field);
			//var attrs = new List<Attribute> (assembly_attributes.Count);
			//foreach (var a in assembly_attributes)
			//{
			//    var type = metaImporter.ImportType (a.Constructor.DeclaringType);
			//    var ctor = metaImporter.CreateMethod (a.Constructor, type);

			//    foreach (var carg in a.ConstructorArguments) {
			//        carg.Value
			//    }

			//    attrs.Add (new Attribute ("assembly", ctor, null, Location.Null, true));
			//}

			return null;
		}
	}

	public class ImportedAssemblyDefinition : IAssemblyDefinition
	{
		readonly Assembly assembly;
		readonly AssemblyName aname;
		bool cls_compliant;

		List<AssemblyName> internals_visible_to;
		Dictionary<IAssemblyDefinition, AssemblyName> internals_visible_to_cache;

		public ImportedAssemblyDefinition (Assembly assembly)
		{
			this.assembly = assembly;
			this.aname = assembly.GetName ();
		}

		#region Properties

		public Assembly Assembly {
			get {
				return assembly;
			}
		}

		public string FullName {
			get {
				return aname.FullName;
			}
		}

		public bool HasStrongName {
			get {
				return aname.GetPublicKey ().Length != 0;
			}
		}

		public bool IsMissing {
			get {
#if STATIC
				return assembly.__IsMissing;
#else
				return false;
#endif
			}
		}

		public bool IsCLSCompliant {
			get {
				return cls_compliant;
			}
		}

		public string Location {
			get {
				return assembly.Location;
			}
		}

		public string Name {
			get {
				return aname.Name;
			}
		}

		#endregion

		public byte[] GetPublicKeyToken ()
		{
			return aname.GetPublicKeyToken ();
		}

		public AssemblyName GetAssemblyVisibleToName (IAssemblyDefinition assembly)
		{
			return internals_visible_to_cache [assembly];
		}

		public bool IsFriendAssemblyTo (IAssemblyDefinition assembly)
		{
			if (internals_visible_to == null)
				return false;

			AssemblyName is_visible = null;
			if (internals_visible_to_cache == null) {
				internals_visible_to_cache = new Dictionary<IAssemblyDefinition, AssemblyName> ();
			} else {
				if (internals_visible_to_cache.TryGetValue (assembly, out is_visible))
					return is_visible != null;
			}

			var token = assembly.GetPublicKeyToken ();
			if (token != null && token.Length == 0)
				token = null;

			foreach (var internals in internals_visible_to) {
				if (internals.Name != assembly.Name)
					continue;

				if (token == null && assembly is AssemblyDefinition) {
					is_visible = internals;
					break;
				}

				if (!ArrayComparer.IsEqual (token, internals.GetPublicKeyToken ()))
					continue;

				is_visible = internals;
				break;
			}

			internals_visible_to_cache.Add (assembly, is_visible);
			return is_visible != null;
		}

		public void ReadAttributes ()
		{
#if STATIC
			if (assembly.__IsMissing)
				return;
#endif

			IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (assembly);

			foreach (var a in attrs) {
				var dt = a.Constructor.DeclaringType;
				var name = dt.Name;
				if (name == "CLSCompliantAttribute") {
					if (dt.Namespace == "System") {
						cls_compliant = (bool) a.ConstructorArguments[0].Value;
					}
					continue;
				}

				if (name == "InternalsVisibleToAttribute") {
					if (dt.Namespace != MetadataImporter.CompilerServicesNamespace)
						continue;

					string s = a.ConstructorArguments[0].Value as string;
					if (s == null)
						continue;

					var an = new AssemblyName (s);
					if (internals_visible_to == null)
						internals_visible_to = new List<AssemblyName> ();

					internals_visible_to.Add (an);
					continue;
				}
			}
		}

		public override string ToString ()
		{
			return FullName;
		}
	}

	class ImportedMemberDefinition : ImportedDefinition
	{
		readonly TypeSpec type;

		public ImportedMemberDefinition (MemberInfo member, TypeSpec type, MetadataImporter importer)
			: base (member, importer)
		{
			this.type = type;
		}

		#region Properties

		public TypeSpec MemberType {
			get {
				return type;
			}
		}

		#endregion
	}

	class ImportedParameterMemberDefinition : ImportedMemberDefinition, IParametersMember
	{
		readonly AParametersCollection parameters;

		protected ImportedParameterMemberDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
			: base (provider, type, importer)
		{
			this.parameters = parameters;
		}

		public ImportedParameterMemberDefinition (PropertyInfo provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
			: base (provider, type, importer)
		{
			this.parameters = parameters;
		}

		#region Properties

		public AParametersCollection Parameters {
			get {
				return parameters;
			}
		}

		#endregion
	}

	class ImportedMethodDefinition : ImportedParameterMemberDefinition, IMethodDefinition
	{
		public ImportedMethodDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
			: base (provider, type, parameters, importer)
		{
		}

		MethodBase IMethodDefinition.Metadata {
			get {
				return (MethodBase) provider;
			}
		}
	}

	class ImportedGenericMethodDefinition : ImportedMethodDefinition, IGenericMethodDefinition
	{
		readonly TypeParameterSpec[] tparams;

		public ImportedGenericMethodDefinition (MethodInfo provider, TypeSpec type, AParametersCollection parameters, TypeParameterSpec[] tparams, MetadataImporter importer)
			: base (provider, type, parameters, importer)
		{
			this.tparams = tparams;
		}

		#region Properties

		public TypeParameterSpec[] TypeParameters {
			get {
				return tparams;
			}
		}

		public int TypeParametersCount {
			get {
				return tparams.Length;
			}
		}

		#endregion
	}

	class ImportedTypeDefinition : ImportedDefinition, ITypeDefinition
	{
		TypeParameterSpec[] tparams;
		string name;

		public ImportedTypeDefinition (MetaType type, MetadataImporter importer)
			: base (type, importer)
		{
		}

		#region Properties

		public IAssemblyDefinition DeclaringAssembly {
			get {
				return importer.GetAssemblyDefinition (provider.Module.Assembly);
			}
		}

		bool ITypeDefinition.IsComImport {
			get {
				return ((MetaType) provider).IsImport;
			}
		}


		bool ITypeDefinition.IsPartial {
			get {
				return false;
			}
		}

		bool ITypeDefinition.IsTypeForwarder {
			get {
#if STATIC
				return ((MetaType) provider).__IsTypeForwarder;
#else
				return false;
#endif
			}
		}

		bool ITypeDefinition.IsCyclicTypeForwarder {
			get {
#if STATIC
				return ((MetaType) provider).__IsCyclicTypeForwarder;
#else
				return false;
#endif
			}
		}

		public override string Name {
			get {
				if (name == null) {
					name = base.Name;
					if (tparams != null) {
						int arity_start = name.IndexOf ('`');
						if (arity_start > 0)
							name = name.Substring (0, arity_start);
					}
				}

				return name;
			}
		}

		public string Namespace {
			get {
				return ((MetaType) provider).Namespace;
			}
		}

		public int TypeParametersCount {
			get {
				return tparams == null ? 0 : tparams.Length;
			}
		}

		public TypeParameterSpec[] TypeParameters {
			get {
				return tparams;
			}
			set {
				tparams = value;
			}
		}

		#endregion

		public void DefineInterfaces (TypeSpec spec)
		{
			var type = (MetaType) provider;
			MetaType[] ifaces;
#if STATIC
			ifaces = type.__GetDeclaredInterfaces ();
			if (ifaces.Length != 0) {
				foreach (var iface in ifaces) {
					var it = importer.CreateType (iface);
					if (it == null)
						continue;

					spec.AddInterfaceDefined (it);

					// Unfortunately not all languages expand inherited interfaces
					var bifaces = it.Interfaces;
					if (bifaces != null) {
						foreach (var biface in bifaces) {
							spec.AddInterfaceDefined (biface);
						}
					}
				}
			}
			
			//
			// It's impossible to get declared interfaces only using System.Reflection
			// hence we need to mimic the behavior with ikvm-reflection too to keep
			// our type look-up logic same
			//
			if (spec.BaseType != null) {
				var bifaces = spec.BaseType.Interfaces;
				if (bifaces != null) {
					//
					// Before adding base class interfaces close defined interfaces
					// on type parameter
					//
					var tp = spec as TypeParameterSpec;
					if (tp != null && tp.InterfacesDefined == null) {
						tp.InterfacesDefined = TypeSpec.EmptyTypes;
					}

					foreach (var iface in bifaces)
						spec.AddInterfaceDefined (iface);
				}
			}
#else
			ifaces = type.GetInterfaces ();

			if (ifaces.Length > 0) {
				foreach (var iface in ifaces) {
					spec.AddInterface (importer.CreateType (iface));
				}
			}
#endif

		}

		public static void Error_MissingDependency (IMemberContext ctx, List<MissingTypeSpecReference> missing, Location loc)
		{
			// 
			// Report details about missing type and most likely cause of the problem.
			// csc reports 1683, 1684 as warnings but we report them only when used
			// or referenced from the user core in which case compilation error has to
			// be reported because compiler cannot continue anyway
			//

			var report = ctx.Module.Compiler.Report;

			for (int i = 0; i < missing.Count; ++i) {
				var t = missing [i].Type;

				//
				// Report missing types only once
				//
				if (report.Printer.MissingTypeReported (t.MemberDefinition))
					continue;

				string name = t.GetSignatureForError ();

				var caller = missing[i].Caller;
				if (caller.Kind != MemberKind.MissingType)
					report.SymbolRelatedToPreviousError (caller);

				var definition = t.MemberDefinition;
				if (definition.DeclaringAssembly == ctx.Module.DeclaringAssembly) {
					report.Error (1683, loc,
						"Reference to type `{0}' claims it is defined in this assembly, but it is not defined in source or any added modules",
						name);
				} else if (definition.DeclaringAssembly.IsMissing) {
					if (definition.IsTypeForwarder) {
						report.Error (1070, loc,
							"The type `{0}' has been forwarded to an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
							name, definition.DeclaringAssembly.FullName);
					} else {
						report.Error (12, loc,
							"The type `{0}' is defined in an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
							name, definition.DeclaringAssembly.FullName);
					}
				} else if (definition.IsTypeForwarder) {
					report.Error (731, loc, "The type forwarder for type `{0}' in assembly `{1}' has circular dependency",
						name, definition.DeclaringAssembly.FullName);
				} else {
					report.Error (1684, loc,
						"Reference to type `{0}' claims it is defined assembly `{1}', but it could not be found",
						name, t.MemberDefinition.DeclaringAssembly.FullName);
				}
			}
		}

		public TypeSpec GetAttributeCoClass ()
		{
			if (cattrs == null)
				ReadAttributes ();

			return cattrs.CoClass;
		}

		public string GetAttributeDefaultMember ()
		{
			if (cattrs == null)
				ReadAttributes ();

			return cattrs.DefaultIndexerName;
		}

		public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
		{
			if (cattrs == null)
				ReadAttributes ();

			return cattrs.AttributeUsage;
		}

		bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
		{
			var a = importer.GetAssemblyDefinition (provider.Module.Assembly);
			return a == assembly || a.IsFriendAssemblyTo (assembly);
		}

		public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
		{
			//
			// Not interested in members of nested private types unless the importer needs them
			//
			if (declaringType.IsPrivate && importer.IgnorePrivateMembers) {
				cache = MemberCache.Empty;
				return;
			}

			var loading_type = (MetaType) provider;
			const BindingFlags all_members = BindingFlags.DeclaredOnly |
				BindingFlags.Static | BindingFlags.Instance |
				BindingFlags.Public | BindingFlags.NonPublic;

			const MethodAttributes explicit_impl = MethodAttributes.NewSlot |
					MethodAttributes.Virtual | MethodAttributes.HideBySig |
					MethodAttributes.Final;

			Dictionary<MethodBase, MethodSpec> possible_accessors = null;
			List<EventSpec> imported_events = null;
			EventSpec event_spec;
			MemberSpec imported;
			MethodInfo m;
			MemberInfo[] all;
			try {
				all = loading_type.GetMembers (all_members);
			} catch (Exception e) {
				throw new InternalErrorException (e, "Could not import type `{0}' from `{1}'",
					declaringType.GetSignatureForError (), declaringType.MemberDefinition.DeclaringAssembly.FullName);
			}

			if (cache == null) {
				cache = new MemberCache (all.Length);

				//
				// Do the types first as they can be referenced by the members before
				// they are found or inflated
				//
				foreach (var member in all) {
					if (member.MemberType != MemberTypes.NestedType)
						continue;

					var t = (MetaType) member;

					// Ignore compiler generated types, mostly lambda containers
					if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
						continue;

					try {
						imported = importer.CreateNestedType (t, declaringType);
					} catch (Exception e) {
						throw new InternalErrorException (e, "Could not import nested type `{0}' from `{1}'",
							t.FullName, declaringType.MemberDefinition.DeclaringAssembly.FullName);
					}

					cache.AddMemberImported (imported);
				}

				foreach (var member in all) {
					if (member.MemberType != MemberTypes.NestedType)
						continue;

					var t = (MetaType) member;

					if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
						continue;

					importer.ImportTypeBase (t);
				}
			}

			//
			// Load base interfaces first to minic behaviour of compiled members
			//
			if (declaringType.IsInterface && declaringType.Interfaces != null) {
				foreach (var iface in declaringType.Interfaces) {
					cache.AddInterface (iface);
				}
			}

			if (!onlyTypes) {
				//
				// The logic here requires methods to be returned first which seems to work for both Mono and .NET
				//
				foreach (var member in all) {
					switch (member.MemberType) {
					case MemberTypes.Constructor:
						if (declaringType.IsInterface)
							continue;

						goto case MemberTypes.Method;
					case MemberTypes.Method:
						MethodBase mb = (MethodBase) member;
						var attrs = mb.Attributes;

						if ((attrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) {
							if (importer.IgnorePrivateMembers)
								continue;

							// Ignore explicitly implemented members
							if ((attrs & explicit_impl) == explicit_impl)
								continue;

							// Ignore compiler generated methods
							if (MetadataImporter.HasAttribute (CustomAttributeData.GetCustomAttributes (mb), "CompilerGeneratedAttribute", MetadataImporter.CompilerServicesNamespace))
								continue;
						}

						imported = importer.CreateMethod (mb, declaringType);
						if (imported.Kind == MemberKind.Method && !imported.IsGeneric) {
							if (possible_accessors == null)
								possible_accessors = new Dictionary<MethodBase, MethodSpec> (ReferenceEquality<MethodBase>.Default);

							// There are no metadata rules for accessors, we have to consider any method as possible candidate
							possible_accessors.Add (mb, (MethodSpec) imported);
						}

						break;
					case MemberTypes.Property:
						if (possible_accessors == null)
							continue;

						var p = (PropertyInfo) member;
						//
						// Links possible accessors with property
						//
						MethodSpec get, set;
						m = p.GetGetMethod (true);
						if (m == null || !possible_accessors.TryGetValue (m, out get))
							get = null;

						m = p.GetSetMethod (true);
						if (m == null || !possible_accessors.TryGetValue (m, out set))
							set = null;

						// No accessors registered (e.g. explicit implementation)
						if (get == null && set == null)
							continue;

						try {
							imported = importer.CreateProperty (p, declaringType, get, set);
						} catch (Exception ex) {
							throw new InternalErrorException (ex, "Could not import property `{0}' inside `{1}'",
								p.Name, declaringType.GetSignatureForError ());
						}

						if (imported == null)
							continue;

						break;
					case MemberTypes.Event:
						if (possible_accessors == null)
							continue;

						var e = (EventInfo) member;
						//
						// Links accessors with event
						//
						MethodSpec add, remove;
						m = e.GetAddMethod (true);
						if (m == null || !possible_accessors.TryGetValue (m, out add))
							add = null;

						m = e.GetRemoveMethod (true);
						if (m == null || !possible_accessors.TryGetValue (m, out remove))
							remove = null;

						// Both accessors are required
						if (add == null || remove == null)
							continue;

						event_spec = importer.CreateEvent (e, declaringType, add, remove);
						if (!importer.IgnorePrivateMembers) {
							if (imported_events == null)
								imported_events = new List<EventSpec> ();

							imported_events.Add (event_spec);
						}

						imported = event_spec;
						break;
					case MemberTypes.Field:
						var fi = (FieldInfo) member;

						imported = importer.CreateField (fi, declaringType);
						if (imported == null)
							continue;

						//
						// For dynamic binder event has to be fully restored to allow operations
						// within the type container to work correctly
						//
						if (imported_events != null) {
							// The backing event field should be private but it may not
							int i;
							for (i = 0; i < imported_events.Count; ++i) {
								var ev = imported_events[i];
								if (ev.Name == fi.Name) {
									ev.BackingField = (FieldSpec) imported;
									imported_events.RemoveAt (i);
									i = -1;
									break;
								}
							}

							if (i < 0)
								continue;
						}

						break;
					case MemberTypes.NestedType:
						// Already in the cache from the first pass
						continue;
					default:
						throw new NotImplementedException (member.ToString ());
					}

					if (imported.IsStatic && declaringType.IsInterface)
						continue;

					cache.AddMemberImported (imported);
				}
			}
		}
	}

	class ImportedTypeParameterDefinition : ImportedDefinition, ITypeDefinition
	{
		public ImportedTypeParameterDefinition (MetaType type, MetadataImporter importer)
			: base (type, importer)
		{
		}

		#region Properties

		public IAssemblyDefinition DeclaringAssembly {
			get {
				throw new NotImplementedException ();
			}
		}

		bool ITypeDefinition.IsComImport {
			get {
				return false;
			}
		}

		bool ITypeDefinition.IsPartial {
			get {
				return false;
			}
		}

		bool ITypeDefinition.IsTypeForwarder {
			get {
				return false;
			}
		}

		bool ITypeDefinition.IsCyclicTypeForwarder {
			get {
				return false;
			}
		}

		public string Namespace {
			get {
				return null;
			}
		}

		public int TypeParametersCount {
			get {
				return 0;
			}
		}

		public TypeParameterSpec[] TypeParameters {
			get {
				return null;
			}
		}

		#endregion

		public TypeSpec GetAttributeCoClass ()
		{
			return null;
		}

		public string GetAttributeDefaultMember ()
		{
			throw new NotSupportedException ();
		}

		public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
		{
			throw new NotSupportedException ();
		}

		bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
		{
			throw new NotImplementedException ();
		}

		public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
		{
			throw new NotImplementedException ();
		}
	}
}