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