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