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