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