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