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