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