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