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