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