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