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