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