[mcs] Implements C# 7.2 readonly structs
[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                                 switch (kind) {
963                                 case MemberKind.Class:
964                                         if ((ma & TypeAttributes.Sealed) != 0) {
965                                                 if ((ma & TypeAttributes.Abstract) != 0)
966                                                         mod |= Modifiers.STATIC;
967                                                 else
968                                                         mod |= Modifiers.SEALED;
969                                         } else if ((ma & TypeAttributes.Abstract) != 0) {
970                                                 mod |= Modifiers.ABSTRACT;
971                                         }
972                                         break;
973                                 case MemberKind.Struct:
974                                         if (HasAttribute (CustomAttributeData.GetCustomAttributes (type), "IsReadOnlyAttribute", CompilerServicesNamespace)) {
975                                                 mod |= Modifiers.READONLY;
976                                         }
977
978                                         break;
979                                 }
980                         }
981
982                         var definition = new ImportedTypeDefinition (type, this);
983                         TypeSpec pt;
984
985                         if (kind == MemberKind.Enum) {
986                                 const BindingFlags underlying_member = BindingFlags.DeclaredOnly |
987                                         BindingFlags.Instance |
988                                         BindingFlags.Public | BindingFlags.NonPublic;
989
990                                 var type_members = type.GetFields (underlying_member);
991                                 foreach (var type_member in type_members) {
992                                         spec = new EnumSpec (declaringType, definition, CreateType (type_member.FieldType), type, mod);
993                                         break;
994                                 }
995
996                                 if (spec == null)
997                                         kind = MemberKind.Class;
998
999                         } else if (kind == MemberKind.TypeParameter) {
1000                                 spec = CreateTypeParameter (type, declaringType);
1001                         } else if (type.IsGenericTypeDefinition) {
1002                                 definition.TypeParameters = CreateGenericParameters (type, declaringType);
1003                         } else if (compiled_types.TryGetValue (type, out pt)) {
1004                                 //
1005                                 // Same type was found in inside compiled types. It's
1006                                 // either build-in type or forward referenced typed
1007                                 // which point into just compiled assembly.
1008                                 //
1009                                 spec = pt;
1010                                 BuiltinTypeSpec bts = pt as BuiltinTypeSpec;
1011                                 if (bts != null)
1012                                         bts.SetDefinition (definition, type, mod);
1013                         }
1014
1015                         if (spec == null)
1016                                 spec = new TypeSpec (kind, declaringType, definition, type, mod);
1017
1018                         import_cache.Add (type, spec);
1019
1020                         if (kind == MemberKind.TypeParameter) {
1021                                 if (canImportBaseType)
1022                                         ImportTypeParameterTypeConstraints ((TypeParameterSpec) spec, type);
1023
1024                                 return spec;
1025                         }
1026
1027                         //
1028                         // Two stage setup as the base type can be inflated declaring type or
1029                         // another nested type inside same declaring type which has not been
1030                         // loaded, therefore we can import a base type of nested types once
1031                         // the types have been imported
1032                         //
1033                         if (canImportBaseType)
1034                                 ImportTypeBase (spec, type);
1035
1036                         return spec;
1037                 }
1038
1039                 public IAssemblyDefinition GetAssemblyDefinition (Assembly assembly)
1040                 {
1041                         IAssemblyDefinition found;
1042                         if (!assembly_2_definition.TryGetValue (assembly, out found)) {
1043
1044                                 // This can happen in dynamic context only
1045                                 var def = new ImportedAssemblyDefinition (assembly);
1046                                 assembly_2_definition.Add (assembly, def);
1047                                 def.ReadAttributes ();
1048                                 found = def;
1049                         }
1050
1051                         return found;
1052                 }
1053
1054                 public ImportedAssemblyDefinition GetImportedAssemblyDefinition (AssemblyName assemblyName)
1055                 {
1056                         foreach (var a in Assemblies) {
1057                                 var ia = a as ImportedAssemblyDefinition;
1058                                 if (ia == null)
1059                                         continue;
1060                                 
1061                                 if (a.Name == assemblyName.Name)
1062                                         return ia;
1063                         }
1064
1065                         return null;
1066                 }
1067
1068
1069                 public void ImportTypeBase (MetaType type)
1070                 {
1071                         TypeSpec spec = import_cache[type];
1072                         if (spec != null)
1073                                 ImportTypeBase (spec, type);
1074                 }
1075
1076                 TypeParameterSpec CreateTypeParameter (MetaType type, TypeSpec declaringType)
1077                 {
1078                         Variance variance;
1079                         switch (type.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) {
1080                         case GenericParameterAttributes.Covariant:
1081                                 variance = Variance.Covariant;
1082                                 break;
1083                         case GenericParameterAttributes.Contravariant:
1084                                 variance = Variance.Contravariant;
1085                                 break;
1086                         default:
1087                                 variance = Variance.None;
1088                                 break;
1089                         }
1090
1091                         SpecialConstraint special = SpecialConstraint.None;
1092                         var import_special = type.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask;
1093
1094                         if ((import_special & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) {
1095                                 special |= SpecialConstraint.Struct;
1096                         } else if ((import_special & GenericParameterAttributes.DefaultConstructorConstraint) != 0) {
1097                                 special = SpecialConstraint.Constructor;
1098                         }
1099
1100                         if ((import_special & GenericParameterAttributes.ReferenceTypeConstraint) != 0) {
1101                                 special |= SpecialConstraint.Class;
1102                         }
1103
1104                         TypeParameterSpec spec;
1105                         var def = new ImportedTypeParameterDefinition (type, this);
1106                         if (type.DeclaringMethod != null) {
1107                                 spec = new TypeParameterSpec (type.GenericParameterPosition, def, special, variance, type);
1108                         } else {
1109                                 spec = new TypeParameterSpec (declaringType, type.GenericParameterPosition, def, special, variance, type);
1110                         }
1111
1112                         return spec;
1113                 }
1114
1115                 //
1116                 // Test for a custom attribute type match. Custom attributes are not really predefined globaly 
1117                 // they can be assembly specific therefore we do check based on names only
1118                 //
1119                 public static bool HasAttribute (IList<CustomAttributeData> attributesData, string attrName, string attrNamespace)
1120                 {
1121                         if (attributesData.Count == 0)
1122                                 return false;
1123
1124                         foreach (var attr in attributesData) {
1125                                 var dt = attr.Constructor.DeclaringType;
1126                                 if (dt.Name == attrName && dt.Namespace == attrNamespace)
1127                                         return true;
1128                         }
1129
1130                         return false;
1131                 }
1132
1133                 void ImportTypeBase (TypeSpec spec, MetaType type)
1134                 {
1135                         if (spec.Kind == MemberKind.Interface)
1136                                 spec.BaseType = module.Compiler.BuiltinTypes.Object;
1137                         else if (type.BaseType != null) {
1138                                 TypeSpec base_type;
1139                                 if (!IsMissingType (type.BaseType) && type.BaseType.IsGenericType)
1140                                         base_type = CreateType (type.BaseType, new AttributesTypeInfoReader (type), true);
1141                                 else
1142                                         base_type = CreateType (type.BaseType);
1143
1144                                 spec.BaseType = base_type;
1145                         }
1146
1147                         if (spec.MemberDefinition.TypeParametersCount > 0) {
1148                                 foreach (var tp in spec.MemberDefinition.TypeParameters) {
1149                                         ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
1150                                 }
1151                         }
1152                 }
1153
1154                 public void ImportTypes (MetaType[] types, Namespace targetNamespace, bool importExtensionTypes)
1155                 {
1156                         Namespace ns = targetNamespace;
1157                         string prev_namespace = null;
1158                         foreach (var t in types) {
1159                                 if (t == null)
1160                                         continue;
1161
1162                                 // Be careful not to trigger full parent type loading
1163                                 if (t.MemberType == MemberTypes.NestedType)
1164                                         continue;
1165
1166                                 if (t.Name[0] == '<')
1167                                         continue;
1168
1169                                 var it = CreateType (t, null, new AttributesTypeInfoReader (t), true);
1170                                 if (it == null)
1171                                         continue;
1172
1173                                 if (prev_namespace != t.Namespace) {
1174                                         ns = t.Namespace == null ? targetNamespace : targetNamespace.GetNamespace (t.Namespace, true);
1175                                         prev_namespace = t.Namespace;
1176                                 }
1177
1178                                 // Cannot rely on assembly level Extension attribute or static modifier because they
1179                                 // are not followed by other compilers (e.g. F#).
1180                                 if (it.IsClass && it.Arity == 0 && importExtensionTypes &&
1181                                         HasAttribute (CustomAttributeData.GetCustomAttributes (t), "ExtensionAttribute", CompilerServicesNamespace)) {
1182                                         it.SetExtensionMethodContainer ();
1183                                 }
1184
1185                                 ns.AddType (module, it);
1186                         }
1187                 }
1188
1189                 void ImportTypeParameterTypeConstraints (TypeParameterSpec spec, MetaType type)
1190                 {
1191                         var constraints = type.GetGenericParameterConstraints ();
1192                         List<TypeSpec> tparams = null;
1193                         foreach (var ct in constraints) {
1194                                 if (ct.IsGenericParameter) {
1195                                         if (tparams == null)
1196                                                 tparams = new List<TypeSpec> ();
1197
1198                                         tparams.Add (CreateType (ct));
1199                                         continue;
1200                                 }
1201
1202                                 var constraint_type = CreateType (ct);
1203                                 if (constraint_type.IsClass) {
1204                                         spec.BaseType = constraint_type;
1205                                         continue;
1206                                 }
1207
1208                                 spec.AddInterface (constraint_type);
1209                         }
1210
1211                         if (spec.BaseType == null)
1212                                 spec.BaseType = module.Compiler.BuiltinTypes.Object;
1213
1214                         if (tparams != null)
1215                                 spec.TypeArguments = tparams.ToArray ();
1216                 }
1217
1218                 Constant ImportConstant (object value)
1219                 {
1220                         //
1221                         // Get type of underlying value as int constant can be used for object
1222                         // parameter type. This is not allowed in C# but other languages can do that
1223                         //
1224                         var types = module.Compiler.BuiltinTypes;
1225                         switch (System.Type.GetTypeCode (value.GetType ())) {
1226                         case TypeCode.Boolean:
1227                                 return new BoolConstant (types, (bool) value, Location.Null);
1228                         case TypeCode.Byte:
1229                                 return new ByteConstant (types, (byte) value, Location.Null);
1230                         case TypeCode.Char:
1231                                 return new CharConstant (types, (char) value, Location.Null);
1232                         case TypeCode.Decimal:
1233                                 return new DecimalConstant (types, (decimal) value, Location.Null);
1234                         case TypeCode.Double:
1235                                 return new DoubleConstant (types, (double) value, Location.Null);
1236                         case TypeCode.Int16:
1237                                 return new ShortConstant (types, (short) value, Location.Null);
1238                         case TypeCode.Int32:
1239                                 return new IntConstant (types, (int) value, Location.Null);
1240                         case TypeCode.Int64:
1241                                 return new LongConstant (types, (long) value, Location.Null);
1242                         case TypeCode.SByte:
1243                                 return new SByteConstant (types, (sbyte) value, Location.Null);
1244                         case TypeCode.Single:
1245                                 return new FloatConstant (types, (float) value, Location.Null);
1246                         case TypeCode.String:
1247                                 return new StringConstant (types, (string) value, Location.Null);
1248                         case TypeCode.UInt16:
1249                                 return new UShortConstant (types, (ushort) value, Location.Null);
1250                         case TypeCode.UInt32:
1251                                 return new UIntConstant (types, (uint) value, Location.Null);
1252                         case TypeCode.UInt64:
1253                                 return new ULongConstant (types, (ulong) value, Location.Null);
1254                         }
1255
1256                         throw new NotImplementedException (value.GetType ().ToString ());
1257                 }
1258
1259                 public TypeSpec ImportType (MetaType type)
1260                 {
1261                         return ImportType (type, new AttributesTypeInfoReader (type), null);
1262                 }
1263
1264                 TypeSpec ImportType (MetaType type, AttributesTypeInfoReader dtype, TypeSpec currentType)
1265                 {
1266                         if (type.HasElementType) {
1267                                 var element = type.GetElementType ();
1268                                 ++dtype.DynamicPosition;
1269                                 var spec = ImportType (element, dtype, currentType);
1270
1271                                 if (type.IsArray)
1272                                         return ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
1273                                 if (type.IsByRef)
1274                                         return ReferenceContainer.MakeType (module, spec);
1275                                 if (type.IsPointer)
1276                                         return PointerContainer.MakeType (module, spec);
1277
1278                                 throw new NotImplementedException ("Unknown element type " + type.ToString ());
1279                         }
1280
1281                         TypeSpec compiled_type;
1282                         if (compiled_types.TryGetValue (type, out compiled_type)) {
1283                                 if (compiled_type.BuiltinType == BuiltinTypeSpec.Type.Object && dtype.IsDynamicObject ())
1284                                         return module.Compiler.BuiltinTypes.Dynamic;
1285                         } else {
1286                                 compiled_type = CreateType (type, dtype, true);
1287                         }
1288
1289                         if (currentType == compiled_type && currentType?.IsGeneric == true) {
1290                                 //
1291                                 // Inflates current type to match behaviour of TypeDefinition::CurrentType used by compiled types
1292                                 //
1293                                 var targs = compiled_type.MemberDefinition.TypeParameters;
1294                                 compiled_type = compiled_type.MakeGenericType (module, targs);
1295                         }
1296
1297                         return compiled_type;
1298                 }
1299
1300                 static bool IsMissingType (MetaType type)
1301                 {
1302 #if STATIC
1303                         return type.__IsMissing;
1304 #else
1305                         return false;
1306 #endif
1307                 }
1308
1309                 //
1310                 // Decimal constants cannot be encoded in the constant blob, and thus are marked
1311                 // as IsInitOnly ('readonly' in C# parlance).  We get its value from the 
1312                 // DecimalConstantAttribute metadata.
1313                 //
1314                 Constant ReadDecimalConstant (IList<CustomAttributeData> attrs)
1315                 {
1316                         if (attrs.Count == 0)
1317                                 return null;
1318
1319                         foreach (var ca in attrs) {
1320                                 var dt = ca.Constructor.DeclaringType;
1321                                 if (dt.Name != "DecimalConstantAttribute" || dt.Namespace != CompilerServicesNamespace)
1322                                         continue;
1323
1324                                 var value = new decimal (
1325                                         (int) (uint) ca.ConstructorArguments[4].Value,
1326                                         (int) (uint) ca.ConstructorArguments[3].Value,
1327                                         (int) (uint) ca.ConstructorArguments[2].Value,
1328                                         (byte) ca.ConstructorArguments[1].Value != 0,
1329                                         (byte) ca.ConstructorArguments[0].Value);
1330
1331                                 return new DecimalConstant (module.Compiler.BuiltinTypes, value, Location.Null);
1332                         }
1333
1334                         return null;
1335                 }
1336
1337                 static Modifiers ReadMethodModifiers (MethodBase mb, TypeSpec declaringType)
1338                 {
1339                         Modifiers mod;
1340                         var ma = mb.Attributes;
1341                         switch (ma & MethodAttributes.MemberAccessMask) {
1342                         case MethodAttributes.Public:
1343                                 mod = Modifiers.PUBLIC;
1344                                 break;
1345                         case MethodAttributes.Assembly:
1346                                 mod = Modifiers.INTERNAL;
1347                                 break;
1348                         case MethodAttributes.Family:
1349                                 mod = Modifiers.PROTECTED;
1350                                 break;
1351                         case MethodAttributes.FamORAssem:
1352                                 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
1353                                 break;
1354                         default:
1355                                 mod = Modifiers.PRIVATE;
1356                                 break;
1357                         }
1358
1359                         if ((ma & MethodAttributes.Static) != 0) {
1360                                 mod |= Modifiers.STATIC;
1361                                 return mod;
1362                         }
1363                         if ((ma & MethodAttributes.Abstract) != 0 && declaringType.IsClass) {
1364                                 mod |= Modifiers.ABSTRACT;
1365                                 return mod;
1366                         }
1367
1368                         // It can be sealed and override
1369                         if ((ma & MethodAttributes.Final) != 0)
1370                                 mod |= Modifiers.SEALED;
1371
1372                         if ((ma & MethodAttributes.Virtual) != 0) {
1373                                 // Not every member can be detected based on MethodAttribute, we
1374                                 // set virtual or non-virtual only when we are certain. Further checks
1375                                 // to really find out what `virtual' means for this member are done
1376                                 // later
1377                                 if ((ma & MethodAttributes.NewSlot) != 0) {
1378                                         if ((mod & Modifiers.SEALED) != 0) {
1379                                                 mod &= ~Modifiers.SEALED;
1380                                         } else {
1381                                                 mod |= Modifiers.VIRTUAL;
1382                                         }
1383                                 } else {
1384                                         mod |= Modifiers.OVERRIDE;
1385                                 }
1386                         }
1387
1388                         return mod;
1389                 }
1390         }
1391
1392         abstract class ImportedDefinition : IMemberDefinition
1393         {
1394                 protected class AttributesBag
1395                 {
1396                         public static readonly AttributesBag Default = new AttributesBag ();
1397
1398                         public AttributeUsageAttribute AttributeUsage;
1399                         public ObsoleteAttribute Obsolete;
1400                         public string[] Conditionals;
1401                         public string DefaultIndexerName;
1402                         public bool? CLSAttributeValue;
1403                         public TypeSpec CoClass;
1404
1405                         static bool HasMissingType (ConstructorInfo ctor)
1406                         {
1407 #if STATIC
1408                                 //
1409                                 // Mimic odd csc behaviour where missing type on predefined
1410                                 // attributes means the attribute is silently ignored. This can
1411                                 // happen with PCL facades
1412                                 //
1413                                 foreach (var p in ctor.GetParameters ()) {
1414                                         if (p.ParameterType.__ContainsMissingType)
1415                                                 return true;
1416                                 }
1417 #endif
1418
1419                                 return false;
1420                         }
1421                         
1422                         public static AttributesBag Read (MemberInfo mi, MetadataImporter importer)
1423                         {
1424                                 AttributesBag bag = null;
1425                                 List<string> conditionals = null;
1426
1427                                 // It should not throw any loading exception
1428                                 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (mi);
1429
1430                                 foreach (var a in attrs) {
1431                                         var dt = a.Constructor.DeclaringType;
1432                                         string name = dt.Name;
1433                                         if (name == "ObsoleteAttribute") {
1434                                                 if (dt.Namespace != "System")
1435                                                         continue;
1436
1437                                                 if (bag == null)
1438                                                         bag = new AttributesBag ();
1439
1440                                                 var args = a.ConstructorArguments;
1441
1442                                                 if (args.Count == 1) {
1443                                                         bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value);
1444                                                 } else if (args.Count == 2) {
1445                                                         bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value, (bool) args[1].Value);
1446                                                 } else {
1447                                                         bag.Obsolete = new ObsoleteAttribute ();
1448                                                 }
1449
1450                                                 continue;
1451                                         }
1452
1453                                         if (name == "ConditionalAttribute") {
1454                                                 if (dt.Namespace != "System.Diagnostics")
1455                                                         continue;
1456
1457                                                 if (bag == null)
1458                                                         bag = new AttributesBag ();
1459
1460                                                 if (conditionals == null)
1461                                                         conditionals = new List<string> (2);
1462
1463                                                 conditionals.Add ((string) a.ConstructorArguments[0].Value);
1464                                                 continue;
1465                                         }
1466
1467                                         if (name == "CLSCompliantAttribute") {
1468                                                 if (dt.Namespace != "System")
1469                                                         continue;
1470
1471                                                 if (bag == null)
1472                                                         bag = new AttributesBag ();
1473
1474                                                 bag.CLSAttributeValue = (bool) a.ConstructorArguments[0].Value;
1475                                                 continue;
1476                                         }
1477
1478                                         // Type only attributes
1479                                         if (mi.MemberType == MemberTypes.TypeInfo || mi.MemberType == MemberTypes.NestedType) {
1480                                                 if (name == "DefaultMemberAttribute") {
1481                                                         if (dt.Namespace != "System.Reflection")
1482                                                                 continue;
1483
1484                                                         if (bag == null)
1485                                                                 bag = new AttributesBag ();
1486
1487                                                         bag.DefaultIndexerName = (string) a.ConstructorArguments[0].Value;
1488                                                         continue;
1489                                                 }
1490
1491                                                 if (name == "AttributeUsageAttribute") {
1492                                                         if (dt.Namespace != "System")
1493                                                                 continue;
1494
1495                                                         if (HasMissingType (a.Constructor))
1496                                                                 continue;
1497
1498                                                         if (bag == null)
1499                                                                 bag = new AttributesBag ();
1500
1501                                                         bag.AttributeUsage = new AttributeUsageAttribute ((AttributeTargets) a.ConstructorArguments[0].Value);
1502                                                         foreach (var named in a.NamedArguments) {
1503                                                                 if (named.MemberInfo.Name == "AllowMultiple")
1504                                                                         bag.AttributeUsage.AllowMultiple = (bool) named.TypedValue.Value;
1505                                                                 else if (named.MemberInfo.Name == "Inherited")
1506                                                                         bag.AttributeUsage.Inherited = (bool) named.TypedValue.Value;
1507                                                         }
1508                                                         continue;
1509                                                 }
1510
1511                                                 // Interface only attribute
1512                                                 if (name == "CoClassAttribute") {
1513                                                         if (dt.Namespace != "System.Runtime.InteropServices")
1514                                                                 continue;
1515
1516                                                         if (HasMissingType (a.Constructor))
1517                                                                 continue;
1518
1519                                                         if (bag == null)
1520                                                                 bag = new AttributesBag ();
1521
1522                                                         bag.CoClass = importer.ImportType ((MetaType) a.ConstructorArguments[0].Value);
1523                                                         continue;
1524                                                 }
1525                                         }
1526                                 }
1527
1528                                 if (bag == null)
1529                                         return Default;
1530
1531                                 if (conditionals != null)
1532                                         bag.Conditionals = conditionals.ToArray ();
1533                                 
1534                                 return bag;
1535                         }
1536                 }
1537
1538                 protected readonly MemberInfo provider;
1539                 protected AttributesBag cattrs;
1540                 protected readonly MetadataImporter importer;
1541
1542                 protected ImportedDefinition (MemberInfo provider, MetadataImporter importer)
1543                 {
1544                         this.provider = provider;
1545                         this.importer = importer;
1546                 }
1547
1548                 #region Properties
1549
1550                 public bool IsImported {
1551                         get {
1552                                 return true;
1553                         }
1554                 }
1555
1556                 public virtual string Name {
1557                         get {
1558                                 return provider.Name;
1559                         }
1560                 }
1561
1562                 #endregion
1563
1564                 public string[] ConditionalConditions ()
1565                 {
1566                         if (cattrs == null)
1567                                 ReadAttributes ();
1568
1569                         return cattrs.Conditionals;
1570                 }
1571
1572                 public ObsoleteAttribute GetAttributeObsolete ()
1573                 {
1574                         if (cattrs == null)
1575                                 ReadAttributes ();
1576
1577                         return cattrs.Obsolete;
1578                 }
1579
1580                 public bool? CLSAttributeValue {
1581                         get {
1582                                 if (cattrs == null)
1583                                         ReadAttributes ();
1584
1585                                 return cattrs.CLSAttributeValue;
1586                         }
1587                 }
1588
1589                 protected void ReadAttributes ()
1590                 {
1591                         cattrs = AttributesBag.Read (provider, importer);
1592                 }
1593
1594                 public void SetIsAssigned ()
1595                 {
1596                         // Unused for imported members
1597                 }
1598
1599                 public void SetIsUsed ()
1600                 {
1601                         // Unused for imported members
1602                 }
1603         }
1604
1605         public class ImportedModuleDefinition
1606         {
1607                 readonly Module module;
1608                 bool cls_compliant;
1609                 
1610                 public ImportedModuleDefinition (Module module)
1611                 {
1612                         this.module = module;
1613                 }
1614
1615                 #region Properties
1616
1617                 public bool IsCLSCompliant {
1618                         get {
1619                                 return cls_compliant;
1620                         }
1621                 }
1622
1623                 public string Name {
1624                         get {
1625                                 return module.Name;
1626                         }
1627                 }
1628
1629                 #endregion
1630
1631                 public void ReadAttributes ()
1632                 {
1633                         IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (module);
1634
1635                         foreach (var a in attrs) {
1636                                 var dt = a.Constructor.DeclaringType;
1637                                 if (dt.Name == "CLSCompliantAttribute") {
1638                                         if (dt.Namespace != "System")
1639                                                 continue;
1640
1641                                         cls_compliant = (bool) a.ConstructorArguments[0].Value;
1642                                         continue;
1643                                 }
1644                         }
1645                 }
1646
1647                 //
1648                 // Reads assembly attributes which where attached to a special type because
1649                 // module does have assembly manifest
1650                 //
1651                 public List<Attribute> ReadAssemblyAttributes ()
1652                 {
1653                         var t = module.GetType (AssemblyAttributesPlaceholder.GetGeneratedName (Name));
1654                         if (t == null)
1655                                 return null;
1656
1657                         var field = t.GetField (AssemblyAttributesPlaceholder.AssemblyFieldName, BindingFlags.NonPublic | BindingFlags.Static);
1658                         if (field == null)
1659                                 return null;
1660
1661                         // TODO: implement, the idea is to fabricate specil Attribute class and
1662                         // add it to OptAttributes before resolving the source code attributes
1663                         // Need to build module location as well for correct error reporting
1664
1665                         //var assembly_attributes = CustomAttributeData.GetCustomAttributes (field);
1666                         //var attrs = new List<Attribute> (assembly_attributes.Count);
1667                         //foreach (var a in assembly_attributes)
1668                         //{
1669                         //    var type = metaImporter.ImportType (a.Constructor.DeclaringType);
1670                         //    var ctor = metaImporter.CreateMethod (a.Constructor, type);
1671
1672                         //    foreach (var carg in a.ConstructorArguments) {
1673                         //        carg.Value
1674                         //    }
1675
1676                         //    attrs.Add (new Attribute ("assembly", ctor, null, Location.Null, true));
1677                         //}
1678
1679                         return null;
1680                 }
1681         }
1682
1683         public class ImportedAssemblyDefinition : IAssemblyDefinition
1684         {
1685                 readonly Assembly assembly;
1686                 readonly AssemblyName aname;
1687                 bool cls_compliant;
1688
1689                 List<AssemblyName> internals_visible_to;
1690                 Dictionary<IAssemblyDefinition, AssemblyName> internals_visible_to_cache;
1691
1692                 public ImportedAssemblyDefinition (Assembly assembly)
1693                 {
1694                         this.assembly = assembly;
1695                         this.aname = assembly.GetName ();
1696                 }
1697
1698                 #region Properties
1699
1700                 public Assembly Assembly {
1701                         get {
1702                                 return assembly;
1703                         }
1704                 }
1705
1706                 public string FullName {
1707                         get {
1708                                 return aname.FullName;
1709                         }
1710                 }
1711
1712                 public bool HasStrongName {
1713                         get {
1714                                 return aname.GetPublicKey ().Length != 0;
1715                         }
1716                 }
1717
1718                 public bool IsMissing {
1719                         get {
1720 #if STATIC
1721                                 return assembly.__IsMissing;
1722 #else
1723                                 return false;
1724 #endif
1725                         }
1726                 }
1727
1728                 public bool IsCLSCompliant {
1729                         get {
1730                                 return cls_compliant;
1731                         }
1732                 }
1733
1734                 public string Location {
1735                         get {
1736                                 return assembly.Location;
1737                         }
1738                 }
1739
1740                 public string Name {
1741                         get {
1742                                 return aname.Name;
1743                         }
1744                 }
1745
1746                 #endregion
1747
1748                 public byte[] GetPublicKeyToken ()
1749                 {
1750                         return aname.GetPublicKeyToken ();
1751                 }
1752
1753                 public AssemblyName GetAssemblyVisibleToName (IAssemblyDefinition assembly)
1754                 {
1755                         return internals_visible_to_cache [assembly];
1756                 }
1757
1758                 public bool IsFriendAssemblyTo (IAssemblyDefinition assembly)
1759                 {
1760                         if (internals_visible_to == null)
1761                                 return false;
1762
1763                         AssemblyName is_visible = null;
1764                         if (internals_visible_to_cache == null) {
1765                                 internals_visible_to_cache = new Dictionary<IAssemblyDefinition, AssemblyName> ();
1766                         } else {
1767                                 if (internals_visible_to_cache.TryGetValue (assembly, out is_visible))
1768                                         return is_visible != null;
1769                         }
1770
1771                         var token = assembly.GetPublicKeyToken ();
1772                         if (token != null && token.Length == 0)
1773                                 token = null;
1774
1775                         foreach (var internals in internals_visible_to) {
1776                                 if (!String.Equals(internals.Name, assembly.Name, StringComparison.OrdinalIgnoreCase))
1777                                         continue;
1778
1779                                 if (token == null && assembly is AssemblyDefinition) {
1780                                         is_visible = internals;
1781                                         break;
1782                                 }
1783
1784                                 if (!ArrayComparer.IsEqual (token, internals.GetPublicKeyToken ()))
1785                                         continue;
1786
1787                                 is_visible = internals;
1788                                 break;
1789                         }
1790
1791                         internals_visible_to_cache.Add (assembly, is_visible);
1792                         return is_visible != null;
1793                 }
1794
1795                 public void ReadAttributes ()
1796                 {
1797 #if STATIC
1798                         if (assembly.__IsMissing)
1799                                 return;
1800 #endif
1801
1802                         IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (assembly);
1803
1804                         foreach (var a in attrs) {
1805                                 var dt = a.Constructor.DeclaringType;
1806                                 var name = dt.Name;
1807                                 if (name == "CLSCompliantAttribute") {
1808                                         if (dt.Namespace == "System") {
1809                                                 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1810                                         }
1811                                         continue;
1812                                 }
1813
1814                                 if (name == "InternalsVisibleToAttribute") {
1815                                         if (dt.Namespace != MetadataImporter.CompilerServicesNamespace)
1816                                                 continue;
1817
1818                                         string s = a.ConstructorArguments[0].Value as string;
1819                                         if (s == null)
1820                                                 continue;
1821
1822                                         AssemblyName an;
1823                                         try {
1824                                                 an = new AssemblyName (s);
1825                                         } catch (FileLoadException) {
1826                                                 // Invalid assembly name reuses FileLoadException
1827                                                 continue;
1828                                         }
1829
1830                                         if (internals_visible_to == null)
1831                                                 internals_visible_to = new List<AssemblyName> ();
1832
1833                                         internals_visible_to.Add (an);
1834                                         continue;
1835                                 }
1836                         }
1837                 }
1838
1839                 public override string ToString ()
1840                 {
1841                         return FullName;
1842                 }
1843         }
1844
1845         class ImportedMemberDefinition : ImportedDefinition
1846         {
1847                 readonly TypeSpec type;
1848
1849                 public ImportedMemberDefinition (MemberInfo member, TypeSpec type, MetadataImporter importer)
1850                         : base (member, importer)
1851                 {
1852                         this.type = type;
1853                 }
1854
1855                 #region Properties
1856
1857                 public TypeSpec MemberType {
1858                         get {
1859                                 return type;
1860                         }
1861                 }
1862
1863                 #endregion
1864         }
1865
1866         class ImportedParameterMemberDefinition : ImportedMemberDefinition, IParametersMember
1867         {
1868                 readonly AParametersCollection parameters;
1869
1870                 protected ImportedParameterMemberDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1871                         : base (provider, type, importer)
1872                 {
1873                         this.parameters = parameters;
1874                 }
1875
1876                 public ImportedParameterMemberDefinition (PropertyInfo provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1877                         : base (provider, type, importer)
1878                 {
1879                         this.parameters = parameters;
1880                 }
1881
1882                 #region Properties
1883
1884                 public AParametersCollection Parameters {
1885                         get {
1886                                 return parameters;
1887                         }
1888                 }
1889
1890                 #endregion
1891         }
1892
1893         class ImportedMethodDefinition : ImportedParameterMemberDefinition, IMethodDefinition
1894         {
1895                 public ImportedMethodDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1896                         : base (provider, type, parameters, importer)
1897                 {
1898                 }
1899
1900                 MethodBase IMethodDefinition.Metadata {
1901                         get {
1902                                 return (MethodBase) provider;
1903                         }
1904                 }
1905         }
1906
1907         class ImportedGenericMethodDefinition : ImportedMethodDefinition, IGenericMethodDefinition
1908         {
1909                 readonly TypeParameterSpec[] tparams;
1910
1911                 public ImportedGenericMethodDefinition (MethodInfo provider, TypeSpec type, AParametersCollection parameters, TypeParameterSpec[] tparams, MetadataImporter importer)
1912                         : base (provider, type, parameters, importer)
1913                 {
1914                         this.tparams = tparams;
1915                 }
1916
1917                 #region Properties
1918
1919                 public TypeParameterSpec[] TypeParameters {
1920                         get {
1921                                 return tparams;
1922                         }
1923                 }
1924
1925                 public int TypeParametersCount {
1926                         get {
1927                                 return tparams.Length;
1928                         }
1929                 }
1930
1931                 #endregion
1932         }
1933
1934         class ImportedTypeDefinition : ImportedDefinition, ITypeDefinition
1935         {
1936                 TypeParameterSpec[] tparams;
1937                 string name;
1938
1939                 public ImportedTypeDefinition (MetaType type, MetadataImporter importer)
1940                         : base (type, importer)
1941                 {
1942                 }
1943
1944                 #region Properties
1945
1946                 public IAssemblyDefinition DeclaringAssembly {
1947                         get {
1948                                 return importer.GetAssemblyDefinition (provider.Module.Assembly);
1949                         }
1950                 }
1951
1952                 bool ITypeDefinition.IsComImport {
1953                         get {
1954                                 return ((MetaType) provider).IsImport;
1955                         }
1956                 }
1957
1958
1959                 bool ITypeDefinition.IsPartial {
1960                         get {
1961                                 return false;
1962                         }
1963                 }
1964
1965                 bool ITypeDefinition.IsTypeForwarder {
1966                         get {
1967 #if STATIC
1968                                 return ((MetaType) provider).__IsTypeForwarder;
1969 #else
1970                                 return false;
1971 #endif
1972                         }
1973                 }
1974
1975                 bool ITypeDefinition.IsCyclicTypeForwarder {
1976                         get {
1977 #if STATIC
1978                                 return ((MetaType) provider).__IsCyclicTypeForwarder;
1979 #else
1980                                 return false;
1981 #endif
1982                         }
1983                 }
1984
1985                 public override string Name {
1986                         get {
1987                                 if (name == null) {
1988                                         name = base.Name;
1989                                         if (tparams != null) {
1990                                                 int arity_start = name.IndexOf ('`');
1991                                                 if (arity_start > 0)
1992                                                         name = name.Substring (0, arity_start);
1993                                         }
1994                                 }
1995
1996                                 return name;
1997                         }
1998                 }
1999
2000                 public string Namespace {
2001                         get {
2002                                 return ((MetaType) provider).Namespace;
2003                         }
2004                 }
2005
2006                 public int TypeParametersCount {
2007                         get {
2008                                 return tparams == null ? 0 : tparams.Length;
2009                         }
2010                 }
2011
2012                 public TypeParameterSpec[] TypeParameters {
2013                         get {
2014                                 return tparams;
2015                         }
2016                         set {
2017                                 tparams = value;
2018                         }
2019                 }
2020
2021                 #endregion
2022
2023                 public void DefineInterfaces (TypeSpec spec)
2024                 {
2025                         var type = (MetaType) provider;
2026                         MetaType[] ifaces;
2027 #if STATIC
2028                         ifaces = type.__GetDeclaredInterfaces ();
2029                         if (ifaces.Length != 0) {
2030                                 foreach (var iface in ifaces) {
2031                                         var it = importer.CreateType (iface);
2032                                         if (it == null)
2033                                                 continue;
2034
2035                                         spec.AddInterfaceDefined (it);
2036
2037                                         // Unfortunately not all languages expand inherited interfaces
2038                                         var bifaces = it.Interfaces;
2039                                         if (bifaces != null) {
2040                                                 foreach (var biface in bifaces) {
2041                                                         spec.AddInterfaceDefined (biface);
2042                                                 }
2043                                         }
2044                                 }
2045                         }
2046                         
2047                         //
2048                         // It's impossible to get declared interfaces only using System.Reflection
2049                         // hence we need to mimic the behavior with ikvm-reflection too to keep
2050                         // our type look-up logic same
2051                         //
2052                         if (spec.BaseType != null) {
2053                                 var bifaces = spec.BaseType.Interfaces;
2054                                 if (bifaces != null) {
2055                                         //
2056                                         // Before adding base class interfaces close defined interfaces
2057                                         // on type parameter
2058                                         //
2059                                         var tp = spec as TypeParameterSpec;
2060                                         if (tp != null && tp.InterfacesDefined == null) {
2061                                                 tp.InterfacesDefined = TypeSpec.EmptyTypes;
2062                                         }
2063
2064                                         foreach (var iface in bifaces)
2065                                                 spec.AddInterfaceDefined (iface);
2066                                 }
2067                         }
2068 #else
2069                         ifaces = type.GetInterfaces ();
2070
2071                         if (ifaces.Length > 0) {
2072                                 foreach (var iface in ifaces) {
2073                                         spec.AddInterface (importer.CreateType (iface));
2074                                 }
2075                         }
2076 #endif
2077
2078                 }
2079
2080                 public static void Error_MissingDependency (IMemberContext ctx, List<MissingTypeSpecReference> missing, Location loc)
2081                 {
2082                         // 
2083                         // Report details about missing type and most likely cause of the problem.
2084                         // csc used to reports 1683, 1684 (now 7069) as warnings but we report them only when used
2085                         // or referenced from the user core in which case compilation error has to
2086                         // be reported because compiler cannot continue anyway
2087                         //
2088
2089                         var report = ctx.Module.Compiler.Report;
2090
2091                         for (int i = 0; i < missing.Count; ++i) {
2092                                 var t = missing [i].Type;
2093
2094                                 //
2095                                 // Report missing types only once
2096                                 //
2097                                 if (report.Printer.MissingTypeReported (t.MemberDefinition))
2098                                         continue;
2099
2100                                 string name = t.GetSignatureForError ();
2101
2102                                 var caller = missing[i].Caller;
2103                                 if (caller.Kind != MemberKind.MissingType)
2104                                         report.SymbolRelatedToPreviousError (caller);
2105
2106                                 var definition = t.MemberDefinition;
2107                                 if (definition.DeclaringAssembly == ctx.Module.DeclaringAssembly) {
2108                                         report.Error (1683, loc,
2109                                                 "Reference to type `{0}' claims it is defined in this assembly, but it is not defined in source or any added modules",
2110                                                 name);
2111                                 } else if (definition.DeclaringAssembly.IsMissing) {
2112                                         if (definition.IsTypeForwarder) {
2113                                                 report.Error (1070, loc,
2114                                                         "The type `{0}' has been forwarded to an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
2115                                                         name, definition.DeclaringAssembly.FullName);
2116                                         } else {
2117                                                 report.Error (12, loc,
2118                                                         "The type `{0}' is defined in an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
2119                                                         name, definition.DeclaringAssembly.FullName);
2120                                         }
2121                                 } else if (definition.IsTypeForwarder) {
2122                                         report.Error (731, loc, "The type forwarder for type `{0}' in assembly `{1}' has circular dependency",
2123                                                 name, definition.DeclaringAssembly.FullName);
2124                                 } else {
2125                                         report.Error (7069, loc,
2126                                                 "Reference to type `{0}' claims it is defined assembly `{1}', but it could not be found",
2127                                                 name, t.MemberDefinition.DeclaringAssembly.FullName);
2128                                 }
2129                         }
2130                 }
2131
2132                 public TypeSpec GetAttributeCoClass ()
2133                 {
2134                         if (cattrs == null)
2135                                 ReadAttributes ();
2136
2137                         return cattrs.CoClass;
2138                 }
2139
2140                 public string GetAttributeDefaultMember ()
2141                 {
2142                         if (cattrs == null)
2143                                 ReadAttributes ();
2144
2145                         return cattrs.DefaultIndexerName;
2146                 }
2147
2148                 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
2149                 {
2150                         if (cattrs == null)
2151                                 ReadAttributes ();
2152
2153                         return cattrs.AttributeUsage;
2154                 }
2155
2156                 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2157                 {
2158                         var a = importer.GetAssemblyDefinition (provider.Module.Assembly);
2159                         return a == assembly || a.IsFriendAssemblyTo (assembly);
2160                 }
2161
2162                 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2163                 {
2164                         //
2165                         // Not interested in members of nested private types unless the importer needs them
2166                         //
2167                         if (declaringType.IsPrivate && importer.IgnorePrivateMembers) {
2168                                 cache = MemberCache.Empty;
2169                                 return;
2170                         }
2171
2172                         var loading_type = (MetaType) provider;
2173                         const BindingFlags all_members = BindingFlags.DeclaredOnly |
2174                                 BindingFlags.Static | BindingFlags.Instance |
2175                                 BindingFlags.Public | BindingFlags.NonPublic;
2176
2177                         const MethodAttributes explicit_impl = MethodAttributes.NewSlot |
2178                                         MethodAttributes.Virtual | MethodAttributes.HideBySig |
2179                                         MethodAttributes.Final;
2180
2181                         Dictionary<MethodBase, MethodSpec> possible_accessors = null;
2182                         List<EventSpec> imported_events = null;
2183                         EventSpec event_spec;
2184                         MemberSpec imported;
2185                         MethodInfo m;
2186                         MemberInfo[] all;
2187                         try {
2188                                 all = loading_type.GetMembers (all_members);
2189                         } catch (Exception e) {
2190                                 throw new InternalErrorException (e, "Could not import type `{0}' from `{1}'",
2191                                         declaringType.GetSignatureForError (), declaringType.MemberDefinition.DeclaringAssembly.FullName);
2192                         }
2193
2194                         if (cache == null) {
2195                                 cache = new MemberCache (all.Length);
2196
2197                                 //
2198                                 // Do the types first as they can be referenced by the members before
2199                                 // they are found or inflated
2200                                 //
2201                                 foreach (var member in all) {
2202                                         if (member.MemberType != MemberTypes.NestedType)
2203                                                 continue;
2204
2205                                         var t = (MetaType) member;
2206
2207                                         // Ignore compiler generated types, mostly lambda containers
2208                                         if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
2209                                                 continue;
2210
2211                                         try {
2212                                                 imported = importer.CreateNestedType (t, declaringType);
2213                                         } catch (Exception e) {
2214                                                 throw new InternalErrorException (e, "Could not import nested type `{0}' from `{1}'",
2215                                                         t.FullName, declaringType.MemberDefinition.DeclaringAssembly.FullName);
2216                                         }
2217
2218                                         cache.AddMemberImported (imported);
2219                                 }
2220
2221                                 foreach (var member in all) {
2222                                         if (member.MemberType != MemberTypes.NestedType)
2223                                                 continue;
2224
2225                                         var t = (MetaType) member;
2226
2227                                         if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
2228                                                 continue;
2229
2230                                         importer.ImportTypeBase (t);
2231                                 }
2232                         }
2233
2234                         //
2235                         // Load base interfaces first to minic behaviour of compiled members
2236                         //
2237                         if (declaringType.IsInterface && declaringType.Interfaces != null) {
2238                                 foreach (var iface in declaringType.Interfaces) {
2239                                         cache.AddInterface (iface);
2240                                 }
2241                         }
2242
2243                         if (!onlyTypes) {
2244                                 //
2245                                 // The logic here requires methods to be returned first which seems to work for both Mono and .NET
2246                                 //
2247                                 foreach (var member in all) {
2248                                         switch (member.MemberType) {
2249                                         case MemberTypes.Constructor:
2250                                                 if (declaringType.IsInterface)
2251                                                         continue;
2252
2253                                                 goto case MemberTypes.Method;
2254                                         case MemberTypes.Method:
2255                                                 MethodBase mb = (MethodBase) member;
2256                                                 var attrs = mb.Attributes;
2257
2258                                                 if ((attrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) {
2259                                                         if (importer.IgnorePrivateMembers)
2260                                                                 continue;
2261
2262                                                         // Ignore explicitly implemented members
2263                                                         if ((attrs & explicit_impl) == explicit_impl)
2264                                                                 continue;
2265
2266                                                         // Ignore compiler generated methods
2267                                                         if (MetadataImporter.HasAttribute (CustomAttributeData.GetCustomAttributes (mb), "CompilerGeneratedAttribute", MetadataImporter.CompilerServicesNamespace))
2268                                                                 continue;
2269                                                 }
2270
2271                                                 imported = importer.CreateMethod (mb, declaringType);
2272                                                 if (imported.Kind == MemberKind.Method && !imported.IsGeneric) {
2273                                                         if (possible_accessors == null)
2274                                                                 possible_accessors = new Dictionary<MethodBase, MethodSpec> (ReferenceEquality<MethodBase>.Default);
2275
2276                                                         // There are no metadata rules for accessors, we have to consider any method as possible candidate
2277                                                         possible_accessors.Add (mb, (MethodSpec) imported);
2278                                                 }
2279
2280                                                 break;
2281                                         case MemberTypes.Property:
2282                                                 if (possible_accessors == null)
2283                                                         continue;
2284
2285                                                 var p = (PropertyInfo) member;
2286                                                 //
2287                                                 // Links possible accessors with property
2288                                                 //
2289                                                 MethodSpec get, set;
2290                                                 m = p.GetGetMethod (true);
2291                                                 if (m == null || !possible_accessors.TryGetValue (m, out get))
2292                                                         get = null;
2293
2294                                                 m = p.GetSetMethod (true);
2295                                                 if (m == null || !possible_accessors.TryGetValue (m, out set))
2296                                                         set = null;
2297
2298                                                 // No accessors registered (e.g. explicit implementation)
2299                                                 if (get == null && set == null)
2300                                                         continue;
2301
2302                                                 try {
2303                                                         imported = importer.CreateProperty (p, declaringType, get, set);
2304                                                 } catch (Exception ex) {
2305                                                         throw new InternalErrorException (ex, "Could not import property `{0}' inside `{1}'",
2306                                                                 p.Name, declaringType.GetSignatureForError ());
2307                                                 }
2308
2309                                                 if (imported == null)
2310                                                         continue;
2311
2312                                                 break;
2313                                         case MemberTypes.Event:
2314                                                 if (possible_accessors == null)
2315                                                         continue;
2316
2317                                                 var e = (EventInfo) member;
2318                                                 //
2319                                                 // Links accessors with event
2320                                                 //
2321                                                 MethodSpec add, remove;
2322                                                 m = e.GetAddMethod (true);
2323                                                 if (m == null || !possible_accessors.TryGetValue (m, out add))
2324                                                         add = null;
2325
2326                                                 m = e.GetRemoveMethod (true);
2327                                                 if (m == null || !possible_accessors.TryGetValue (m, out remove))
2328                                                         remove = null;
2329
2330                                                 // Both accessors are required
2331                                                 if (add == null || remove == null)
2332                                                         continue;
2333
2334                                                 event_spec = importer.CreateEvent (e, declaringType, add, remove);
2335                                                 if (!importer.IgnorePrivateMembers) {
2336                                                         if (imported_events == null)
2337                                                                 imported_events = new List<EventSpec> ();
2338
2339                                                         imported_events.Add (event_spec);
2340                                                 }
2341
2342                                                 imported = event_spec;
2343                                                 break;
2344                                         case MemberTypes.Field:
2345                                                 var fi = (FieldInfo) member;
2346
2347                                                 imported = importer.CreateField (fi, declaringType);
2348                                                 if (imported == null)
2349                                                         continue;
2350
2351                                                 //
2352                                                 // For dynamic binder event has to be fully restored to allow operations
2353                                                 // within the type container to work correctly
2354                                                 //
2355                                                 if (imported_events != null) {
2356                                                         // The backing event field should be private but it may not
2357                                                         int i;
2358                                                         for (i = 0; i < imported_events.Count; ++i) {
2359                                                                 var ev = imported_events[i];
2360                                                                 if (ev.Name == fi.Name) {
2361                                                                         ev.BackingField = (FieldSpec) imported;
2362                                                                         imported_events.RemoveAt (i);
2363                                                                         i = -1;
2364                                                                         break;
2365                                                                 }
2366                                                         }
2367
2368                                                         if (i < 0)
2369                                                                 continue;
2370                                                 }
2371
2372                                                 break;
2373                                         case MemberTypes.NestedType:
2374                                                 // Already in the cache from the first pass
2375                                                 continue;
2376                                         default:
2377                                                 throw new NotImplementedException (member.ToString ());
2378                                         }
2379
2380                                         if (imported.IsStatic && declaringType.IsInterface)
2381                                                 continue;
2382
2383                                         cache.AddMemberImported (imported);
2384                                 }
2385                         }
2386                 }
2387         }
2388
2389         class ImportedTypeParameterDefinition : ImportedDefinition, ITypeDefinition
2390         {
2391                 public ImportedTypeParameterDefinition (MetaType type, MetadataImporter importer)
2392                         : base (type, importer)
2393                 {
2394                 }
2395
2396                 #region Properties
2397
2398                 public IAssemblyDefinition DeclaringAssembly {
2399                         get {
2400                                 throw new NotImplementedException ();
2401                         }
2402                 }
2403
2404                 bool ITypeDefinition.IsComImport {
2405                         get {
2406                                 return false;
2407                         }
2408                 }
2409
2410                 bool ITypeDefinition.IsPartial {
2411                         get {
2412                                 return false;
2413                         }
2414                 }
2415
2416                 bool ITypeDefinition.IsTypeForwarder {
2417                         get {
2418                                 return false;
2419                         }
2420                 }
2421
2422                 bool ITypeDefinition.IsCyclicTypeForwarder {
2423                         get {
2424                                 return false;
2425                         }
2426                 }
2427
2428                 public string Namespace {
2429                         get {
2430                                 return null;
2431                         }
2432                 }
2433
2434                 public int TypeParametersCount {
2435                         get {
2436                                 return 0;
2437                         }
2438                 }
2439
2440                 public TypeParameterSpec[] TypeParameters {
2441                         get {
2442                                 return null;
2443                         }
2444                 }
2445
2446                 #endregion
2447
2448                 public TypeSpec GetAttributeCoClass ()
2449                 {
2450                         return null;
2451                 }
2452
2453                 public string GetAttributeDefaultMember ()
2454                 {
2455                         throw new NotSupportedException ();
2456                 }
2457
2458                 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
2459                 {
2460                         throw new NotSupportedException ();
2461                 }
2462
2463                 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2464                 {
2465                         throw new NotImplementedException ();
2466                 }
2467
2468                 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2469                 {
2470                         throw new NotImplementedException ();
2471                 }
2472         }
2473 }