Better import of contraints with missing references
[mono.git] / mcs / mcs / import.cs
1 //
2 // import.cs: System.Reflection conversions
3 //
4 // Authors: Marek Safar (marek.safar@gmail.com)
5 //
6 // Dual licensed under the terms of the MIT X11 or GNU GPL
7 //
8 // Copyright 2009-2011 Novell, Inc
9 // Copyright 2011 Xamarin, Inc (http://www.xamarin.com)
10 //
11
12 using System;
13 using System.Runtime.CompilerServices;
14 using System.Linq;
15 using System.Collections.Generic;
16
17 #if STATIC
18 using MetaType = IKVM.Reflection.Type;
19 using IKVM.Reflection;
20 using IKVM.Reflection.Emit;
21 #else
22 using MetaType = System.Type;
23 using System.Reflection;
24 using System.Reflection.Emit;
25 #endif
26
27 namespace Mono.CSharp
28 {
29         public abstract class MetadataImporter
30         {
31                 //
32                 // Dynamic types reader with additional logic to reconstruct a dynamic
33                 // type using DynamicAttribute values
34                 //
35                 struct DynamicTypeReader
36                 {
37                         static readonly bool[] single_attribute = { true };
38
39                         public int Position;
40                         bool[] flags;
41
42                         // There is no common type for CustomAttributeData and we cannot
43                         // use ICustomAttributeProvider
44                         object provider;
45
46                         //
47                         // A member provider which can be used to get CustomAttributeData
48                         //
49                         public DynamicTypeReader (object provider)
50                         {
51                                 Position = 0;
52                                 flags = null;
53                                 this.provider = provider;
54                         }
55
56                         //
57                         // Returns true when object at local position has dynamic attribute flag
58                         //
59                         public bool IsDynamicObject (MetadataImporter importer)
60                         {
61                                 if (provider != null)
62                                         ReadAttribute (importer);
63
64                                 return flags != null && Position < flags.Length && flags[Position];
65                         }
66
67                         //
68                         // Returns true when DynamicAttribute exists
69                         //
70                         public bool HasDynamicAttribute (MetadataImporter importer)
71                         {
72                                 if (provider != null)
73                                         ReadAttribute (importer);
74
75                                 return flags != null;
76                         }
77
78                         void ReadAttribute (MetadataImporter importer)
79                         {
80                                 IList<CustomAttributeData> cad;
81                                 if (provider is MemberInfo) {
82                                         cad = CustomAttributeData.GetCustomAttributes ((MemberInfo) provider);
83                                 } else if (provider is ParameterInfo) {
84                                         cad = CustomAttributeData.GetCustomAttributes ((ParameterInfo) provider);
85                                 } else {
86                                         provider = null;
87                                         return;
88                                 }
89
90                                 if (cad.Count > 0) {
91                                         foreach (var ca in cad) {
92                                                 var dt = ca.Constructor.DeclaringType;
93                                                 if (dt.Name != "DynamicAttribute" && dt.Namespace != CompilerServicesNamespace)
94                                                         continue;
95
96                                                 if (ca.ConstructorArguments.Count == 0) {
97                                                         flags = single_attribute;
98                                                         break;
99                                                 }
100
101                                                 var arg_type = ca.ConstructorArguments[0].ArgumentType;
102
103                                                 if (arg_type.IsArray && MetaType.GetTypeCode (arg_type.GetElementType ()) == TypeCode.Boolean) {
104                                                         var carg = (IList<CustomAttributeTypedArgument>) ca.ConstructorArguments[0].Value;
105                                                         flags = new bool[carg.Count];
106                                                         for (int i = 0; i < flags.Length; ++i) {
107                                                                 if (MetaType.GetTypeCode (carg[i].ArgumentType) == TypeCode.Boolean)
108                                                                         flags[i] = (bool) carg[i].Value;
109                                                         }
110
111                                                         break;
112                                                 }
113                                         }
114                                 }
115
116                                 provider = null;
117                         }
118                 }
119
120                 protected readonly Dictionary<MetaType, TypeSpec> import_cache;
121                 protected readonly Dictionary<MetaType, TypeSpec> compiled_types;
122                 protected readonly Dictionary<Assembly, IAssemblyDefinition> assembly_2_definition;
123                 readonly ModuleContainer module;
124
125                 public static readonly string CompilerServicesNamespace = "System.Runtime.CompilerServices";
126
127                 protected MetadataImporter (ModuleContainer module)
128                 {
129                         this.module = module;
130
131                         import_cache = new Dictionary<MetaType, TypeSpec> (1024, ReferenceEquality<MetaType>.Default);
132                         compiled_types = new Dictionary<MetaType, TypeSpec> (40, ReferenceEquality<MetaType>.Default);
133                         assembly_2_definition = new Dictionary<Assembly, IAssemblyDefinition> (ReferenceEquality<Assembly>.Default);
134                         IgnorePrivateMembers = true;
135                 }
136
137                 #region Properties
138
139                 public ICollection<IAssemblyDefinition> Assemblies {
140                         get {
141                                 return assembly_2_definition.Values;
142                         }
143                 }
144
145                 public bool IgnorePrivateMembers { get; set; }
146
147                 #endregion
148
149                 public abstract void AddCompiledType (TypeBuilder builder, TypeSpec spec);
150                 protected abstract MemberKind DetermineKindFromBaseType (MetaType baseType);
151                 protected abstract bool HasVolatileModifier (MetaType[] modifiers);
152
153                 public FieldSpec CreateField (FieldInfo fi, TypeSpec declaringType)
154                 {
155                         Modifiers mod = 0;
156                         var fa = fi.Attributes;
157                         switch (fa & FieldAttributes.FieldAccessMask) {
158                                 case FieldAttributes.Public:
159                                         mod = Modifiers.PUBLIC;
160                                         break;
161                                 case FieldAttributes.Assembly:
162                                         mod = Modifiers.INTERNAL;
163                                         break;
164                                 case FieldAttributes.Family:
165                                         mod = Modifiers.PROTECTED;
166                                         break;
167                                 case FieldAttributes.FamORAssem:
168                                         mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
169                                         break;
170                                 default:
171                                         // Ignore private fields (even for error reporting) to not require extra dependencies
172                                         if ((IgnorePrivateMembers && !declaringType.IsStruct) ||
173                                                 HasAttribute (CustomAttributeData.GetCustomAttributes (fi), "CompilerGeneratedAttribute", CompilerServicesNamespace))
174                                                 return null;
175
176                                         mod = Modifiers.PRIVATE;
177                                         break;
178                         }
179
180                         TypeSpec field_type;
181
182                         try {
183                                 field_type = ImportType (fi.FieldType, new DynamicTypeReader (fi));
184                         } catch (Exception e) {
185                                 // TODO: I should construct fake TypeSpec based on TypeRef signature
186                                 // but there is no way to do it with System.Reflection
187                                 throw new InternalErrorException (e, "Cannot import field `{0}.{1}' referenced in assembly `{2}'",
188                                         declaringType.GetSignatureForError (), fi.Name, declaringType.MemberDefinition.DeclaringAssembly);
189                         }
190
191                         var definition = new ImportedMemberDefinition (fi, field_type, this);
192
193                         if ((fa & FieldAttributes.Literal) != 0) {
194                                 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.IsNotCSharpCompatible = 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                         if (kind == MemberKind.TypeParameter) {
839                                 if (canImportBaseType)
840                                         ImportTypeParameterTypeConstraints ((TypeParameterSpec) spec, type);
841
842                                 return spec;
843                         }
844
845                         //
846                         // Two stage setup as the base type can be inflated declaring type or
847                         // another nested type inside same declaring type which has not been
848                         // loaded, therefore we can import a base type of nested types once
849                         // the types have been imported
850                         //
851                         if (canImportBaseType)
852                                 ImportTypeBase (spec, type);
853
854                         return spec;
855                 }
856
857                 public IAssemblyDefinition GetAssemblyDefinition (Assembly assembly)
858                 {
859                         IAssemblyDefinition found;
860                         if (!assembly_2_definition.TryGetValue (assembly, out found)) {
861
862                                 // This can happen in dynamic context only
863                                 var def = new ImportedAssemblyDefinition (assembly);
864                                 assembly_2_definition.Add (assembly, def);
865                                 def.ReadAttributes ();
866                                 found = def;
867                         }
868
869                         return found;
870                 }
871
872                 public void ImportTypeBase (MetaType type)
873                 {
874                         TypeSpec spec = import_cache[type];
875                         if (spec != null)
876                                 ImportTypeBase (spec, type);
877                 }
878
879                 TypeParameterSpec CreateTypeParameter (MetaType type, TypeSpec declaringType)
880                 {
881                         Variance variance;
882                         switch (type.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) {
883                         case GenericParameterAttributes.Covariant:
884                                 variance = Variance.Covariant;
885                                 break;
886                         case GenericParameterAttributes.Contravariant:
887                                 variance = Variance.Contravariant;
888                                 break;
889                         default:
890                                 variance = Variance.None;
891                                 break;
892                         }
893
894                         SpecialConstraint special = SpecialConstraint.None;
895                         var import_special = type.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask;
896
897                         if ((import_special & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) {
898                                 special |= SpecialConstraint.Struct;
899                         } else if ((import_special & GenericParameterAttributes.DefaultConstructorConstraint) != 0) {
900                                 special = SpecialConstraint.Constructor;
901                         }
902
903                         if ((import_special & GenericParameterAttributes.ReferenceTypeConstraint) != 0) {
904                                 special |= SpecialConstraint.Class;
905                         }
906
907                         TypeParameterSpec spec;
908                         var def = new ImportedTypeParameterDefinition (type, this);
909                         if (type.DeclaringMethod != null) {
910                                 spec = new TypeParameterSpec (type.GenericParameterPosition, def, special, variance, type);
911                         } else {
912                                 spec = new TypeParameterSpec (declaringType, type.GenericParameterPosition, def, special, variance, type);
913                         }
914
915                         return spec;
916                 }
917
918                 //
919                 // Test for a custom attribute type match. Custom attributes are not really predefined globaly 
920                 // they can be assembly specific therefore we do check based on names only
921                 //
922                 public static bool HasAttribute (IList<CustomAttributeData> attributesData, string attrName, string attrNamespace)
923                 {
924                         if (attributesData.Count == 0)
925                                 return false;
926
927                         foreach (var attr in attributesData) {
928                                 var dt = attr.Constructor.DeclaringType;
929                                 if (dt.Name == attrName && dt.Namespace == attrNamespace)
930                                         return true;
931                         }
932
933                         return false;
934                 }
935
936                 void ImportTypeBase (TypeSpec spec, MetaType type)
937                 {
938                         if (spec.Kind == MemberKind.Interface)
939                                 spec.BaseType = module.Compiler.BuiltinTypes.Object;
940                         else if (type.BaseType != null) {
941                                 TypeSpec base_type;
942                                 if (!IsMissingType (type.BaseType) && type.BaseType.IsGenericType)
943                                         base_type = CreateType (type.BaseType, new DynamicTypeReader (type), true);
944                                 else
945                                         base_type = CreateType (type.BaseType);
946
947                                 spec.BaseType = base_type;
948                         }
949
950                         MetaType[] ifaces;
951 #if STATIC
952                         ifaces = type.__GetDeclaredInterfaces ();
953                         if (ifaces.Length != 0) {
954                                 foreach (var iface in ifaces) {
955                                         var it = CreateType (iface);
956                                         if (it == null)
957                                                 continue;
958
959                                         spec.AddInterface (it);
960
961                                         // Unfortunately not all languages expand inherited interfaces
962                                         var bifaces = it.Interfaces;
963                                         if (bifaces != null) {
964                                                 foreach (var biface in bifaces) {
965                                                         spec.AddInterface (biface);
966                                                 }
967                                         }
968                                 }
969                         }
970
971                         if (spec.BaseType != null) {
972                                 var bifaces = spec.BaseType.Interfaces;
973                                 if (bifaces != null) {
974                                         //
975                                         // Before adding base class interfaces close defined interfaces
976                                         // on type parameter
977                                         //
978                                         var tp = spec as TypeParameterSpec;
979                                         if (tp != null && tp.InterfacesDefined == null) {
980                                                 tp.InterfacesDefined = TypeSpec.EmptyTypes;
981                                         }
982
983                                         foreach (var iface in bifaces)
984                                                 spec.AddInterface (iface);
985                                 }
986                         }
987 #else
988                         ifaces = type.GetInterfaces ();
989
990                         if (ifaces.Length > 0) {
991                                 foreach (var iface in ifaces) {
992                                         spec.AddInterface (CreateType (iface));
993                                 }
994                         }
995 #endif
996
997                         if (spec.MemberDefinition.TypeParametersCount > 0) {
998                                 foreach (var tp in spec.MemberDefinition.TypeParameters) {
999                                         ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
1000                                 }
1001                         }
1002                 }
1003
1004                 protected void ImportTypes (MetaType[] types, Namespace targetNamespace, bool hasExtensionTypes)
1005                 {
1006                         Namespace ns = targetNamespace;
1007                         string prev_namespace = null;
1008                         foreach (var t in types) {
1009                                 if (t == null)
1010                                         continue;
1011
1012                                 // Be careful not to trigger full parent type loading
1013                                 if (t.MemberType == MemberTypes.NestedType)
1014                                         continue;
1015
1016                                 if (t.Name[0] == '<')
1017                                         continue;
1018
1019                                 var it = CreateType (t, null, new DynamicTypeReader (t), true);
1020                                 if (it == null)
1021                                         continue;
1022
1023                                 if (prev_namespace != t.Namespace) {
1024                                         ns = t.Namespace == null ? targetNamespace : targetNamespace.GetNamespace (t.Namespace, true);
1025                                         prev_namespace = t.Namespace;
1026                                 }
1027
1028                                 ns.AddType (module, it);
1029
1030                                 if (it.IsStatic && hasExtensionTypes &&
1031                                         HasAttribute (CustomAttributeData.GetCustomAttributes (t), "ExtensionAttribute", CompilerServicesNamespace)) {
1032                                         it.SetExtensionMethodContainer ();
1033                                 }
1034                         }
1035                 }
1036
1037                 void ImportTypeParameterTypeConstraints (TypeParameterSpec spec, MetaType type)
1038                 {
1039                         var constraints = type.GetGenericParameterConstraints ();
1040                         List<TypeSpec> tparams = null;
1041                         foreach (var ct in constraints) {
1042                                 if (ct.IsGenericParameter) {
1043                                         if (tparams == null)
1044                                                 tparams = new List<TypeSpec> ();
1045
1046                                         tparams.Add (CreateType (ct));
1047                                         continue;
1048                                 }
1049
1050                                 if (!IsMissingType (ct) && ct.IsClass) {
1051                                         spec.BaseType = CreateType (ct);
1052                                         continue;
1053                                 }
1054
1055                                 spec.AddInterface (CreateType (ct));
1056                         }
1057
1058                         if (spec.BaseType == null)
1059                                 spec.BaseType = module.Compiler.BuiltinTypes.Object;
1060
1061                         if (tparams != null)
1062                                 spec.TypeArguments = tparams.ToArray ();
1063                 }
1064
1065                 Constant ImportParameterConstant (object value)
1066                 {
1067                         //
1068                         // Get type of underlying value as int constant can be used for object
1069                         // parameter type. This is not allowed in C# but other languages can do that
1070                         //
1071                         var types = module.Compiler.BuiltinTypes;
1072                         switch (System.Type.GetTypeCode (value.GetType ())) {
1073                         case TypeCode.Boolean:
1074                                 return new BoolConstant (types, (bool) value, Location.Null);
1075                         case TypeCode.Byte:
1076                                 return new ByteConstant (types, (byte) value, Location.Null);
1077                         case TypeCode.Char:
1078                                 return new CharConstant (types, (char) value, Location.Null);
1079                         case TypeCode.Decimal:
1080                                 return new DecimalConstant (types, (decimal) value, Location.Null);
1081                         case TypeCode.Double:
1082                                 return new DoubleConstant (types, (double) value, Location.Null);
1083                         case TypeCode.Int16:
1084                                 return new ShortConstant (types, (short) value, Location.Null);
1085                         case TypeCode.Int32:
1086                                 return new IntConstant (types, (int) value, Location.Null);
1087                         case TypeCode.Int64:
1088                                 return new LongConstant (types, (long) value, Location.Null);
1089                         case TypeCode.SByte:
1090                                 return new SByteConstant (types, (sbyte) value, Location.Null);
1091                         case TypeCode.Single:
1092                                 return new FloatConstant (types, (float) value, Location.Null);
1093                         case TypeCode.String:
1094                                 return new StringConstant (types, (string) value, Location.Null);
1095                         case TypeCode.UInt16:
1096                                 return new UShortConstant (types, (ushort) value, Location.Null);
1097                         case TypeCode.UInt32:
1098                                 return new UIntConstant (types, (uint) value, Location.Null);
1099                         case TypeCode.UInt64:
1100                                 return new ULongConstant (types, (ulong) value, Location.Null);
1101                         }
1102
1103                         throw new NotImplementedException (value.GetType ().ToString ());
1104                 }
1105
1106                 public TypeSpec ImportType (MetaType type)
1107                 {
1108                         return ImportType (type, new DynamicTypeReader (type));
1109                 }
1110
1111                 TypeSpec ImportType (MetaType type, DynamicTypeReader dtype)
1112                 {
1113                         if (type.HasElementType) {
1114                                 var element = type.GetElementType ();
1115                                 ++dtype.Position;
1116                                 var spec = ImportType (element, dtype);
1117
1118                                 if (type.IsArray)
1119                                         return ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
1120                                 if (type.IsByRef)
1121                                         return ReferenceContainer.MakeType (module, spec);
1122                                 if (type.IsPointer)
1123                                         return PointerContainer.MakeType (module, spec);
1124
1125                                 throw new NotImplementedException ("Unknown element type " + type.ToString ());
1126                         }
1127
1128                         return CreateType (type, dtype, true);
1129                 }
1130
1131                 static bool IsMissingType (MetaType type)
1132                 {
1133 #if STATIC
1134                         return type.__IsMissing;
1135 #else
1136                         return false;
1137 #endif
1138                 }
1139
1140                 //
1141                 // Decimal constants cannot be encoded in the constant blob, and thus are marked
1142                 // as IsInitOnly ('readonly' in C# parlance).  We get its value from the 
1143                 // DecimalConstantAttribute metadata.
1144                 //
1145                 Constant ReadDecimalConstant (IList<CustomAttributeData> attrs)
1146                 {
1147                         if (attrs.Count == 0)
1148                                 return null;
1149
1150                         foreach (var ca in attrs) {
1151                                 var dt = ca.Constructor.DeclaringType;
1152                                 if (dt.Name != "DecimalConstantAttribute" || dt.Namespace != CompilerServicesNamespace)
1153                                         continue;
1154
1155                                 var value = new decimal (
1156                                         (int) (uint) ca.ConstructorArguments[4].Value,
1157                                         (int) (uint) ca.ConstructorArguments[3].Value,
1158                                         (int) (uint) ca.ConstructorArguments[2].Value,
1159                                         (byte) ca.ConstructorArguments[1].Value != 0,
1160                                         (byte) ca.ConstructorArguments[0].Value);
1161
1162                                 return new DecimalConstant (module.Compiler.BuiltinTypes, value, Location.Null);
1163                         }
1164
1165                         return null;
1166                 }
1167
1168                 static Modifiers ReadMethodModifiers (MethodBase mb, TypeSpec declaringType)
1169                 {
1170                         Modifiers mod;
1171                         var ma = mb.Attributes;
1172                         switch (ma & MethodAttributes.MemberAccessMask) {
1173                         case MethodAttributes.Public:
1174                                 mod = Modifiers.PUBLIC;
1175                                 break;
1176                         case MethodAttributes.Assembly:
1177                                 mod = Modifiers.INTERNAL;
1178                                 break;
1179                         case MethodAttributes.Family:
1180                                 mod = Modifiers.PROTECTED;
1181                                 break;
1182                         case MethodAttributes.FamORAssem:
1183                                 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
1184                                 break;
1185                         default:
1186                                 mod = Modifiers.PRIVATE;
1187                                 break;
1188                         }
1189
1190                         if ((ma & MethodAttributes.Static) != 0) {
1191                                 mod |= Modifiers.STATIC;
1192                                 return mod;
1193                         }
1194                         if ((ma & MethodAttributes.Abstract) != 0 && declaringType.IsClass) {
1195                                 mod |= Modifiers.ABSTRACT;
1196                                 return mod;
1197                         }
1198
1199                         // It can be sealed and override
1200                         if ((ma & MethodAttributes.Final) != 0)
1201                                 mod |= Modifiers.SEALED;
1202
1203                         if ((ma & MethodAttributes.Virtual) != 0) {
1204                                 // Not every member can be detected based on MethodAttribute, we
1205                                 // set virtual or non-virtual only when we are certain. Further checks
1206                                 // to really find out what `virtual' means for this member are done
1207                                 // later
1208                                 if ((ma & MethodAttributes.NewSlot) != 0) {
1209                                         if ((mod & Modifiers.SEALED) != 0) {
1210                                                 mod &= ~Modifiers.SEALED;
1211                                         } else {
1212                                                 mod |= Modifiers.VIRTUAL;
1213                                         }
1214                                 } else {
1215                                         mod |= Modifiers.OVERRIDE;
1216                                 }
1217                         }
1218
1219                         return mod;
1220                 }
1221         }
1222
1223         abstract class ImportedDefinition : IMemberDefinition
1224         {
1225                 protected class AttributesBag
1226                 {
1227                         public static readonly AttributesBag Default = new AttributesBag ();
1228
1229                         public AttributeUsageAttribute AttributeUsage;
1230                         public ObsoleteAttribute Obsolete;
1231                         public string[] Conditionals;
1232                         public string DefaultIndexerName;
1233                         public bool? CLSAttributeValue;
1234                         public TypeSpec CoClass;
1235                         
1236                         public static AttributesBag Read (MemberInfo mi, MetadataImporter importer)
1237                         {
1238                                 AttributesBag bag = null;
1239                                 List<string> conditionals = null;
1240
1241                                 // It should not throw any loading exception
1242                                 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (mi);
1243
1244                                 foreach (var a in attrs) {
1245                                         var dt = a.Constructor.DeclaringType;
1246                                         string name = dt.Name;
1247                                         if (name == "ObsoleteAttribute") {
1248                                                 if (dt.Namespace != "System")
1249                                                         continue;
1250
1251                                                 if (bag == null)
1252                                                         bag = new AttributesBag ();
1253
1254                                                 var args = a.ConstructorArguments;
1255
1256                                                 if (args.Count == 1) {
1257                                                         bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value);
1258                                                 } else if (args.Count == 2) {
1259                                                         bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value, (bool) args[1].Value);
1260                                                 } else {
1261                                                         bag.Obsolete = new ObsoleteAttribute ();
1262                                                 }
1263
1264                                                 continue;
1265                                         }
1266
1267                                         if (name == "ConditionalAttribute") {
1268                                                 if (dt.Namespace != "System.Diagnostics")
1269                                                         continue;
1270
1271                                                 if (bag == null)
1272                                                         bag = new AttributesBag ();
1273
1274                                                 if (conditionals == null)
1275                                                         conditionals = new List<string> (2);
1276
1277                                                 conditionals.Add ((string) a.ConstructorArguments[0].Value);
1278                                                 continue;
1279                                         }
1280
1281                                         if (name == "CLSCompliantAttribute") {
1282                                                 if (dt.Namespace != "System")
1283                                                         continue;
1284
1285                                                 if (bag == null)
1286                                                         bag = new AttributesBag ();
1287
1288                                                 bag.CLSAttributeValue = (bool) a.ConstructorArguments[0].Value;
1289                                                 continue;
1290                                         }
1291
1292                                         // Type only attributes
1293                                         if (mi.MemberType == MemberTypes.TypeInfo || mi.MemberType == MemberTypes.NestedType) {
1294                                                 if (name == "DefaultMemberAttribute") {
1295                                                         if (dt.Namespace != "System.Reflection")
1296                                                                 continue;
1297
1298                                                         if (bag == null)
1299                                                                 bag = new AttributesBag ();
1300
1301                                                         bag.DefaultIndexerName = (string) a.ConstructorArguments[0].Value;
1302                                                         continue;
1303                                                 }
1304
1305                                                 if (name == "AttributeUsageAttribute") {
1306                                                         if (dt.Namespace != "System")
1307                                                                 continue;
1308
1309                                                         if (bag == null)
1310                                                                 bag = new AttributesBag ();
1311
1312                                                         bag.AttributeUsage = new AttributeUsageAttribute ((AttributeTargets) a.ConstructorArguments[0].Value);
1313                                                         foreach (var named in a.NamedArguments) {
1314                                                                 if (named.MemberInfo.Name == "AllowMultiple")
1315                                                                         bag.AttributeUsage.AllowMultiple = (bool) named.TypedValue.Value;
1316                                                                 else if (named.MemberInfo.Name == "Inherited")
1317                                                                         bag.AttributeUsage.Inherited = (bool) named.TypedValue.Value;
1318                                                         }
1319                                                         continue;
1320                                                 }
1321
1322                                                 // Interface only attribute
1323                                                 if (name == "CoClassAttribute") {
1324                                                         if (dt.Namespace != "System.Runtime.InteropServices")
1325                                                                 continue;
1326
1327                                                         if (bag == null)
1328                                                                 bag = new AttributesBag ();
1329
1330                                                         bag.CoClass = importer.ImportType ((MetaType) a.ConstructorArguments[0].Value);
1331                                                         continue;
1332                                                 }
1333                                         }
1334                                 }
1335
1336                                 if (bag == null)
1337                                         return Default;
1338
1339                                 if (conditionals != null)
1340                                         bag.Conditionals = conditionals.ToArray ();
1341                                 
1342                                 return bag;
1343                         }
1344                 }
1345
1346                 protected readonly MemberInfo provider;
1347                 protected AttributesBag cattrs;
1348                 protected readonly MetadataImporter importer;
1349
1350                 public ImportedDefinition (MemberInfo provider, MetadataImporter importer)
1351                 {
1352                         this.provider = provider;
1353                         this.importer = importer;
1354                 }
1355
1356                 #region Properties
1357
1358                 public bool IsImported {
1359                         get {
1360                                 return true;
1361                         }
1362                 }
1363
1364                 public virtual string Name {
1365                         get {
1366                                 return provider.Name;
1367                         }
1368                 }
1369
1370                 #endregion
1371
1372                 public string[] ConditionalConditions ()
1373                 {
1374                         if (cattrs == null)
1375                                 ReadAttributes ();
1376
1377                         return cattrs.Conditionals;
1378                 }
1379
1380                 public ObsoleteAttribute GetAttributeObsolete ()
1381                 {
1382                         if (cattrs == null)
1383                                 ReadAttributes ();
1384
1385                         return cattrs.Obsolete;
1386                 }
1387
1388                 public bool? CLSAttributeValue {
1389                         get {
1390                                 if (cattrs == null)
1391                                         ReadAttributes ();
1392
1393                                 return cattrs.CLSAttributeValue;
1394                         }
1395                 }
1396
1397                 protected void ReadAttributes ()
1398                 {
1399                         cattrs = AttributesBag.Read (provider, importer);
1400                 }
1401
1402                 public void SetIsAssigned ()
1403                 {
1404                         // Unused for imported members
1405                 }
1406
1407                 public void SetIsUsed ()
1408                 {
1409                         // Unused for imported members
1410                 }
1411         }
1412
1413         public class ImportedModuleDefinition
1414         {
1415                 readonly Module module;
1416                 bool cls_compliant;
1417                 
1418                 public ImportedModuleDefinition (Module module)
1419                 {
1420                         this.module = module;
1421                 }
1422
1423                 #region Properties
1424
1425                 public bool IsCLSCompliant {
1426                         get {
1427                                 return cls_compliant;
1428                         }
1429                 }
1430
1431                 public string Name {
1432                         get {
1433                                 return module.Name;
1434                         }
1435                 }
1436
1437                 #endregion
1438
1439                 public void ReadAttributes ()
1440                 {
1441                         IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (module);
1442
1443                         foreach (var a in attrs) {
1444                                 var dt = a.Constructor.DeclaringType;
1445                                 if (dt.Name == "CLSCompliantAttribute") {
1446                                         if (dt.Namespace != "System")
1447                                                 continue;
1448
1449                                         cls_compliant = (bool) a.ConstructorArguments[0].Value;
1450                                         continue;
1451                                 }
1452                         }
1453                 }
1454
1455                 //
1456                 // Reads assembly attributes which where attached to a special type because
1457                 // module does have assembly manifest
1458                 //
1459                 public List<Attribute> ReadAssemblyAttributes ()
1460                 {
1461                         var t = module.GetType (AssemblyAttributesPlaceholder.GetGeneratedName (Name));
1462                         if (t == null)
1463                                 return null;
1464
1465                         var field = t.GetField (AssemblyAttributesPlaceholder.AssemblyFieldName, BindingFlags.NonPublic | BindingFlags.Static);
1466                         if (field == null)
1467                                 return null;
1468
1469                         // TODO: implement, the idea is to fabricate specil Attribute class and
1470                         // add it to OptAttributes before resolving the source code attributes
1471                         // Need to build module location as well for correct error reporting
1472
1473                         //var assembly_attributes = CustomAttributeData.GetCustomAttributes (field);
1474                         //var attrs = new List<Attribute> (assembly_attributes.Count);
1475                         //foreach (var a in assembly_attributes)
1476                         //{
1477                         //    var type = metaImporter.ImportType (a.Constructor.DeclaringType);
1478                         //    var ctor = metaImporter.CreateMethod (a.Constructor, type);
1479
1480                         //    foreach (var carg in a.ConstructorArguments) {
1481                         //        carg.Value
1482                         //    }
1483
1484                         //    attrs.Add (new Attribute ("assembly", ctor, null, Location.Null, true));
1485                         //}
1486
1487                         return null;
1488                 }
1489         }
1490
1491         public class ImportedAssemblyDefinition : IAssemblyDefinition
1492         {
1493                 readonly Assembly assembly;
1494                 readonly AssemblyName aname;
1495                 bool cls_compliant;
1496                 bool contains_extension_methods;
1497
1498                 List<AssemblyName> internals_visible_to;
1499                 Dictionary<IAssemblyDefinition, AssemblyName> internals_visible_to_cache;
1500
1501                 public ImportedAssemblyDefinition (Assembly assembly)
1502                 {
1503                         this.assembly = assembly;
1504                         this.aname = assembly.GetName ();
1505                 }
1506
1507                 #region Properties
1508
1509                 public Assembly Assembly {
1510                         get {
1511                                 return assembly;
1512                         }
1513                 }
1514
1515                 public string FullName {
1516                         get {
1517                                 return aname.FullName;
1518                         }
1519                 }
1520
1521                 public bool HasExtensionMethod {
1522                         get {
1523                                 return contains_extension_methods;
1524                         }
1525                 }
1526
1527                 public bool HasStrongName {
1528                         get {
1529                                 return aname.GetPublicKey ().Length != 0;
1530                         }
1531                 }
1532
1533                 public bool IsMissing {
1534                         get {
1535 #if STATIC
1536                                 return assembly.__IsMissing;
1537 #else
1538                                 return false;
1539 #endif
1540                         }
1541                 }
1542
1543                 public bool IsCLSCompliant {
1544                         get {
1545                                 return cls_compliant;
1546                         }
1547                 }
1548
1549                 public string Location {
1550                         get {
1551                                 return assembly.Location;
1552                         }
1553                 }
1554
1555                 public string Name {
1556                         get {
1557                                 return aname.Name;
1558                         }
1559                 }
1560
1561                 #endregion
1562
1563                 public byte[] GetPublicKeyToken ()
1564                 {
1565                         return aname.GetPublicKeyToken ();
1566                 }
1567
1568                 public AssemblyName GetAssemblyVisibleToName (IAssemblyDefinition assembly)
1569                 {
1570                         return internals_visible_to_cache [assembly];
1571                 }
1572
1573                 public bool IsFriendAssemblyTo (IAssemblyDefinition assembly)
1574                 {
1575                         if (internals_visible_to == null)
1576                                 return false;
1577
1578                         AssemblyName is_visible = null;
1579                         if (internals_visible_to_cache == null) {
1580                                 internals_visible_to_cache = new Dictionary<IAssemblyDefinition, AssemblyName> ();
1581                         } else {
1582                                 if (internals_visible_to_cache.TryGetValue (assembly, out is_visible))
1583                                         return is_visible != null;
1584                         }
1585
1586                         var token = assembly.GetPublicKeyToken ();
1587                         if (token != null && token.Length == 0)
1588                                 token = null;
1589
1590                         foreach (var internals in internals_visible_to) {
1591                                 if (internals.Name != assembly.Name)
1592                                         continue;
1593
1594                                 if (token == null && assembly is AssemblyDefinition) {
1595                                         is_visible = internals;
1596                                         break;
1597                                 }
1598
1599                                 if (!ArrayComparer.IsEqual (token, internals.GetPublicKeyToken ()))
1600                                         continue;
1601
1602                                 is_visible = internals;
1603                                 break;
1604                         }
1605
1606                         internals_visible_to_cache.Add (assembly, is_visible);
1607                         return is_visible != null;
1608                 }
1609
1610                 public void ReadAttributes ()
1611                 {
1612 #if STATIC
1613                         if (assembly.__IsMissing)
1614                                 return;
1615 #endif
1616
1617                         IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (assembly);
1618
1619                         foreach (var a in attrs) {
1620                                 var dt = a.Constructor.DeclaringType;
1621                                 var name = dt.Name;
1622                                 if (name == "CLSCompliantAttribute") {
1623                                         if (dt.Namespace == "System") {
1624                                                 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1625                                         }
1626                                         continue;
1627                                 }
1628
1629                                 if (name == "InternalsVisibleToAttribute") {
1630                                         if (dt.Namespace != MetadataImporter.CompilerServicesNamespace)
1631                                                 continue;
1632
1633                                         string s = a.ConstructorArguments[0].Value as string;
1634                                         if (s == null)
1635                                                 continue;
1636
1637                                         var an = new AssemblyName (s);
1638                                         if (internals_visible_to == null)
1639                                                 internals_visible_to = new List<AssemblyName> ();
1640
1641                                         internals_visible_to.Add (an);
1642                                         continue;
1643                                 }
1644
1645                                 if (name == "ExtensionAttribute") {
1646                                         if (dt.Namespace == MetadataImporter.CompilerServicesNamespace)
1647                                                 contains_extension_methods = true;
1648
1649                                         continue;
1650                                 }
1651                         }
1652                 }
1653
1654                 public override string ToString ()
1655                 {
1656                         return FullName;
1657                 }
1658         }
1659
1660         class ImportedMemberDefinition : ImportedDefinition
1661         {
1662                 readonly TypeSpec type;
1663
1664                 public ImportedMemberDefinition (MemberInfo member, TypeSpec type, MetadataImporter importer)
1665                         : base (member, importer)
1666                 {
1667                         this.type = type;
1668                 }
1669
1670                 #region Properties
1671
1672                 public TypeSpec MemberType {
1673                         get {
1674                                 return type;
1675                         }
1676                 }
1677
1678                 #endregion
1679         }
1680
1681         class ImportedParameterMemberDefinition : ImportedMemberDefinition, IParametersMember
1682         {
1683                 readonly AParametersCollection parameters;
1684
1685                 public ImportedParameterMemberDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1686                         : base (provider, type, importer)
1687                 {
1688                         this.parameters = parameters;
1689                 }
1690
1691                 public ImportedParameterMemberDefinition (PropertyInfo provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1692                         : base (provider, type, importer)
1693                 {
1694                         this.parameters = parameters;
1695                 }
1696
1697                 #region Properties
1698
1699                 public AParametersCollection Parameters {
1700                         get {
1701                                 return parameters;
1702                         }
1703                 }
1704
1705                 #endregion
1706         }
1707
1708         class ImportedGenericMethodDefinition : ImportedParameterMemberDefinition, IGenericMethodDefinition
1709         {
1710                 readonly TypeParameterSpec[] tparams;
1711
1712                 public ImportedGenericMethodDefinition (MethodInfo provider, TypeSpec type, AParametersCollection parameters, TypeParameterSpec[] tparams, MetadataImporter importer)
1713                         : base (provider, type, parameters, importer)
1714                 {
1715                         this.tparams = tparams;
1716                 }
1717
1718                 #region Properties
1719
1720                 public TypeParameterSpec[] TypeParameters {
1721                         get {
1722                                 return tparams;
1723                         }
1724                 }
1725
1726                 public int TypeParametersCount {
1727                         get {
1728                                 return tparams.Length;
1729                         }
1730                 }
1731
1732                 #endregion
1733         }
1734
1735         class ImportedTypeDefinition : ImportedDefinition, ITypeDefinition
1736         {
1737                 TypeParameterSpec[] tparams;
1738                 string name;
1739
1740                 public ImportedTypeDefinition (MetaType type, MetadataImporter importer)
1741                         : base (type, importer)
1742                 {
1743                 }
1744
1745                 #region Properties
1746
1747                 public IAssemblyDefinition DeclaringAssembly {
1748                         get {
1749                                 return importer.GetAssemblyDefinition (provider.Module.Assembly);
1750                         }
1751                 }
1752
1753                 bool ITypeDefinition.IsPartial {
1754                         get {
1755                                 return false;
1756                         }
1757                 }
1758
1759                 public override string Name {
1760                         get {
1761                                 if (name == null) {
1762                                         name = base.Name;
1763                                         if (tparams != null) {
1764                                                 int arity_start = name.IndexOf ('`');
1765                                                 if (arity_start > 0)
1766                                                         name = name.Substring (0, arity_start);
1767                                         }
1768                                 }
1769
1770                                 return name;
1771                         }
1772                 }
1773
1774                 public string Namespace {
1775                         get {
1776                                 return ((MetaType) provider).Namespace;
1777                         }
1778                 }
1779
1780                 public int TypeParametersCount {
1781                         get {
1782                                 return tparams == null ? 0 : tparams.Length;
1783                         }
1784                 }
1785
1786                 public TypeParameterSpec[] TypeParameters {
1787                         get {
1788                                 return tparams;
1789                         }
1790                         set {
1791                                 tparams = value;
1792                         }
1793                 }
1794
1795                 #endregion
1796
1797                 public static void Error_MissingDependency (IMemberContext ctx, List<TypeSpec> types, Location loc)
1798                 {
1799                         // 
1800                         // Report details about missing type and most likely cause of the problem.
1801                         // csc reports 1683, 1684 as warnings but we report them only when used
1802                         // or referenced from the user core in which case compilation error has to
1803                         // be reported because compiler cannot continue anyway
1804                         //
1805                         foreach (var t in types) {
1806                                 string name = t.GetSignatureForError ();
1807
1808                                 if (t.MemberDefinition.DeclaringAssembly == ctx.Module.DeclaringAssembly) {
1809                                         ctx.Module.Compiler.Report.Error (1683, loc,
1810                                                 "Reference to type `{0}' claims it is defined in this assembly, but it is not defined in source or any added modules",
1811                                                 name);
1812                                 } else if (t.MemberDefinition.DeclaringAssembly.IsMissing) {
1813                                         ctx.Module.Compiler.Report.Error (12, loc,
1814                                                 "The type `{0}' is defined in an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
1815                                                 name, t.MemberDefinition.DeclaringAssembly.FullName);
1816                                 } else {
1817                                         ctx.Module.Compiler.Report.Error (1684, loc,
1818                                                 "Reference to type `{0}' claims it is defined assembly `{1}', but it could not be found",
1819                                                 name, t.MemberDefinition.DeclaringAssembly.FullName);
1820                                 }
1821                         }
1822                 }
1823
1824                 public TypeSpec GetAttributeCoClass ()
1825                 {
1826                         if (cattrs == null)
1827                                 ReadAttributes ();
1828
1829                         return cattrs.CoClass;
1830                 }
1831
1832                 public string GetAttributeDefaultMember ()
1833                 {
1834                         if (cattrs == null)
1835                                 ReadAttributes ();
1836
1837                         return cattrs.DefaultIndexerName;
1838                 }
1839
1840                 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
1841                 {
1842                         if (cattrs == null)
1843                                 ReadAttributes ();
1844
1845                         return cattrs.AttributeUsage;
1846                 }
1847
1848                 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
1849                 {
1850                         var a = importer.GetAssemblyDefinition (provider.Module.Assembly);
1851                         return a == assembly || a.IsFriendAssemblyTo (assembly);
1852                 }
1853
1854                 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
1855                 {
1856                         //
1857                         // Not interested in members of nested private types unless the importer needs them
1858                         //
1859                         if (declaringType.IsPrivate && importer.IgnorePrivateMembers) {
1860                                 cache = MemberCache.Empty;
1861                                 return;
1862                         }
1863
1864                         var loading_type = (MetaType) provider;
1865                         const BindingFlags all_members = BindingFlags.DeclaredOnly |
1866                                 BindingFlags.Static | BindingFlags.Instance |
1867                                 BindingFlags.Public | BindingFlags.NonPublic;
1868
1869                         const MethodAttributes explicit_impl = MethodAttributes.NewSlot |
1870                                         MethodAttributes.Virtual | MethodAttributes.HideBySig |
1871                                         MethodAttributes.Final;
1872
1873                         Dictionary<MethodBase, MethodSpec> possible_accessors = null;
1874                         List<EventSpec> imported_events = null;
1875                         EventSpec event_spec;
1876                         MemberSpec imported;
1877                         MethodInfo m;
1878                         MemberInfo[] all;
1879                         try {
1880                                 all = loading_type.GetMembers (all_members);
1881                         } catch (Exception e) {
1882                                 throw new InternalErrorException (e, "Could not import type `{0}' from `{1}'",
1883                                         declaringType.GetSignatureForError (), declaringType.MemberDefinition.DeclaringAssembly.FullName);
1884                         }
1885
1886                         if (cache == null) {
1887                                 cache = new MemberCache (all.Length);
1888
1889                                 //
1890                                 // Do the types first as they can be referenced by the members before
1891                                 // they are found or inflated
1892                                 //
1893                                 foreach (var member in all) {
1894                                         if (member.MemberType != MemberTypes.NestedType)
1895                                                 continue;
1896
1897                                         var t = (MetaType) member;
1898
1899                                         // Ignore compiler generated types, mostly lambda containers
1900                                         if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
1901                                                 continue;
1902
1903                                         try {
1904                                                 imported = importer.CreateNestedType (t, declaringType);
1905                                         } catch (Exception e) {
1906                                                 throw new InternalErrorException (e, "Could not import nested type `{0}' from `{1}'",
1907                                                         t.FullName, declaringType.MemberDefinition.DeclaringAssembly.FullName);
1908                                         }
1909
1910                                         cache.AddMemberImported (imported);
1911                                 }
1912
1913                                 foreach (var member in all) {
1914                                         if (member.MemberType != MemberTypes.NestedType)
1915                                                 continue;
1916
1917                                         var t = (MetaType) member;
1918
1919                                         if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
1920                                                 continue;
1921
1922                                         importer.ImportTypeBase (t);
1923                                 }
1924                         }
1925
1926                         //
1927                         // Load base interfaces first to minic behaviour of compiled members
1928                         //
1929                         if (declaringType.IsInterface && declaringType.Interfaces != null) {
1930                                 foreach (var iface in declaringType.Interfaces) {
1931                                         cache.AddInterface (iface);
1932                                 }
1933                         }
1934
1935                         if (!onlyTypes) {
1936                                 //
1937                                 // The logic here requires methods to be returned first which seems to work for both Mono and .NET
1938                                 //
1939                                 foreach (var member in all) {
1940                                         switch (member.MemberType) {
1941                                         case MemberTypes.Constructor:
1942                                         case MemberTypes.Method:
1943                                                 MethodBase mb = (MethodBase) member;
1944                                                 var attrs = mb.Attributes;
1945
1946                                                 if ((attrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) {
1947                                                         if (importer.IgnorePrivateMembers)
1948                                                                 continue;
1949
1950                                                         // Ignore explicitly implemented members
1951                                                         if ((attrs & explicit_impl) == explicit_impl)
1952                                                                 continue;
1953
1954                                                         // Ignore compiler generated methods
1955                                                         if (MetadataImporter.HasAttribute (CustomAttributeData.GetCustomAttributes (mb), "CompilerGeneratedAttribute", MetadataImporter.CompilerServicesNamespace))
1956                                                                 continue;
1957                                                 }
1958
1959                                                 imported = importer.CreateMethod (mb, declaringType);
1960                                                 if (imported.Kind == MemberKind.Method && !imported.IsGeneric) {
1961                                                         if (possible_accessors == null)
1962                                                                 possible_accessors = new Dictionary<MethodBase, MethodSpec> (ReferenceEquality<MethodBase>.Default);
1963
1964                                                         // There are no metadata rules for accessors, we have to consider any method as possible candidate
1965                                                         possible_accessors.Add (mb, (MethodSpec) imported);
1966                                                 }
1967
1968                                                 break;
1969                                         case MemberTypes.Property:
1970                                                 if (possible_accessors == null)
1971                                                         continue;
1972
1973                                                 var p = (PropertyInfo) member;
1974                                                 //
1975                                                 // Links possible accessors with property
1976                                                 //
1977                                                 MethodSpec get, set;
1978                                                 m = p.GetGetMethod (true);
1979                                                 if (m == null || !possible_accessors.TryGetValue (m, out get))
1980                                                         get = null;
1981
1982                                                 m = p.GetSetMethod (true);
1983                                                 if (m == null || !possible_accessors.TryGetValue (m, out set))
1984                                                         set = null;
1985
1986                                                 // No accessors registered (e.g. explicit implementation)
1987                                                 if (get == null && set == null)
1988                                                         continue;
1989
1990                                                 imported = importer.CreateProperty (p, declaringType, get, set);
1991                                                 if (imported == null)
1992                                                         continue;
1993
1994                                                 break;
1995                                         case MemberTypes.Event:
1996                                                 if (possible_accessors == null)
1997                                                         continue;
1998
1999                                                 var e = (EventInfo) member;
2000                                                 //
2001                                                 // Links accessors with event
2002                                                 //
2003                                                 MethodSpec add, remove;
2004                                                 m = e.GetAddMethod (true);
2005                                                 if (m == null || !possible_accessors.TryGetValue (m, out add))
2006                                                         add = null;
2007
2008                                                 m = e.GetRemoveMethod (true);
2009                                                 if (m == null || !possible_accessors.TryGetValue (m, out remove))
2010                                                         remove = null;
2011
2012                                                 // Both accessors are required
2013                                                 if (add == null || remove == null)
2014                                                         continue;
2015
2016                                                 event_spec = importer.CreateEvent (e, declaringType, add, remove);
2017                                                 if (!importer.IgnorePrivateMembers) {
2018                                                         if (imported_events == null)
2019                                                                 imported_events = new List<EventSpec> ();
2020
2021                                                         imported_events.Add (event_spec);
2022                                                 }
2023
2024                                                 imported = event_spec;
2025                                                 break;
2026                                         case MemberTypes.Field:
2027                                                 var fi = (FieldInfo) member;
2028
2029                                                 imported = importer.CreateField (fi, declaringType);
2030                                                 if (imported == null)
2031                                                         continue;
2032
2033                                                 //
2034                                                 // For dynamic binder event has to be fully restored to allow operations
2035                                                 // within the type container to work correctly
2036                                                 //
2037                                                 if (imported_events != null) {
2038                                                         // The backing event field should be private but it may not
2039                                                         int i;
2040                                                         for (i = 0; i < imported_events.Count; ++i) {
2041                                                                 var ev = imported_events[i];
2042                                                                 if (ev.Name == fi.Name) {
2043                                                                         ev.BackingField = (FieldSpec) imported;
2044                                                                         imported_events.RemoveAt (i);
2045                                                                         i = -1;
2046                                                                         break;
2047                                                                 }
2048                                                         }
2049
2050                                                         if (i < 0)
2051                                                                 continue;
2052                                                 }
2053
2054                                                 break;
2055                                         case MemberTypes.NestedType:
2056                                                 // Already in the cache from the first pass
2057                                                 continue;
2058                                         default:
2059                                                 throw new NotImplementedException (member.ToString ());
2060                                         }
2061
2062                                         cache.AddMemberImported (imported);
2063                                 }
2064                         }
2065                 }
2066         }
2067
2068         class ImportedTypeParameterDefinition : ImportedDefinition, ITypeDefinition
2069         {
2070                 public ImportedTypeParameterDefinition (MetaType type, MetadataImporter importer)
2071                         : base (type, importer)
2072                 {
2073                 }
2074
2075                 #region Properties
2076
2077                 public IAssemblyDefinition DeclaringAssembly {
2078                         get {
2079                                 throw new NotImplementedException ();
2080                         }
2081                 }
2082
2083                 bool ITypeDefinition.IsPartial {
2084                         get {
2085                                 return false;
2086                         }
2087                 }
2088
2089                 public string Namespace {
2090                         get {
2091                                 return null;
2092                         }
2093                 }
2094
2095                 public int TypeParametersCount {
2096                         get {
2097                                 return 0;
2098                         }
2099                 }
2100
2101                 public TypeParameterSpec[] TypeParameters {
2102                         get {
2103                                 return null;
2104                         }
2105                 }
2106
2107                 #endregion
2108
2109                 public TypeSpec GetAttributeCoClass ()
2110                 {
2111                         return null;
2112                 }
2113
2114                 public string GetAttributeDefaultMember ()
2115                 {
2116                         throw new NotSupportedException ();
2117                 }
2118
2119                 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
2120                 {
2121                         throw new NotSupportedException ();
2122                 }
2123
2124                 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2125                 {
2126                         throw new NotImplementedException ();
2127                 }
2128
2129                 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2130                 {
2131                         throw new NotImplementedException ();
2132                 }
2133         }
2134 }