ce43902012d843e19be99e0355e1ece5da5246d9
[mono.git] / mcs / mcs / import.cs
1 //
2 // import.cs: System.Reflection conversions
3 //
4 // Authors: Marek Safar (marek.safar@gmail.com)
5 //
6 // Dual licensed under the terms of the MIT X11 or GNU GPL
7 //
8 // Copyright 2009-2011 Novell, Inc
9 // Copyright 2011-2012 Xamarin, Inc (http://www.xamarin.com)
10 //
11
12 using System;
13 using System.Runtime.CompilerServices;
14 using System.Linq;
15 using System.Collections.Generic;
16
17 #if STATIC
18 using MetaType = IKVM.Reflection.Type;
19 using IKVM.Reflection;
20 using IKVM.Reflection.Emit;
21 #else
22 using MetaType = System.Type;
23 using System.Reflection;
24 using System.Reflection.Emit;
25 #endif
26
27 namespace Mono.CSharp
28 {
29         public abstract class MetadataImporter
30         {
31                 //
32                 // Dynamic types reader with additional logic to reconstruct a dynamic
33                 // type using DynamicAttribute values
34                 //
35                 protected struct DynamicTypeReader
36                 {
37                         static readonly bool[] single_attribute = { true };
38
39                         public int Position;
40                         bool[] flags;
41
42                         // There is no common type for CustomAttributeData and we cannot
43                         // use ICustomAttributeProvider
44                         object provider;
45
46                         //
47                         // A member provider which can be used to get CustomAttributeData
48                         //
49                         public DynamicTypeReader (object provider)
50                         {
51                                 Position = 0;
52                                 flags = null;
53                                 this.provider = provider;
54                         }
55
56                         //
57                         // Returns true when object at local position has dynamic attribute flag
58                         //
59                         public bool IsDynamicObject (MetadataImporter importer)
60                         {
61                                 if (provider != null)
62                                         ReadAttribute (importer);
63
64                                 return flags != null && Position < flags.Length && flags[Position];
65                         }
66
67                         //
68                         // Returns true when DynamicAttribute exists
69                         //
70                         public bool HasDynamicAttribute (MetadataImporter importer)
71                         {
72                                 if (provider != null)
73                                         ReadAttribute (importer);
74
75                                 return flags != null;
76                         }
77
78                         void ReadAttribute (MetadataImporter importer)
79                         {
80                                 IList<CustomAttributeData> cad;
81                                 if (provider is MemberInfo) {
82                                         cad = CustomAttributeData.GetCustomAttributes ((MemberInfo) provider);
83                                 } else if (provider is ParameterInfo) {
84                                         cad = CustomAttributeData.GetCustomAttributes ((ParameterInfo) provider);
85                                 } else {
86                                         provider = null;
87                                         return;
88                                 }
89
90                                 if (cad.Count > 0) {
91                                         foreach (var ca in cad) {
92                                                 var dt = ca.Constructor.DeclaringType;
93                                                 if (dt.Name != "DynamicAttribute" || dt.Namespace != CompilerServicesNamespace)
94                                                         continue;
95
96                                                 if (ca.ConstructorArguments.Count == 0) {
97                                                         flags = single_attribute;
98                                                         break;
99                                                 }
100
101                                                 var arg_type = ca.ConstructorArguments[0].ArgumentType;
102
103                                                 if (arg_type.IsArray && MetaType.GetTypeCode (arg_type.GetElementType ()) == TypeCode.Boolean) {
104                                                         var carg = (IList<CustomAttributeTypedArgument>) ca.ConstructorArguments[0].Value;
105                                                         flags = new bool[carg.Count];
106                                                         for (int i = 0; i < flags.Length; ++i) {
107                                                                 if (MetaType.GetTypeCode (carg[i].ArgumentType) == TypeCode.Boolean)
108                                                                         flags[i] = (bool) carg[i].Value;
109                                                         }
110
111                                                         break;
112                                                 }
113                                         }
114                                 }
115
116                                 provider = null;
117                         }
118                 }
119
120                 protected readonly Dictionary<MetaType, TypeSpec> import_cache;
121                 protected readonly Dictionary<MetaType, TypeSpec> compiled_types;
122                 protected readonly Dictionary<Assembly, IAssemblyDefinition> assembly_2_definition;
123                 protected readonly ModuleContainer module;
124
125                 public static readonly string CompilerServicesNamespace = "System.Runtime.CompilerServices";
126
127                 protected MetadataImporter (ModuleContainer module)
128                 {
129                         this.module = module;
130
131                         import_cache = new Dictionary<MetaType, TypeSpec> (1024, ReferenceEquality<MetaType>.Default);
132                         compiled_types = new Dictionary<MetaType, TypeSpec> (40, ReferenceEquality<MetaType>.Default);
133                         assembly_2_definition = new Dictionary<Assembly, IAssemblyDefinition> (ReferenceEquality<Assembly>.Default);
134                         IgnorePrivateMembers = true;
135                 }
136
137                 #region Properties
138
139                 public ICollection<IAssemblyDefinition> Assemblies {
140                         get {
141                                 return assembly_2_definition.Values;
142                         }
143                 }
144
145                 public bool IgnorePrivateMembers { get; set; }
146
147                 #endregion
148
149                 public abstract void AddCompiledType (TypeBuilder builder, TypeSpec spec);
150                 protected abstract MemberKind DetermineKindFromBaseType (MetaType baseType);
151                 protected abstract bool HasVolatileModifier (MetaType[] modifiers);
152
153                 public FieldSpec CreateField (FieldInfo fi, TypeSpec declaringType)
154                 {
155                         Modifiers mod = 0;
156                         var fa = fi.Attributes;
157                         switch (fa & FieldAttributes.FieldAccessMask) {
158                                 case FieldAttributes.Public:
159                                         mod = Modifiers.PUBLIC;
160                                         break;
161                                 case FieldAttributes.Assembly:
162                                         mod = Modifiers.INTERNAL;
163                                         break;
164                                 case FieldAttributes.Family:
165                                         mod = Modifiers.PROTECTED;
166                                         break;
167                                 case FieldAttributes.FamORAssem:
168                                         mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
169                                         break;
170                                 default:
171                                         // Ignore private fields (even for error reporting) to not require extra dependencies
172                                         if ((IgnorePrivateMembers && !declaringType.IsStruct) ||
173                                                 HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "CompilerGeneratedAttribute", CompilerServicesNamespace))
174                                                 return null;
175
176                                         mod = Modifiers.PRIVATE;
177                                         break;
178                         }
179
180                         TypeSpec field_type;
181
182                         try {
183                                 field_type = ImportType (fi.FieldType, new DynamicTypeReader (fi));
184                         } catch (Exception e) {
185                                 // TODO: I should construct fake TypeSpec based on TypeRef signature
186                                 // but there is no way to do it with System.Reflection
187                                 throw new InternalErrorException (e, "Cannot import field `{0}.{1}' referenced in assembly `{2}'",
188                                         declaringType.GetSignatureForError (), fi.Name, declaringType.MemberDefinition.DeclaringAssembly);
189                         }
190
191                         var definition = new ImportedMemberDefinition (fi, field_type, this);
192
193                         if ((fa & FieldAttributes.Literal) != 0) {
194                                 Constant c = field_type.Kind == MemberKind.MissingType ?
195                                         new NullConstant (InternalType.ErrorType, Location.Null) :
196                                         Constant.CreateConstantFromValue (field_type, fi.GetRawConstantValue (), Location.Null);
197                                 return new ConstSpec (declaringType, definition, field_type, fi, mod, c);
198                         }
199
200                         if ((fa & FieldAttributes.InitOnly) != 0) {
201                                 if (field_type.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
202                                         var dc = ReadDecimalConstant (CustomAttributeData.GetCustomAttributes (fi));
203                                         if (dc != null)
204                                                 return new ConstSpec (declaringType, definition, field_type, fi, mod, dc);
205                                 }
206
207                                 mod |= Modifiers.READONLY;
208                         } else {
209                                 var req_mod = fi.GetRequiredCustomModifiers ();
210                                 if (req_mod.Length > 0 && HasVolatileModifier (req_mod))
211                                         mod |= Modifiers.VOLATILE;
212                         }
213
214                         if ((fa & FieldAttributes.Static) != 0) {
215                                 mod |= Modifiers.STATIC;
216                         } else {
217                                 // Fixed buffers cannot be static
218                                 if (declaringType.IsStruct && field_type.IsStruct && field_type.IsNested &&
219                                         HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "FixedBufferAttribute", CompilerServicesNamespace)) {
220
221                                         // TODO: Sanity check on field_type (only few types are allowed)
222                                         var element_field = CreateField (fi.FieldType.GetField (FixedField.FixedElementName), declaringType);
223                                         return new FixedFieldSpec (module, declaringType, definition, fi, element_field, mod);
224                                 }
225                         }
226
227                         return new FieldSpec (declaringType, definition, field_type, fi, mod);
228                 }
229
230                 public EventSpec CreateEvent (EventInfo ei, TypeSpec declaringType, MethodSpec add, MethodSpec remove)
231                 {
232                         add.IsAccessor = true;
233                         remove.IsAccessor = true;
234
235                         if (add.Modifiers != remove.Modifiers)
236                                 throw new NotImplementedException ("Different accessor modifiers " + ei.Name);
237
238                         var event_type = ImportType (ei.EventHandlerType, new DynamicTypeReader (ei));
239                         var definition = new ImportedMemberDefinition (ei, event_type,  this);
240                         return new EventSpec (declaringType, definition, event_type, add.Modifiers, add, remove);
241                 }
242
243                 TypeParameterSpec[] CreateGenericParameters (MetaType type, TypeSpec declaringType)
244                 {
245                         var tparams = type.GetGenericArguments ();
246
247                         int parent_owned_count;
248                         if (type.IsNested) {
249                                 parent_owned_count = type.DeclaringType.GetGenericArguments ().Length;
250
251                                 //
252                                 // System.Reflection duplicates parent type parameters for each
253                                 // nested type with slightly modified properties (eg. different owner)
254                                 // This just makes things more complicated (think of cloned constraints)
255                                 // therefore we remap any nested type owned by parent using `type_cache'
256                                 // to the single TypeParameterSpec
257                                 //
258                                 if (declaringType != null && parent_owned_count > 0) {
259                                         int read_count = 0;
260                                         while (read_count != parent_owned_count) {
261                                                 var tparams_count = declaringType.Arity;
262                                                 if (tparams_count != 0) {
263                                                         var parent_tp = declaringType.MemberDefinition.TypeParameters;
264                                                         read_count += tparams_count;
265                                                         for (int i = 0; i < tparams_count; i++) {
266                                                                 import_cache.Add (tparams[parent_owned_count - read_count + i], parent_tp[i]);
267                                                         }
268                                                 }
269
270                                                 declaringType = declaringType.DeclaringType;
271                                         }
272                                 }                       
273                         } else {
274                                 parent_owned_count = 0;
275                         }
276
277                         if (tparams.Length - parent_owned_count == 0)
278                                 return null;
279
280                         return CreateGenericParameters (parent_owned_count, tparams);
281                 }
282
283                 TypeParameterSpec[] CreateGenericParameters (int first, MetaType[] tparams)
284                 {
285                         var tspec = new TypeParameterSpec[tparams.Length - first];
286                         for (int pos = first; pos < tparams.Length; ++pos) {
287                                 var type = tparams[pos];
288                                 int index = pos - first;
289
290                                 tspec[index] = (TypeParameterSpec) CreateType (type, new DynamicTypeReader (), false);
291                         }
292
293                         return tspec;
294                 }
295
296                 TypeSpec[] CreateGenericArguments (int first, MetaType[] tparams, DynamicTypeReader dtype)
297                 {
298                         ++dtype.Position;
299
300                         var tspec = new TypeSpec [tparams.Length - first];
301                         for (int pos = first; pos < tparams.Length; ++pos) {
302                                 var type = tparams[pos];
303                                 int index = pos - first;
304
305                                 TypeSpec spec;
306                                 if (type.HasElementType) {
307                                         var element = type.GetElementType ();
308                                         ++dtype.Position;
309                                         spec = ImportType (element, dtype);
310
311                                         if (!type.IsArray) {
312                                                 throw new NotImplementedException ("Unknown element type " + type.ToString ());
313                                         }
314
315                                         spec = ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
316                                 } else {
317                                         spec = CreateType (type, dtype, true);
318
319                                         //
320                                         // We treat nested generic types as inflated internally where
321                                         // reflection uses type definition
322                                         //
323                                         // class A<T> {
324                                         //    IFoo<A<T>> foo;   // A<T> is definition in this case
325                                         // }
326                                         //
327                                         // TODO: Is full logic from CreateType needed here as well?
328                                         //
329                                         if (!IsMissingType (type) && type.IsGenericTypeDefinition) {
330                                                 var targs = CreateGenericArguments (0, type.GetGenericArguments (), dtype);
331                                                 spec = spec.MakeGenericType (module, targs);
332                                         }
333                                 }
334
335                                 ++dtype.Position;
336                                 tspec[index] = spec;
337                         }
338
339                         return tspec;
340                 }
341
342                 public MethodSpec CreateMethod (MethodBase mb, TypeSpec declaringType)
343                 {
344                         Modifiers mod = ReadMethodModifiers (mb, declaringType);
345                         TypeParameterSpec[] tparams;
346
347                         var parameters = CreateParameters (declaringType, mb.GetParameters (), mb);
348
349                         if (mb.IsGenericMethod) {
350                                 if (!mb.IsGenericMethodDefinition)
351                                         throw new NotSupportedException ("assert");
352
353                                 tparams = CreateGenericParameters (0, mb.GetGenericArguments ());
354                         } else {
355                                 tparams = null;
356                         }
357
358                         MemberKind kind;
359                         TypeSpec returnType;
360                         if (mb.MemberType == MemberTypes.Constructor) {
361                                 kind = MemberKind.Constructor;
362                                 returnType = module.Compiler.BuiltinTypes.Void;
363                         } else {
364                                 //
365                                 // Detect operators and destructors
366                                 //
367                                 string name = mb.Name;
368                                 kind = MemberKind.Method;
369                                 if (tparams == null && !mb.DeclaringType.IsInterface && name.Length > 6) {
370                                         if ((mod & (Modifiers.STATIC | Modifiers.PUBLIC)) == (Modifiers.STATIC | Modifiers.PUBLIC)) {
371                                                 if (name[2] == '_' && name[1] == 'p' && name[0] == 'o') {
372                                                         var op_type = Operator.GetType (name);
373                                                         if (op_type.HasValue && parameters.Count > 0 && parameters.Count < 3) {
374                                                                 kind = MemberKind.Operator;
375                                                         }
376                                                 }
377                                         } else if (parameters.IsEmpty && name == Destructor.MetadataName) {
378                                                 kind = MemberKind.Destructor;
379                                                 if (declaringType.BuiltinType == BuiltinTypeSpec.Type.Object) {
380                                                         mod &= ~Modifiers.OVERRIDE;
381                                                         mod |= Modifiers.VIRTUAL;
382                                                 }
383                                         }
384                                 }
385
386                                 var mi = (MethodInfo) mb;
387                                 returnType = ImportType (mi.ReturnType, new DynamicTypeReader (mi.ReturnParameter));
388
389                                 // Cannot set to OVERRIDE without full hierarchy checks
390                                 // this flag indicates that the method could be override
391                                 // but further validation is needed
392                                 if ((mod & Modifiers.OVERRIDE) != 0) {
393                                         bool is_real_override = false;
394                                         if (kind == MemberKind.Method && declaringType.BaseType != null) {
395                                                 var btype = declaringType.BaseType;
396                                                 if (IsOverrideMethodBaseTypeAccessible (btype)) {
397                                                         var filter = MemberFilter.Method (name, tparams != null ? tparams.Length : 0, parameters, null);
398                                                         var candidate = MemberCache.FindMember (btype, filter, BindingRestriction.None);
399
400                                                         //
401                                                         // For imported class method do additional validation to be sure that metadata
402                                                         // override flag was correct
403                                                         // 
404                                                         // Difference between protected internal and protected is ok
405                                                         //
406                                                         const Modifiers conflict_mask = Modifiers.AccessibilityMask & ~Modifiers.INTERNAL;
407                                                         if (candidate != null && (candidate.Modifiers & conflict_mask) == (mod & conflict_mask) && !candidate.IsStatic) {
408                                                                 is_real_override = true;
409                                                         }
410                                                 }
411                                         }
412
413                                         if (!is_real_override) {
414                                                 mod &= ~Modifiers.OVERRIDE;
415                                                 if ((mod & Modifiers.SEALED) != 0)
416                                                         mod &= ~Modifiers.SEALED;
417                                                 else
418                                                         mod |= Modifiers.VIRTUAL;
419                                         }
420                                 }
421                         }
422
423                         IMemberDefinition definition;
424                         if (tparams != null) {
425                                 var gmd = new ImportedGenericMethodDefinition ((MethodInfo) mb, returnType, parameters, tparams, this);
426                                 foreach (var tp in gmd.TypeParameters) {
427                                         ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
428                                 }
429
430                                 definition = gmd;
431                         } else {
432                                 definition = new ImportedParameterMemberDefinition (mb, returnType, parameters, this);
433                         }
434
435                         MethodSpec ms = new MethodSpec (kind, declaringType, definition, returnType, mb, parameters, mod);
436                         if (tparams != null)
437                                 ms.IsGeneric = true;
438
439                         return ms;
440                 }
441
442                 bool IsOverrideMethodBaseTypeAccessible (TypeSpec baseType)
443                 {
444                         switch (baseType.Modifiers & Modifiers.AccessibilityMask) {
445                         case Modifiers.PUBLIC:
446                                 return true;
447                         case Modifiers.INTERNAL:
448                                 //
449                                 // Check whether imported method in base type is accessible from compiled
450                                 // context
451                                 //
452                                 return baseType.MemberDefinition.IsInternalAsPublic (module.DeclaringAssembly);
453                         case Modifiers.PRIVATE:
454                                 return false;
455                         default:
456                                 // protected
457                                 // protected internal
458                                 // 
459                                 // Method accessibility checks will be done later based on context
460                                 // where the method is called (CS0122 error will be reported for inaccessible)
461                                 //
462                                 return true;
463                         }
464                 }
465
466                 //
467                 // Imports System.Reflection parameters
468                 //
469                 AParametersCollection CreateParameters (TypeSpec parent, ParameterInfo[] pi, MethodBase method)
470                 {
471                         int varargs = method != null && (method.CallingConvention & CallingConventions.VarArgs) != 0 ? 1 : 0;
472
473                         if (pi.Length == 0 && varargs == 0)
474                                 return ParametersCompiled.EmptyReadOnlyParameters;
475
476                         TypeSpec[] types = new TypeSpec[pi.Length + varargs];
477                         IParameterData[] par = new IParameterData[pi.Length + varargs];
478                         bool is_params = false;
479                         for (int i = 0; i < pi.Length; i++) {
480                                 ParameterInfo p = pi[i];
481                                 Parameter.Modifier mod = 0;
482                                 Expression default_value = null;
483                                 if (p.ParameterType.IsByRef) {
484                                         if ((p.Attributes & (ParameterAttributes.Out | ParameterAttributes.In)) == ParameterAttributes.Out)
485                                                 mod = Parameter.Modifier.OUT;
486                                         else
487                                                 mod = Parameter.Modifier.REF;
488
489                                         //
490                                         // Strip reference wrapping
491                                         //
492                                         var el = p.ParameterType.GetElementType ();
493                                         types[i] = ImportType (el, new DynamicTypeReader (p));  // TODO: 1-based positio to be csc compatible
494                                 } else if (i == 0 && method.IsStatic && (parent.Modifiers & Modifiers.METHOD_EXTENSION) != 0 &&
495                                         HasAttribute (CustomAttributeData.GetCustomAttributes (method), "ExtensionAttribute", CompilerServicesNamespace)) {
496                                         mod = Parameter.Modifier.This;
497                                         types[i] = ImportType (p.ParameterType);
498                                 } else {
499                                         types[i] = ImportType (p.ParameterType, new DynamicTypeReader (p));
500
501                                         if (i >= pi.Length - 2 && types[i] is ArrayContainer) {
502                                                 if (HasAttribute (CustomAttributeData.GetCustomAttributes (p), "ParamArrayAttribute", "System")) {
503                                                         mod = Parameter.Modifier.PARAMS;
504                                                         is_params = true;
505                                                 }
506                                         }
507
508                                         if (!is_params && p.IsOptional) {
509                                                 object value = p.RawDefaultValue;
510                                                 var ptype = types[i];
511                                                 if ((p.Attributes & ParameterAttributes.HasDefault) != 0 && ptype.Kind != MemberKind.TypeParameter && (value != null || TypeSpec.IsReferenceType (ptype))) {
512                                                         if (value == null) {
513                                                                 default_value = Constant.CreateConstantFromValue (ptype, null, Location.Null);
514                                                         } else {
515                                                                 default_value = ImportParameterConstant (value);
516
517                                                                 if (ptype.IsEnum) {
518                                                                         default_value = new EnumConstant ((Constant) default_value, ptype);
519                                                                 }
520                                                         }
521
522                                                         var attrs = CustomAttributeData.GetCustomAttributes (p);
523                                                         for (int ii = 0; ii < attrs.Count; ++ii) {
524                                                                 var attr = attrs[ii];
525                                                                 var dt = attr.Constructor.DeclaringType;
526                                                                 if (dt.Namespace != CompilerServicesNamespace)
527                                                                         continue;
528
529                                                                 if (dt.Name == "CallerLineNumberAttribute" && (ptype.BuiltinType == BuiltinTypeSpec.Type.Int || Convert.ImplicitNumericConversionExists (module.Compiler.BuiltinTypes.Int, ptype)))
530                                                                         mod |= Parameter.Modifier.CallerLineNumber;
531                                                                 else if (dt.Name == "CallerFilePathAttribute" && Convert.ImplicitReferenceConversionExists (module.Compiler.BuiltinTypes.String, ptype))
532                                                                         mod |= Parameter.Modifier.CallerFilePath;
533                                                                 else if (dt.Name == "CallerMemberNameAttribute" && Convert.ImplicitReferenceConversionExists (module.Compiler.BuiltinTypes.String, ptype))
534                                                                         mod |= Parameter.Modifier.CallerMemberName;
535                                                         }
536                                                 } else if (value == Missing.Value) {
537                                                         default_value = EmptyExpression.MissingValue;
538                                                 } else if (value == null) {
539                                                         default_value = new DefaultValueExpression (new TypeExpression (ptype, Location.Null), Location.Null);
540                                                 } else if (ptype.BuiltinType == BuiltinTypeSpec.Type.Decimal) {
541                                                         default_value = ImportParameterConstant (value);
542                                                 }
543                                         }
544                                 }
545
546                                 par[i] = new ParameterData (p.Name, mod, default_value);
547                         }
548
549                         if (varargs != 0) {
550                                 par[par.Length - 1] = new ArglistParameter (Location.Null);
551                                 types[types.Length - 1] = InternalType.Arglist;
552                         }
553
554                         return method != null ?
555                                 new ParametersImported (par, types, varargs != 0, is_params) :
556                                 new ParametersImported (par, types, is_params);
557                 }
558
559                 //
560                 // Returns null when the property is not valid C# property
561                 //
562                 public PropertySpec CreateProperty (PropertyInfo pi, TypeSpec declaringType, MethodSpec get, MethodSpec set)
563                 {
564                         Modifiers mod = 0;
565                         AParametersCollection param = null;
566                         TypeSpec type = null;
567                         if (get != null) {
568                                 mod = get.Modifiers;
569                                 param = get.Parameters;
570                                 type = get.ReturnType;
571                         }
572
573                         bool is_valid_property = true;
574                         if (set != null) {
575                                 if (set.ReturnType.Kind != MemberKind.Void)
576                                         is_valid_property = false;
577
578                                 var set_param_count = set.Parameters.Count - 1;
579
580                                 if (set_param_count < 0) {
581                                         set_param_count = 0;
582                                         is_valid_property = false;
583                                 }
584
585                                 var set_type = set.Parameters.Types[set_param_count];
586
587                                 if (mod == 0) {
588                                         AParametersCollection set_based_param;
589
590                                         if (set_param_count == 0) {
591                                                 set_based_param = ParametersCompiled.EmptyReadOnlyParameters;
592                                         } else {
593                                                 //
594                                                 // Create indexer parameters based on setter method parameters (the last parameter has to be removed)
595                                                 //
596                                                 var data = new IParameterData[set_param_count];
597                                                 var types = new TypeSpec[set_param_count];
598                                                 Array.Copy (set.Parameters.FixedParameters, data, set_param_count);
599                                                 Array.Copy (set.Parameters.Types, types, set_param_count);
600                                                 set_based_param = new ParametersImported (data, types, set.Parameters.HasParams);
601                                         }
602
603                                         mod = set.Modifiers;
604                                         param = set_based_param;
605                                         type = set_type;
606                                 } else {
607                                         if (set_param_count != get.Parameters.Count)
608                                                 is_valid_property = false;
609
610                                         if (get.ReturnType != set_type)
611                                                 is_valid_property = false;
612
613                                         // Possible custom accessor modifiers
614                                         if ((mod & Modifiers.AccessibilityMask) != (set.Modifiers & Modifiers.AccessibilityMask)) {
615                                                 var get_acc = mod & Modifiers.AccessibilityMask;
616                                                 if (get_acc != Modifiers.PUBLIC) {
617                                                         var set_acc = set.Modifiers & Modifiers.AccessibilityMask;
618                                                         // If the accessor modifiers are not same, do extra restriction checks
619                                                         if (get_acc != set_acc) {
620                                                                 var get_restr = ModifiersExtensions.IsRestrictedModifier (get_acc, set_acc);
621                                                                 var set_restr = ModifiersExtensions.IsRestrictedModifier (set_acc, get_acc);
622                                                                 if (get_restr && set_restr) {
623                                                                         is_valid_property = false; // Neither is more restrictive
624                                                                 }
625
626                                                                 if (get_restr) {
627                                                                         mod &= ~Modifiers.AccessibilityMask;
628                                                                         mod |= set_acc;
629                                                                 }
630                                                         }
631                                                 }
632                                         }
633                                 }
634                         }
635
636                         PropertySpec spec = null;
637                         if (!param.IsEmpty) {
638                                 if (is_valid_property) {
639                                         var index_name = declaringType.MemberDefinition.GetAttributeDefaultMember ();
640                                         if (index_name == null) {
641                                                 is_valid_property = false;
642                                         } else {
643                                                 if (get != null) {
644                                                         if (get.IsStatic)
645                                                                 is_valid_property = false;
646                                                         if (get.Name.IndexOf (index_name, StringComparison.Ordinal) != 4)
647                                                                 is_valid_property = false;
648                                                 }
649                                                 if (set != null) {
650                                                         if (set.IsStatic)
651                                                                 is_valid_property = false;
652                                                         if (set.Name.IndexOf (index_name, StringComparison.Ordinal) != 4)
653                                                                 is_valid_property = false;
654                                                 }
655                                         }
656
657                                         if (is_valid_property) {
658                                                 spec = new IndexerSpec (declaringType, new ImportedParameterMemberDefinition (pi, type, param, this), type, param, pi, mod);
659                                         } else if (declaringType.MemberDefinition.IsComImport && param.FixedParameters[0].HasDefaultValue) {
660                                                 //
661                                                 // Enables support for properties with parameters (must have default value) of COM-imported types
662                                                 //
663                                                 is_valid_property = true;
664
665                                                 for (int i = 0; i < param.FixedParameters.Length; ++i) {
666                                                         if (!param.FixedParameters[i].HasDefaultValue) {
667                                                                 is_valid_property = false;
668                                                                 break;
669                                                         }
670                                                 }
671                                         }
672                                 }
673                         }
674
675                         if (spec == null)
676                                 spec = new PropertySpec (MemberKind.Property, declaringType, new ImportedMemberDefinition (pi, type, this), type, pi, mod);
677
678                         if (!is_valid_property) {
679                                 spec.IsNotCSharpCompatible = true;
680                                 return spec;
681                         }
682
683                         if (set != null)
684                                 spec.Set = set;
685                         if (get != null)
686                                 spec.Get = get;
687
688                         return spec;
689                 }
690
691                 public TypeSpec CreateType (MetaType type)
692                 {
693                         return CreateType (type, new DynamicTypeReader (), true);
694                 }
695
696                 public TypeSpec CreateNestedType (MetaType type, TypeSpec declaringType)
697                 {
698                         return CreateType (type, declaringType, new DynamicTypeReader (type), false);
699                 }
700
701                 TypeSpec CreateType (MetaType type, DynamicTypeReader dtype, bool canImportBaseType)
702                 {
703                         TypeSpec declaring_type;
704                         if (type.IsNested && !type.IsGenericParameter)
705                                 declaring_type = CreateType (type.DeclaringType, new DynamicTypeReader (type.DeclaringType), true);
706                         else
707                                 declaring_type = null;
708
709                         return CreateType (type, declaring_type, dtype, canImportBaseType);
710                 }
711
712                 protected TypeSpec CreateType (MetaType type, TypeSpec declaringType, DynamicTypeReader dtype, bool canImportBaseType)
713                 {
714                         TypeSpec spec;
715                         if (import_cache.TryGetValue (type, out spec)) {
716                                 if (spec.BuiltinType == BuiltinTypeSpec.Type.Object) {
717                                         if (dtype.IsDynamicObject (this))
718                                                 return module.Compiler.BuiltinTypes.Dynamic;
719
720                                         return spec;
721                                 }
722
723                                 if (!spec.IsGeneric || type.IsGenericTypeDefinition)
724                                         return spec;
725
726                                 if (!dtype.HasDynamicAttribute (this))
727                                         return spec;
728
729                                 // We've found same object in the cache but this one has a dynamic custom attribute
730                                 // and it's most likely dynamic version of same type IFoo<object> agains IFoo<dynamic>
731                                 // Do type resolve process again in that case
732
733                                 // TODO: Handle cases where they still unify
734                         }
735
736                         if (IsMissingType (type)) {
737                                 spec = new TypeSpec (MemberKind.MissingType, declaringType, new ImportedTypeDefinition (type, this), type, Modifiers.PUBLIC);
738                                 spec.MemberCache = MemberCache.Empty;
739                                 import_cache.Add (type, spec);
740                                 return spec;
741                         }
742
743                         if (type.IsGenericType && !type.IsGenericTypeDefinition) {
744                                 var type_def = type.GetGenericTypeDefinition ();
745
746                                 // Generic type definition can also be forwarded
747                                 if (compiled_types.TryGetValue (type_def, out spec))
748                                         return spec;
749
750                                 var targs = CreateGenericArguments (0, type.GetGenericArguments (), dtype);
751                                 if (declaringType == null) {
752                                         // Simple case, no nesting
753                                         spec = CreateType (type_def, null, new DynamicTypeReader (), canImportBaseType);
754                                         spec = spec.MakeGenericType (module, targs);
755                                 } else {
756                                         //
757                                         // Nested type case, converting .NET types like
758                                         // A`1.B`1.C`1<int, long, string> to typespec like
759                                         // A<int>.B<long>.C<string>
760                                         //
761                                         var nested_hierarchy = new List<TypeSpec> ();
762                                         while (declaringType.IsNested) {
763                                                 nested_hierarchy.Add (declaringType);
764                                                 declaringType = declaringType.DeclaringType;
765                                         }
766
767                                         int targs_pos = 0;
768                                         if (declaringType.Arity > 0) {
769                                                 spec = declaringType.MakeGenericType (module, targs.Skip (targs_pos).Take (declaringType.Arity).ToArray ());
770                                                 targs_pos = spec.Arity;
771                                         } else {
772                                                 spec = declaringType;
773                                         }
774
775                                         for (int i = nested_hierarchy.Count; i != 0; --i) {
776                                                 var t = nested_hierarchy [i - 1];
777                                                 spec = MemberCache.FindNestedType (spec, t.Name, t.Arity);
778                                                 if (t.Arity > 0) {
779                                                         spec = spec.MakeGenericType (module, targs.Skip (targs_pos).Take (spec.Arity).ToArray ());
780                                                         targs_pos += t.Arity;
781                                                 }
782                                         }
783
784                                         string name = type.Name;
785                                         int index = name.IndexOf ('`');
786                                         if (index > 0)
787                                                 name = name.Substring (0, index);
788
789                                         spec = MemberCache.FindNestedType (spec, name, targs.Length - targs_pos);
790                                         if (spec == null)
791                                                 return null;
792
793                                         if (spec.Arity > 0) {
794                                                 spec = spec.MakeGenericType (module, targs.Skip (targs_pos).ToArray ());
795                                         }
796                                 }
797
798                                 // Don't add generic type with dynamic arguments, they can interfere with same type
799                                 // using object type arguments
800                                 if (!spec.HasDynamicElement) {
801
802                                         // Add to reading cache to speed up reading
803                                         if (!import_cache.ContainsKey (type))
804                                                 import_cache.Add (type, spec);
805                                 }
806
807                                 return spec;
808                         }
809
810                         Modifiers mod;
811                         MemberKind kind;
812
813                         var ma = type.Attributes;
814                         switch (ma & TypeAttributes.VisibilityMask) {
815                         case TypeAttributes.Public:
816                         case TypeAttributes.NestedPublic:
817                                 mod = Modifiers.PUBLIC;
818                                 break;
819                         case TypeAttributes.NestedPrivate:
820                                 mod = Modifiers.PRIVATE;
821                                 break;
822                         case TypeAttributes.NestedFamily:
823                                 mod = Modifiers.PROTECTED;
824                                 break;
825                         case TypeAttributes.NestedFamORAssem:
826                                 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
827                                 break;
828                         default:
829                                 mod = Modifiers.INTERNAL;
830                                 break;
831                         }
832
833                         if ((ma & TypeAttributes.Interface) != 0) {
834                                 kind = MemberKind.Interface;
835                         } else if (type.IsGenericParameter) {
836                                 kind = MemberKind.TypeParameter;
837                         } else {
838                                 var base_type = type.BaseType;
839                                 if (base_type == null || (ma & TypeAttributes.Abstract) != 0) {
840                                         kind = MemberKind.Class;
841                                 } else {
842                                         kind = DetermineKindFromBaseType (base_type);
843                                         if (kind == MemberKind.Struct || kind == MemberKind.Delegate) {
844                                                 mod |= Modifiers.SEALED;
845                                         }
846                                 }
847
848                                 if (kind == MemberKind.Class) {
849                                         if ((ma & TypeAttributes.Sealed) != 0) {
850                                                 mod |= Modifiers.SEALED;
851                                                 if ((ma & TypeAttributes.Abstract) != 0)
852                                                         mod |= Modifiers.STATIC;
853                                         } else if ((ma & TypeAttributes.Abstract) != 0) {
854                                                 mod |= Modifiers.ABSTRACT;
855                                         }
856                                 }
857                         }
858
859                         var definition = new ImportedTypeDefinition (type, this);
860                         TypeSpec pt;
861
862                         if (kind == MemberKind.Enum) {
863                                 const BindingFlags underlying_member = BindingFlags.DeclaredOnly |
864                                         BindingFlags.Instance |
865                                         BindingFlags.Public | BindingFlags.NonPublic;
866
867                                 var type_members = type.GetFields (underlying_member);
868                                 foreach (var type_member in type_members) {
869                                         spec = new EnumSpec (declaringType, definition, CreateType (type_member.FieldType), type, mod);
870                                         break;
871                                 }
872
873                                 if (spec == null)
874                                         kind = MemberKind.Class;
875
876                         } else if (kind == MemberKind.TypeParameter) {
877                                 spec = CreateTypeParameter (type, declaringType);
878                         } else if (type.IsGenericTypeDefinition) {
879                                 definition.TypeParameters = CreateGenericParameters (type, declaringType);
880                         } else if (compiled_types.TryGetValue (type, out pt)) {
881                                 //
882                                 // Same type was found in inside compiled types. It's
883                                 // either build-in type or forward referenced typed
884                                 // which point into just compiled assembly.
885                                 //
886                                 spec = pt;
887                                 BuiltinTypeSpec bts = pt as BuiltinTypeSpec;
888                                 if (bts != null)
889                                         bts.SetDefinition (definition, type, mod);
890                         }
891
892                         if (spec == null)
893                                 spec = new TypeSpec (kind, declaringType, definition, type, mod);
894
895                         import_cache.Add (type, spec);
896
897                         if (kind == MemberKind.TypeParameter) {
898                                 if (canImportBaseType)
899                                         ImportTypeParameterTypeConstraints ((TypeParameterSpec) spec, type);
900
901                                 return spec;
902                         }
903
904                         //
905                         // Two stage setup as the base type can be inflated declaring type or
906                         // another nested type inside same declaring type which has not been
907                         // loaded, therefore we can import a base type of nested types once
908                         // the types have been imported
909                         //
910                         if (canImportBaseType)
911                                 ImportTypeBase (spec, type);
912
913                         return spec;
914                 }
915
916                 public IAssemblyDefinition GetAssemblyDefinition (Assembly assembly)
917                 {
918                         IAssemblyDefinition found;
919                         if (!assembly_2_definition.TryGetValue (assembly, out found)) {
920
921                                 // This can happen in dynamic context only
922                                 var def = new ImportedAssemblyDefinition (assembly);
923                                 assembly_2_definition.Add (assembly, def);
924                                 def.ReadAttributes ();
925                                 found = def;
926                         }
927
928                         return found;
929                 }
930
931                 public void ImportTypeBase (MetaType type)
932                 {
933                         TypeSpec spec = import_cache[type];
934                         if (spec != null)
935                                 ImportTypeBase (spec, type);
936                 }
937
938                 TypeParameterSpec CreateTypeParameter (MetaType type, TypeSpec declaringType)
939                 {
940                         Variance variance;
941                         switch (type.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) {
942                         case GenericParameterAttributes.Covariant:
943                                 variance = Variance.Covariant;
944                                 break;
945                         case GenericParameterAttributes.Contravariant:
946                                 variance = Variance.Contravariant;
947                                 break;
948                         default:
949                                 variance = Variance.None;
950                                 break;
951                         }
952
953                         SpecialConstraint special = SpecialConstraint.None;
954                         var import_special = type.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask;
955
956                         if ((import_special & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) {
957                                 special |= SpecialConstraint.Struct;
958                         } else if ((import_special & GenericParameterAttributes.DefaultConstructorConstraint) != 0) {
959                                 special = SpecialConstraint.Constructor;
960                         }
961
962                         if ((import_special & GenericParameterAttributes.ReferenceTypeConstraint) != 0) {
963                                 special |= SpecialConstraint.Class;
964                         }
965
966                         TypeParameterSpec spec;
967                         var def = new ImportedTypeParameterDefinition (type, this);
968                         if (type.DeclaringMethod != null) {
969                                 spec = new TypeParameterSpec (type.GenericParameterPosition, def, special, variance, type);
970                         } else {
971                                 spec = new TypeParameterSpec (declaringType, type.GenericParameterPosition, def, special, variance, type);
972                         }
973
974                         return spec;
975                 }
976
977                 //
978                 // Test for a custom attribute type match. Custom attributes are not really predefined globaly 
979                 // they can be assembly specific therefore we do check based on names only
980                 //
981                 public static bool HasAttribute (IList<CustomAttributeData> attributesData, string attrName, string attrNamespace)
982                 {
983                         if (attributesData.Count == 0)
984                                 return false;
985
986                         foreach (var attr in attributesData) {
987                                 var dt = attr.Constructor.DeclaringType;
988                                 if (dt.Name == attrName && dt.Namespace == attrNamespace)
989                                         return true;
990                         }
991
992                         return false;
993                 }
994
995                 void ImportTypeBase (TypeSpec spec, MetaType type)
996                 {
997                         if (spec.Kind == MemberKind.Interface)
998                                 spec.BaseType = module.Compiler.BuiltinTypes.Object;
999                         else if (type.BaseType != null) {
1000                                 TypeSpec base_type;
1001                                 if (!IsMissingType (type.BaseType) && type.BaseType.IsGenericType)
1002                                         base_type = CreateType (type.BaseType, new DynamicTypeReader (type), true);
1003                                 else
1004                                         base_type = CreateType (type.BaseType);
1005
1006                                 spec.BaseType = base_type;
1007                         }
1008
1009                         if (spec.MemberDefinition.TypeParametersCount > 0) {
1010                                 foreach (var tp in spec.MemberDefinition.TypeParameters) {
1011                                         ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
1012                                 }
1013                         }
1014                 }
1015
1016                 protected void ImportTypes (MetaType[] types, Namespace targetNamespace, bool importExtensionTypes)
1017                 {
1018                         Namespace ns = targetNamespace;
1019                         string prev_namespace = null;
1020                         foreach (var t in types) {
1021                                 if (t == null)
1022                                         continue;
1023
1024                                 // Be careful not to trigger full parent type loading
1025                                 if (t.MemberType == MemberTypes.NestedType)
1026                                         continue;
1027
1028                                 if (t.Name[0] == '<')
1029                                         continue;
1030
1031                                 var it = CreateType (t, null, new DynamicTypeReader (t), true);
1032                                 if (it == null)
1033                                         continue;
1034
1035                                 if (prev_namespace != t.Namespace) {
1036                                         ns = t.Namespace == null ? targetNamespace : targetNamespace.GetNamespace (t.Namespace, true);
1037                                         prev_namespace = t.Namespace;
1038                                 }
1039
1040                                 // Cannot rely on assembly level Extension attribute or static modifier because they
1041                                 // are not followed by other compilers (e.g. F#).
1042                                 if (it.IsClass && it.Arity == 0 && importExtensionTypes &&
1043                                         HasAttribute (CustomAttributeData.GetCustomAttributes (t), "ExtensionAttribute", CompilerServicesNamespace)) {
1044                                         it.SetExtensionMethodContainer ();
1045                                 }
1046
1047                                 ns.AddType (module, it);
1048                         }
1049                 }
1050
1051                 void ImportTypeParameterTypeConstraints (TypeParameterSpec spec, MetaType type)
1052                 {
1053                         var constraints = type.GetGenericParameterConstraints ();
1054                         List<TypeSpec> tparams = null;
1055                         foreach (var ct in constraints) {
1056                                 if (ct.IsGenericParameter) {
1057                                         if (tparams == null)
1058                                                 tparams = new List<TypeSpec> ();
1059
1060                                         tparams.Add (CreateType (ct));
1061                                         continue;
1062                                 }
1063
1064                                 var constraint_type = CreateType (ct);
1065                                 if (constraint_type.IsClass) {
1066                                         spec.BaseType = constraint_type;
1067                                         continue;
1068                                 }
1069
1070                                 spec.AddInterface (constraint_type);
1071                         }
1072
1073                         if (spec.BaseType == null)
1074                                 spec.BaseType = module.Compiler.BuiltinTypes.Object;
1075
1076                         if (tparams != null)
1077                                 spec.TypeArguments = tparams.ToArray ();
1078                 }
1079
1080                 Constant ImportParameterConstant (object value)
1081                 {
1082                         //
1083                         // Get type of underlying value as int constant can be used for object
1084                         // parameter type. This is not allowed in C# but other languages can do that
1085                         //
1086                         var types = module.Compiler.BuiltinTypes;
1087                         switch (System.Type.GetTypeCode (value.GetType ())) {
1088                         case TypeCode.Boolean:
1089                                 return new BoolConstant (types, (bool) value, Location.Null);
1090                         case TypeCode.Byte:
1091                                 return new ByteConstant (types, (byte) value, Location.Null);
1092                         case TypeCode.Char:
1093                                 return new CharConstant (types, (char) value, Location.Null);
1094                         case TypeCode.Decimal:
1095                                 return new DecimalConstant (types, (decimal) value, Location.Null);
1096                         case TypeCode.Double:
1097                                 return new DoubleConstant (types, (double) value, Location.Null);
1098                         case TypeCode.Int16:
1099                                 return new ShortConstant (types, (short) value, Location.Null);
1100                         case TypeCode.Int32:
1101                                 return new IntConstant (types, (int) value, Location.Null);
1102                         case TypeCode.Int64:
1103                                 return new LongConstant (types, (long) value, Location.Null);
1104                         case TypeCode.SByte:
1105                                 return new SByteConstant (types, (sbyte) value, Location.Null);
1106                         case TypeCode.Single:
1107                                 return new FloatConstant (types, (float) value, Location.Null);
1108                         case TypeCode.String:
1109                                 return new StringConstant (types, (string) value, Location.Null);
1110                         case TypeCode.UInt16:
1111                                 return new UShortConstant (types, (ushort) value, Location.Null);
1112                         case TypeCode.UInt32:
1113                                 return new UIntConstant (types, (uint) value, Location.Null);
1114                         case TypeCode.UInt64:
1115                                 return new ULongConstant (types, (ulong) value, Location.Null);
1116                         }
1117
1118                         throw new NotImplementedException (value.GetType ().ToString ());
1119                 }
1120
1121                 public TypeSpec ImportType (MetaType type)
1122                 {
1123                         return ImportType (type, new DynamicTypeReader (type));
1124                 }
1125
1126                 TypeSpec ImportType (MetaType type, DynamicTypeReader dtype)
1127                 {
1128                         if (type.HasElementType) {
1129                                 var element = type.GetElementType ();
1130                                 ++dtype.Position;
1131                                 var spec = ImportType (element, dtype);
1132
1133                                 if (type.IsArray)
1134                                         return ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
1135                                 if (type.IsByRef)
1136                                         return ReferenceContainer.MakeType (module, spec);
1137                                 if (type.IsPointer)
1138                                         return PointerContainer.MakeType (module, spec);
1139
1140                                 throw new NotImplementedException ("Unknown element type " + type.ToString ());
1141                         }
1142
1143                         return CreateType (type, dtype, true);
1144                 }
1145
1146                 static bool IsMissingType (MetaType type)
1147                 {
1148 #if STATIC
1149                         return type.__IsMissing;
1150 #else
1151                         return false;
1152 #endif
1153                 }
1154
1155                 //
1156                 // Decimal constants cannot be encoded in the constant blob, and thus are marked
1157                 // as IsInitOnly ('readonly' in C# parlance).  We get its value from the 
1158                 // DecimalConstantAttribute metadata.
1159                 //
1160                 Constant ReadDecimalConstant (IList<CustomAttributeData> attrs)
1161                 {
1162                         if (attrs.Count == 0)
1163                                 return null;
1164
1165                         foreach (var ca in attrs) {
1166                                 var dt = ca.Constructor.DeclaringType;
1167                                 if (dt.Name != "DecimalConstantAttribute" || dt.Namespace != CompilerServicesNamespace)
1168                                         continue;
1169
1170                                 var value = new decimal (
1171                                         (int) (uint) ca.ConstructorArguments[4].Value,
1172                                         (int) (uint) ca.ConstructorArguments[3].Value,
1173                                         (int) (uint) ca.ConstructorArguments[2].Value,
1174                                         (byte) ca.ConstructorArguments[1].Value != 0,
1175                                         (byte) ca.ConstructorArguments[0].Value);
1176
1177                                 return new DecimalConstant (module.Compiler.BuiltinTypes, value, Location.Null);
1178                         }
1179
1180                         return null;
1181                 }
1182
1183                 static Modifiers ReadMethodModifiers (MethodBase mb, TypeSpec declaringType)
1184                 {
1185                         Modifiers mod;
1186                         var ma = mb.Attributes;
1187                         switch (ma & MethodAttributes.MemberAccessMask) {
1188                         case MethodAttributes.Public:
1189                                 mod = Modifiers.PUBLIC;
1190                                 break;
1191                         case MethodAttributes.Assembly:
1192                                 mod = Modifiers.INTERNAL;
1193                                 break;
1194                         case MethodAttributes.Family:
1195                                 mod = Modifiers.PROTECTED;
1196                                 break;
1197                         case MethodAttributes.FamORAssem:
1198                                 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
1199                                 break;
1200                         default:
1201                                 mod = Modifiers.PRIVATE;
1202                                 break;
1203                         }
1204
1205                         if ((ma & MethodAttributes.Static) != 0) {
1206                                 mod |= Modifiers.STATIC;
1207                                 return mod;
1208                         }
1209                         if ((ma & MethodAttributes.Abstract) != 0 && declaringType.IsClass) {
1210                                 mod |= Modifiers.ABSTRACT;
1211                                 return mod;
1212                         }
1213
1214                         // It can be sealed and override
1215                         if ((ma & MethodAttributes.Final) != 0)
1216                                 mod |= Modifiers.SEALED;
1217
1218                         if ((ma & MethodAttributes.Virtual) != 0) {
1219                                 // Not every member can be detected based on MethodAttribute, we
1220                                 // set virtual or non-virtual only when we are certain. Further checks
1221                                 // to really find out what `virtual' means for this member are done
1222                                 // later
1223                                 if ((ma & MethodAttributes.NewSlot) != 0) {
1224                                         if ((mod & Modifiers.SEALED) != 0) {
1225                                                 mod &= ~Modifiers.SEALED;
1226                                         } else {
1227                                                 mod |= Modifiers.VIRTUAL;
1228                                         }
1229                                 } else {
1230                                         mod |= Modifiers.OVERRIDE;
1231                                 }
1232                         }
1233
1234                         return mod;
1235                 }
1236         }
1237
1238         abstract class ImportedDefinition : IMemberDefinition
1239         {
1240                 protected class AttributesBag
1241                 {
1242                         public static readonly AttributesBag Default = new AttributesBag ();
1243
1244                         public AttributeUsageAttribute AttributeUsage;
1245                         public ObsoleteAttribute Obsolete;
1246                         public string[] Conditionals;
1247                         public string DefaultIndexerName;
1248                         public bool? CLSAttributeValue;
1249                         public TypeSpec CoClass;
1250                         
1251                         public static AttributesBag Read (MemberInfo mi, MetadataImporter importer)
1252                         {
1253                                 AttributesBag bag = null;
1254                                 List<string> conditionals = null;
1255
1256                                 // It should not throw any loading exception
1257                                 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (mi);
1258
1259                                 foreach (var a in attrs) {
1260                                         var dt = a.Constructor.DeclaringType;
1261                                         string name = dt.Name;
1262                                         if (name == "ObsoleteAttribute") {
1263                                                 if (dt.Namespace != "System")
1264                                                         continue;
1265
1266                                                 if (bag == null)
1267                                                         bag = new AttributesBag ();
1268
1269                                                 var args = a.ConstructorArguments;
1270
1271                                                 if (args.Count == 1) {
1272                                                         bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value);
1273                                                 } else if (args.Count == 2) {
1274                                                         bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value, (bool) args[1].Value);
1275                                                 } else {
1276                                                         bag.Obsolete = new ObsoleteAttribute ();
1277                                                 }
1278
1279                                                 continue;
1280                                         }
1281
1282                                         if (name == "ConditionalAttribute") {
1283                                                 if (dt.Namespace != "System.Diagnostics")
1284                                                         continue;
1285
1286                                                 if (bag == null)
1287                                                         bag = new AttributesBag ();
1288
1289                                                 if (conditionals == null)
1290                                                         conditionals = new List<string> (2);
1291
1292                                                 conditionals.Add ((string) a.ConstructorArguments[0].Value);
1293                                                 continue;
1294                                         }
1295
1296                                         if (name == "CLSCompliantAttribute") {
1297                                                 if (dt.Namespace != "System")
1298                                                         continue;
1299
1300                                                 if (bag == null)
1301                                                         bag = new AttributesBag ();
1302
1303                                                 bag.CLSAttributeValue = (bool) a.ConstructorArguments[0].Value;
1304                                                 continue;
1305                                         }
1306
1307                                         // Type only attributes
1308                                         if (mi.MemberType == MemberTypes.TypeInfo || mi.MemberType == MemberTypes.NestedType) {
1309                                                 if (name == "DefaultMemberAttribute") {
1310                                                         if (dt.Namespace != "System.Reflection")
1311                                                                 continue;
1312
1313                                                         if (bag == null)
1314                                                                 bag = new AttributesBag ();
1315
1316                                                         bag.DefaultIndexerName = (string) a.ConstructorArguments[0].Value;
1317                                                         continue;
1318                                                 }
1319
1320                                                 if (name == "AttributeUsageAttribute") {
1321                                                         if (dt.Namespace != "System")
1322                                                                 continue;
1323
1324                                                         if (bag == null)
1325                                                                 bag = new AttributesBag ();
1326
1327                                                         bag.AttributeUsage = new AttributeUsageAttribute ((AttributeTargets) a.ConstructorArguments[0].Value);
1328                                                         foreach (var named in a.NamedArguments) {
1329                                                                 if (named.MemberInfo.Name == "AllowMultiple")
1330                                                                         bag.AttributeUsage.AllowMultiple = (bool) named.TypedValue.Value;
1331                                                                 else if (named.MemberInfo.Name == "Inherited")
1332                                                                         bag.AttributeUsage.Inherited = (bool) named.TypedValue.Value;
1333                                                         }
1334                                                         continue;
1335                                                 }
1336
1337                                                 // Interface only attribute
1338                                                 if (name == "CoClassAttribute") {
1339                                                         if (dt.Namespace != "System.Runtime.InteropServices")
1340                                                                 continue;
1341
1342                                                         if (bag == null)
1343                                                                 bag = new AttributesBag ();
1344
1345                                                         bag.CoClass = importer.ImportType ((MetaType) a.ConstructorArguments[0].Value);
1346                                                         continue;
1347                                                 }
1348                                         }
1349                                 }
1350
1351                                 if (bag == null)
1352                                         return Default;
1353
1354                                 if (conditionals != null)
1355                                         bag.Conditionals = conditionals.ToArray ();
1356                                 
1357                                 return bag;
1358                         }
1359                 }
1360
1361                 protected readonly MemberInfo provider;
1362                 protected AttributesBag cattrs;
1363                 protected readonly MetadataImporter importer;
1364
1365                 public ImportedDefinition (MemberInfo provider, MetadataImporter importer)
1366                 {
1367                         this.provider = provider;
1368                         this.importer = importer;
1369                 }
1370
1371                 #region Properties
1372
1373                 public bool IsImported {
1374                         get {
1375                                 return true;
1376                         }
1377                 }
1378
1379                 public virtual string Name {
1380                         get {
1381                                 return provider.Name;
1382                         }
1383                 }
1384
1385                 #endregion
1386
1387                 public string[] ConditionalConditions ()
1388                 {
1389                         if (cattrs == null)
1390                                 ReadAttributes ();
1391
1392                         return cattrs.Conditionals;
1393                 }
1394
1395                 public ObsoleteAttribute GetAttributeObsolete ()
1396                 {
1397                         if (cattrs == null)
1398                                 ReadAttributes ();
1399
1400                         return cattrs.Obsolete;
1401                 }
1402
1403                 public bool? CLSAttributeValue {
1404                         get {
1405                                 if (cattrs == null)
1406                                         ReadAttributes ();
1407
1408                                 return cattrs.CLSAttributeValue;
1409                         }
1410                 }
1411
1412                 protected void ReadAttributes ()
1413                 {
1414                         cattrs = AttributesBag.Read (provider, importer);
1415                 }
1416
1417                 public void SetIsAssigned ()
1418                 {
1419                         // Unused for imported members
1420                 }
1421
1422                 public void SetIsUsed ()
1423                 {
1424                         // Unused for imported members
1425                 }
1426         }
1427
1428         public class ImportedModuleDefinition
1429         {
1430                 readonly Module module;
1431                 bool cls_compliant;
1432                 
1433                 public ImportedModuleDefinition (Module module)
1434                 {
1435                         this.module = module;
1436                 }
1437
1438                 #region Properties
1439
1440                 public bool IsCLSCompliant {
1441                         get {
1442                                 return cls_compliant;
1443                         }
1444                 }
1445
1446                 public string Name {
1447                         get {
1448                                 return module.Name;
1449                         }
1450                 }
1451
1452                 #endregion
1453
1454                 public void ReadAttributes ()
1455                 {
1456                         IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (module);
1457
1458                         foreach (var a in attrs) {
1459                                 var dt = a.Constructor.DeclaringType;
1460                                 if (dt.Name == "CLSCompliantAttribute") {
1461                                         if (dt.Namespace != "System")
1462                                                 continue;
1463
1464                                         cls_compliant = (bool) a.ConstructorArguments[0].Value;
1465                                         continue;
1466                                 }
1467                         }
1468                 }
1469
1470                 //
1471                 // Reads assembly attributes which where attached to a special type because
1472                 // module does have assembly manifest
1473                 //
1474                 public List<Attribute> ReadAssemblyAttributes ()
1475                 {
1476                         var t = module.GetType (AssemblyAttributesPlaceholder.GetGeneratedName (Name));
1477                         if (t == null)
1478                                 return null;
1479
1480                         var field = t.GetField (AssemblyAttributesPlaceholder.AssemblyFieldName, BindingFlags.NonPublic | BindingFlags.Static);
1481                         if (field == null)
1482                                 return null;
1483
1484                         // TODO: implement, the idea is to fabricate specil Attribute class and
1485                         // add it to OptAttributes before resolving the source code attributes
1486                         // Need to build module location as well for correct error reporting
1487
1488                         //var assembly_attributes = CustomAttributeData.GetCustomAttributes (field);
1489                         //var attrs = new List<Attribute> (assembly_attributes.Count);
1490                         //foreach (var a in assembly_attributes)
1491                         //{
1492                         //    var type = metaImporter.ImportType (a.Constructor.DeclaringType);
1493                         //    var ctor = metaImporter.CreateMethod (a.Constructor, type);
1494
1495                         //    foreach (var carg in a.ConstructorArguments) {
1496                         //        carg.Value
1497                         //    }
1498
1499                         //    attrs.Add (new Attribute ("assembly", ctor, null, Location.Null, true));
1500                         //}
1501
1502                         return null;
1503                 }
1504         }
1505
1506         public class ImportedAssemblyDefinition : IAssemblyDefinition
1507         {
1508                 readonly Assembly assembly;
1509                 readonly AssemblyName aname;
1510                 bool cls_compliant;
1511
1512                 List<AssemblyName> internals_visible_to;
1513                 Dictionary<IAssemblyDefinition, AssemblyName> internals_visible_to_cache;
1514
1515                 public ImportedAssemblyDefinition (Assembly assembly)
1516                 {
1517                         this.assembly = assembly;
1518                         this.aname = assembly.GetName ();
1519                 }
1520
1521                 #region Properties
1522
1523                 public Assembly Assembly {
1524                         get {
1525                                 return assembly;
1526                         }
1527                 }
1528
1529                 public string FullName {
1530                         get {
1531                                 return aname.FullName;
1532                         }
1533                 }
1534
1535                 public bool HasStrongName {
1536                         get {
1537                                 return aname.GetPublicKey ().Length != 0;
1538                         }
1539                 }
1540
1541                 public bool IsMissing {
1542                         get {
1543 #if STATIC
1544                                 return assembly.__IsMissing;
1545 #else
1546                                 return false;
1547 #endif
1548                         }
1549                 }
1550
1551                 public bool IsCLSCompliant {
1552                         get {
1553                                 return cls_compliant;
1554                         }
1555                 }
1556
1557                 public string Location {
1558                         get {
1559                                 return assembly.Location;
1560                         }
1561                 }
1562
1563                 public string Name {
1564                         get {
1565                                 return aname.Name;
1566                         }
1567                 }
1568
1569                 #endregion
1570
1571                 public byte[] GetPublicKeyToken ()
1572                 {
1573                         return aname.GetPublicKeyToken ();
1574                 }
1575
1576                 public AssemblyName GetAssemblyVisibleToName (IAssemblyDefinition assembly)
1577                 {
1578                         return internals_visible_to_cache [assembly];
1579                 }
1580
1581                 public bool IsFriendAssemblyTo (IAssemblyDefinition assembly)
1582                 {
1583                         if (internals_visible_to == null)
1584                                 return false;
1585
1586                         AssemblyName is_visible = null;
1587                         if (internals_visible_to_cache == null) {
1588                                 internals_visible_to_cache = new Dictionary<IAssemblyDefinition, AssemblyName> ();
1589                         } else {
1590                                 if (internals_visible_to_cache.TryGetValue (assembly, out is_visible))
1591                                         return is_visible != null;
1592                         }
1593
1594                         var token = assembly.GetPublicKeyToken ();
1595                         if (token != null && token.Length == 0)
1596                                 token = null;
1597
1598                         foreach (var internals in internals_visible_to) {
1599                                 if (internals.Name != assembly.Name)
1600                                         continue;
1601
1602                                 if (token == null && assembly is AssemblyDefinition) {
1603                                         is_visible = internals;
1604                                         break;
1605                                 }
1606
1607                                 if (!ArrayComparer.IsEqual (token, internals.GetPublicKeyToken ()))
1608                                         continue;
1609
1610                                 is_visible = internals;
1611                                 break;
1612                         }
1613
1614                         internals_visible_to_cache.Add (assembly, is_visible);
1615                         return is_visible != null;
1616                 }
1617
1618                 public void ReadAttributes ()
1619                 {
1620 #if STATIC
1621                         if (assembly.__IsMissing)
1622                                 return;
1623 #endif
1624
1625                         IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (assembly);
1626
1627                         foreach (var a in attrs) {
1628                                 var dt = a.Constructor.DeclaringType;
1629                                 var name = dt.Name;
1630                                 if (name == "CLSCompliantAttribute") {
1631                                         if (dt.Namespace == "System") {
1632                                                 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1633                                         }
1634                                         continue;
1635                                 }
1636
1637                                 if (name == "InternalsVisibleToAttribute") {
1638                                         if (dt.Namespace != MetadataImporter.CompilerServicesNamespace)
1639                                                 continue;
1640
1641                                         string s = a.ConstructorArguments[0].Value as string;
1642                                         if (s == null)
1643                                                 continue;
1644
1645                                         var an = new AssemblyName (s);
1646                                         if (internals_visible_to == null)
1647                                                 internals_visible_to = new List<AssemblyName> ();
1648
1649                                         internals_visible_to.Add (an);
1650                                         continue;
1651                                 }
1652                         }
1653                 }
1654
1655                 public override string ToString ()
1656                 {
1657                         return FullName;
1658                 }
1659         }
1660
1661         class ImportedMemberDefinition : ImportedDefinition
1662         {
1663                 readonly TypeSpec type;
1664
1665                 public ImportedMemberDefinition (MemberInfo member, TypeSpec type, MetadataImporter importer)
1666                         : base (member, importer)
1667                 {
1668                         this.type = type;
1669                 }
1670
1671                 #region Properties
1672
1673                 public TypeSpec MemberType {
1674                         get {
1675                                 return type;
1676                         }
1677                 }
1678
1679                 #endregion
1680         }
1681
1682         class ImportedParameterMemberDefinition : ImportedMemberDefinition, IParametersMember
1683         {
1684                 readonly AParametersCollection parameters;
1685
1686                 public ImportedParameterMemberDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1687                         : base (provider, type, importer)
1688                 {
1689                         this.parameters = parameters;
1690                 }
1691
1692                 public ImportedParameterMemberDefinition (PropertyInfo provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1693                         : base (provider, type, importer)
1694                 {
1695                         this.parameters = parameters;
1696                 }
1697
1698                 #region Properties
1699
1700                 public AParametersCollection Parameters {
1701                         get {
1702                                 return parameters;
1703                         }
1704                 }
1705
1706                 #endregion
1707         }
1708
1709         class ImportedGenericMethodDefinition : ImportedParameterMemberDefinition, IGenericMethodDefinition
1710         {
1711                 readonly TypeParameterSpec[] tparams;
1712
1713                 public ImportedGenericMethodDefinition (MethodInfo provider, TypeSpec type, AParametersCollection parameters, TypeParameterSpec[] tparams, MetadataImporter importer)
1714                         : base (provider, type, parameters, importer)
1715                 {
1716                         this.tparams = tparams;
1717                 }
1718
1719                 #region Properties
1720
1721                 public TypeParameterSpec[] TypeParameters {
1722                         get {
1723                                 return tparams;
1724                         }
1725                 }
1726
1727                 public int TypeParametersCount {
1728                         get {
1729                                 return tparams.Length;
1730                         }
1731                 }
1732
1733                 #endregion
1734         }
1735
1736         class ImportedTypeDefinition : ImportedDefinition, ITypeDefinition
1737         {
1738                 TypeParameterSpec[] tparams;
1739                 string name;
1740
1741                 public ImportedTypeDefinition (MetaType type, MetadataImporter importer)
1742                         : base (type, importer)
1743                 {
1744                 }
1745
1746                 #region Properties
1747
1748                 public IAssemblyDefinition DeclaringAssembly {
1749                         get {
1750                                 return importer.GetAssemblyDefinition (provider.Module.Assembly);
1751                         }
1752                 }
1753
1754                 bool ITypeDefinition.IsComImport {
1755                         get {
1756                                 return ((MetaType) provider).IsImport;
1757                         }
1758                 }
1759
1760
1761                 bool ITypeDefinition.IsPartial {
1762                         get {
1763                                 return false;
1764                         }
1765                 }
1766
1767                 bool ITypeDefinition.IsTypeForwarder {
1768                         get {
1769 #if STATIC
1770                                 return ((MetaType) provider).__IsTypeForwarder;
1771 #else
1772                                 return false;
1773 #endif
1774                         }
1775                 }
1776
1777                 public override string Name {
1778                         get {
1779                                 if (name == null) {
1780                                         name = base.Name;
1781                                         if (tparams != null) {
1782                                                 int arity_start = name.IndexOf ('`');
1783                                                 if (arity_start > 0)
1784                                                         name = name.Substring (0, arity_start);
1785                                         }
1786                                 }
1787
1788                                 return name;
1789                         }
1790                 }
1791
1792                 public string Namespace {
1793                         get {
1794                                 return ((MetaType) provider).Namespace;
1795                         }
1796                 }
1797
1798                 public int TypeParametersCount {
1799                         get {
1800                                 return tparams == null ? 0 : tparams.Length;
1801                         }
1802                 }
1803
1804                 public TypeParameterSpec[] TypeParameters {
1805                         get {
1806                                 return tparams;
1807                         }
1808                         set {
1809                                 tparams = value;
1810                         }
1811                 }
1812
1813                 #endregion
1814
1815                 public void DefineInterfaces (TypeSpec spec)
1816                 {
1817                         var type = (MetaType) provider;
1818                         MetaType[] ifaces;
1819 #if STATIC
1820                         ifaces = type.__GetDeclaredInterfaces ();
1821                         if (ifaces.Length != 0) {
1822                                 foreach (var iface in ifaces) {
1823                                         var it = importer.CreateType (iface);
1824                                         if (it == null)
1825                                                 continue;
1826
1827                                         spec.AddInterfaceDefined (it);
1828
1829                                         // Unfortunately not all languages expand inherited interfaces
1830                                         var bifaces = it.Interfaces;
1831                                         if (bifaces != null) {
1832                                                 foreach (var biface in bifaces) {
1833                                                         spec.AddInterfaceDefined (biface);
1834                                                 }
1835                                         }
1836                                 }
1837                         }
1838                         
1839                         //
1840                         // It's impossible to get declared interfaces only using System.Reflection
1841                         // hence we need to mimic the behavior with ikvm-reflection too to keep
1842                         // our type look-up logic same
1843                         //
1844                         if (spec.BaseType != null) {
1845                                 var bifaces = spec.BaseType.Interfaces;
1846                                 if (bifaces != null) {
1847                                         //
1848                                         // Before adding base class interfaces close defined interfaces
1849                                         // on type parameter
1850                                         //
1851                                         var tp = spec as TypeParameterSpec;
1852                                         if (tp != null && tp.InterfacesDefined == null) {
1853                                                 tp.InterfacesDefined = TypeSpec.EmptyTypes;
1854                                         }
1855
1856                                         foreach (var iface in bifaces)
1857                                                 spec.AddInterfaceDefined (iface);
1858                                 }
1859                         }
1860 #else
1861                         ifaces = type.GetInterfaces ();
1862
1863                         if (ifaces.Length > 0) {
1864                                 foreach (var iface in ifaces) {
1865                                         spec.AddInterface (importer.CreateType (iface));
1866                                 }
1867                         }
1868 #endif
1869
1870                 }
1871
1872                 public static void Error_MissingDependency (IMemberContext ctx, List<TypeSpec> types, Location loc)
1873                 {
1874                         // 
1875                         // Report details about missing type and most likely cause of the problem.
1876                         // csc reports 1683, 1684 as warnings but we report them only when used
1877                         // or referenced from the user core in which case compilation error has to
1878                         // be reported because compiler cannot continue anyway
1879                         //
1880                         for (int i = 0; i < types.Count; ++i) {
1881                                 var t = types [i];
1882
1883                                 //
1884                                 // Report missing types only once per type
1885                                 //
1886                                 if (i > 0 && types.IndexOf (t) < i)
1887                                         continue;
1888
1889                                 string name = t.GetSignatureForError ();
1890
1891                                 if (t.MemberDefinition.DeclaringAssembly == ctx.Module.DeclaringAssembly) {
1892                                         ctx.Module.Compiler.Report.Error (1683, loc,
1893                                                 "Reference to type `{0}' claims it is defined in this assembly, but it is not defined in source or any added modules",
1894                                                 name);
1895                                 } else if (t.MemberDefinition.DeclaringAssembly.IsMissing) {
1896                                         if (t.MemberDefinition.IsTypeForwarder) {
1897                                                 ctx.Module.Compiler.Report.Error (1070, loc,
1898                                                         "The type `{0}' has been forwarded to an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
1899                                                         name, t.MemberDefinition.DeclaringAssembly.FullName);
1900                                         } else {
1901                                                 ctx.Module.Compiler.Report.Error (12, loc,
1902                                                         "The type `{0}' is defined in an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
1903                                                         name, t.MemberDefinition.DeclaringAssembly.FullName);
1904                                         }
1905                                 } else {
1906                                         ctx.Module.Compiler.Report.Error (1684, loc,
1907                                                 "Reference to type `{0}' claims it is defined assembly `{1}', but it could not be found",
1908                                                 name, t.MemberDefinition.DeclaringAssembly.FullName);
1909                                 }
1910                         }
1911                 }
1912
1913                 public TypeSpec GetAttributeCoClass ()
1914                 {
1915                         if (cattrs == null)
1916                                 ReadAttributes ();
1917
1918                         return cattrs.CoClass;
1919                 }
1920
1921                 public string GetAttributeDefaultMember ()
1922                 {
1923                         if (cattrs == null)
1924                                 ReadAttributes ();
1925
1926                         return cattrs.DefaultIndexerName;
1927                 }
1928
1929                 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
1930                 {
1931                         if (cattrs == null)
1932                                 ReadAttributes ();
1933
1934                         return cattrs.AttributeUsage;
1935                 }
1936
1937                 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
1938                 {
1939                         var a = importer.GetAssemblyDefinition (provider.Module.Assembly);
1940                         return a == assembly || a.IsFriendAssemblyTo (assembly);
1941                 }
1942
1943                 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
1944                 {
1945                         //
1946                         // Not interested in members of nested private types unless the importer needs them
1947                         //
1948                         if (declaringType.IsPrivate && importer.IgnorePrivateMembers) {
1949                                 cache = MemberCache.Empty;
1950                                 return;
1951                         }
1952
1953                         var loading_type = (MetaType) provider;
1954                         const BindingFlags all_members = BindingFlags.DeclaredOnly |
1955                                 BindingFlags.Static | BindingFlags.Instance |
1956                                 BindingFlags.Public | BindingFlags.NonPublic;
1957
1958                         const MethodAttributes explicit_impl = MethodAttributes.NewSlot |
1959                                         MethodAttributes.Virtual | MethodAttributes.HideBySig |
1960                                         MethodAttributes.Final;
1961
1962                         Dictionary<MethodBase, MethodSpec> possible_accessors = null;
1963                         List<EventSpec> imported_events = null;
1964                         EventSpec event_spec;
1965                         MemberSpec imported;
1966                         MethodInfo m;
1967                         MemberInfo[] all;
1968                         try {
1969                                 all = loading_type.GetMembers (all_members);
1970                         } catch (Exception e) {
1971                                 throw new InternalErrorException (e, "Could not import type `{0}' from `{1}'",
1972                                         declaringType.GetSignatureForError (), declaringType.MemberDefinition.DeclaringAssembly.FullName);
1973                         }
1974
1975                         if (cache == null) {
1976                                 cache = new MemberCache (all.Length);
1977
1978                                 //
1979                                 // Do the types first as they can be referenced by the members before
1980                                 // they are found or inflated
1981                                 //
1982                                 foreach (var member in all) {
1983                                         if (member.MemberType != MemberTypes.NestedType)
1984                                                 continue;
1985
1986                                         var t = (MetaType) member;
1987
1988                                         // Ignore compiler generated types, mostly lambda containers
1989                                         if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
1990                                                 continue;
1991
1992                                         try {
1993                                                 imported = importer.CreateNestedType (t, declaringType);
1994                                         } catch (Exception e) {
1995                                                 throw new InternalErrorException (e, "Could not import nested type `{0}' from `{1}'",
1996                                                         t.FullName, declaringType.MemberDefinition.DeclaringAssembly.FullName);
1997                                         }
1998
1999                                         cache.AddMemberImported (imported);
2000                                 }
2001
2002                                 foreach (var member in all) {
2003                                         if (member.MemberType != MemberTypes.NestedType)
2004                                                 continue;
2005
2006                                         var t = (MetaType) member;
2007
2008                                         if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
2009                                                 continue;
2010
2011                                         importer.ImportTypeBase (t);
2012                                 }
2013                         }
2014
2015                         //
2016                         // Load base interfaces first to minic behaviour of compiled members
2017                         //
2018                         if (declaringType.IsInterface && declaringType.Interfaces != null) {
2019                                 foreach (var iface in declaringType.Interfaces) {
2020                                         cache.AddInterface (iface);
2021                                 }
2022                         }
2023
2024                         if (!onlyTypes) {
2025                                 //
2026                                 // The logic here requires methods to be returned first which seems to work for both Mono and .NET
2027                                 //
2028                                 foreach (var member in all) {
2029                                         switch (member.MemberType) {
2030                                         case MemberTypes.Constructor:
2031                                                 if (declaringType.IsInterface)
2032                                                         continue;
2033
2034                                                 goto case MemberTypes.Method;
2035                                         case MemberTypes.Method:
2036                                                 MethodBase mb = (MethodBase) member;
2037                                                 var attrs = mb.Attributes;
2038
2039                                                 if ((attrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) {
2040                                                         if (importer.IgnorePrivateMembers)
2041                                                                 continue;
2042
2043                                                         // Ignore explicitly implemented members
2044                                                         if ((attrs & explicit_impl) == explicit_impl)
2045                                                                 continue;
2046
2047                                                         // Ignore compiler generated methods
2048                                                         if (MetadataImporter.HasAttribute (CustomAttributeData.GetCustomAttributes (mb), "CompilerGeneratedAttribute", MetadataImporter.CompilerServicesNamespace))
2049                                                                 continue;
2050                                                 }
2051
2052                                                 imported = importer.CreateMethod (mb, declaringType);
2053                                                 if (imported.Kind == MemberKind.Method && !imported.IsGeneric) {
2054                                                         if (possible_accessors == null)
2055                                                                 possible_accessors = new Dictionary<MethodBase, MethodSpec> (ReferenceEquality<MethodBase>.Default);
2056
2057                                                         // There are no metadata rules for accessors, we have to consider any method as possible candidate
2058                                                         possible_accessors.Add (mb, (MethodSpec) imported);
2059                                                 }
2060
2061                                                 break;
2062                                         case MemberTypes.Property:
2063                                                 if (possible_accessors == null)
2064                                                         continue;
2065
2066                                                 var p = (PropertyInfo) member;
2067                                                 //
2068                                                 // Links possible accessors with property
2069                                                 //
2070                                                 MethodSpec get, set;
2071                                                 m = p.GetGetMethod (true);
2072                                                 if (m == null || !possible_accessors.TryGetValue (m, out get))
2073                                                         get = null;
2074
2075                                                 m = p.GetSetMethod (true);
2076                                                 if (m == null || !possible_accessors.TryGetValue (m, out set))
2077                                                         set = null;
2078
2079                                                 // No accessors registered (e.g. explicit implementation)
2080                                                 if (get == null && set == null)
2081                                                         continue;
2082
2083                                                 imported = importer.CreateProperty (p, declaringType, get, set);
2084                                                 if (imported == null)
2085                                                         continue;
2086
2087                                                 break;
2088                                         case MemberTypes.Event:
2089                                                 if (possible_accessors == null)
2090                                                         continue;
2091
2092                                                 var e = (EventInfo) member;
2093                                                 //
2094                                                 // Links accessors with event
2095                                                 //
2096                                                 MethodSpec add, remove;
2097                                                 m = e.GetAddMethod (true);
2098                                                 if (m == null || !possible_accessors.TryGetValue (m, out add))
2099                                                         add = null;
2100
2101                                                 m = e.GetRemoveMethod (true);
2102                                                 if (m == null || !possible_accessors.TryGetValue (m, out remove))
2103                                                         remove = null;
2104
2105                                                 // Both accessors are required
2106                                                 if (add == null || remove == null)
2107                                                         continue;
2108
2109                                                 event_spec = importer.CreateEvent (e, declaringType, add, remove);
2110                                                 if (!importer.IgnorePrivateMembers) {
2111                                                         if (imported_events == null)
2112                                                                 imported_events = new List<EventSpec> ();
2113
2114                                                         imported_events.Add (event_spec);
2115                                                 }
2116
2117                                                 imported = event_spec;
2118                                                 break;
2119                                         case MemberTypes.Field:
2120                                                 var fi = (FieldInfo) member;
2121
2122                                                 imported = importer.CreateField (fi, declaringType);
2123                                                 if (imported == null)
2124                                                         continue;
2125
2126                                                 //
2127                                                 // For dynamic binder event has to be fully restored to allow operations
2128                                                 // within the type container to work correctly
2129                                                 //
2130                                                 if (imported_events != null) {
2131                                                         // The backing event field should be private but it may not
2132                                                         int i;
2133                                                         for (i = 0; i < imported_events.Count; ++i) {
2134                                                                 var ev = imported_events[i];
2135                                                                 if (ev.Name == fi.Name) {
2136                                                                         ev.BackingField = (FieldSpec) imported;
2137                                                                         imported_events.RemoveAt (i);
2138                                                                         i = -1;
2139                                                                         break;
2140                                                                 }
2141                                                         }
2142
2143                                                         if (i < 0)
2144                                                                 continue;
2145                                                 }
2146
2147                                                 break;
2148                                         case MemberTypes.NestedType:
2149                                                 // Already in the cache from the first pass
2150                                                 continue;
2151                                         default:
2152                                                 throw new NotImplementedException (member.ToString ());
2153                                         }
2154
2155                                         if (imported.IsStatic && declaringType.IsInterface)
2156                                                 continue;
2157
2158                                         cache.AddMemberImported (imported);
2159                                 }
2160                         }
2161                 }
2162         }
2163
2164         class ImportedTypeParameterDefinition : ImportedDefinition, ITypeDefinition
2165         {
2166                 public ImportedTypeParameterDefinition (MetaType type, MetadataImporter importer)
2167                         : base (type, importer)
2168                 {
2169                 }
2170
2171                 #region Properties
2172
2173                 public IAssemblyDefinition DeclaringAssembly {
2174                         get {
2175                                 throw new NotImplementedException ();
2176                         }
2177                 }
2178
2179                 bool ITypeDefinition.IsComImport {
2180                         get {
2181                                 return false;
2182                         }
2183                 }
2184
2185                 bool ITypeDefinition.IsPartial {
2186                         get {
2187                                 return false;
2188                         }
2189                 }
2190
2191                 bool ITypeDefinition.IsTypeForwarder {
2192                         get {
2193                                 return false;
2194                         }
2195                 }
2196
2197                 public string Namespace {
2198                         get {
2199                                 return null;
2200                         }
2201                 }
2202
2203                 public int TypeParametersCount {
2204                         get {
2205                                 return 0;
2206                         }
2207                 }
2208
2209                 public TypeParameterSpec[] TypeParameters {
2210                         get {
2211                                 return null;
2212                         }
2213                 }
2214
2215                 #endregion
2216
2217                 public TypeSpec GetAttributeCoClass ()
2218                 {
2219                         return null;
2220                 }
2221
2222                 public string GetAttributeDefaultMember ()
2223                 {
2224                         throw new NotSupportedException ();
2225                 }
2226
2227                 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
2228                 {
2229                         throw new NotSupportedException ();
2230                 }
2231
2232                 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2233                 {
2234                         throw new NotImplementedException ();
2235                 }
2236
2237                 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2238                 {
2239                         throw new NotImplementedException ();
2240                 }
2241         }
2242 }