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