Report better error for recursive type reference
[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 (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 (type.IsGenericType && !type.IsGenericTypeDefinition) {
656                                 var type_def = type.GetGenericTypeDefinition ();
657                                 var targs = CreateGenericArguments (0, type.GetGenericArguments (), dtype);
658                                 if (declaringType == null) {
659                                         // Simple case, no nesting
660                                         spec = CreateType (type_def, null, new DynamicTypeReader (), canImportBaseType);
661                                         spec = spec.MakeGenericType (targs);
662                                 } else {
663                                         //
664                                         // Nested type case, converting .NET types like
665                                         // A`1.B`1.C`1<int, long, string> to typespec like
666                                         // A<int>.B<long>.C<string>
667                                         //
668                                         var nested_hierarchy = new List<TypeSpec> ();
669                                         while (declaringType.IsNested) {
670                                                 nested_hierarchy.Add (declaringType);
671                                                 declaringType = declaringType.DeclaringType;
672                                         }
673
674                                         int targs_pos = 0;
675                                         if (declaringType.Arity > 0) {
676                                                 spec = declaringType.MakeGenericType (targs.Skip (targs_pos).Take (declaringType.Arity).ToArray ());
677                                                 targs_pos = spec.Arity;
678                                         } else {
679                                                 spec = declaringType;
680                                         }
681
682                                         for (int i = nested_hierarchy.Count; i != 0; --i) {
683                                                 var t = nested_hierarchy [i - 1];
684                                                 spec = MemberCache.FindNestedType (spec, t.Name, t.Arity);
685                                                 if (t.Arity > 0) {
686                                                         spec = spec.MakeGenericType (targs.Skip (targs_pos).Take (spec.Arity).ToArray ());
687                                                         targs_pos += t.Arity;
688                                                 }
689                                         }
690
691                                         string name = type.Name;
692                                         int index = name.IndexOf ('`');
693                                         if (index > 0)
694                                                 name = name.Substring (0, index);
695
696                                         spec = MemberCache.FindNestedType (spec, name, targs.Length - targs_pos);
697                                         if (spec.Arity > 0) {
698                                                 spec = spec.MakeGenericType (targs.Skip (targs_pos).ToArray ());
699                                         }
700                                 }
701
702                                 // Don't add generic type with dynamic arguments, they can interfere with same type
703                                 // using object type arguments
704                                 if (!spec.HasDynamicElement) {
705
706                                         // Add to reading cache to speed up reading
707                                         if (!import_cache.ContainsKey (type))
708                                                 import_cache.Add (type, spec);
709                                 }
710
711                                 return spec;
712                         }
713
714                         Modifiers mod;
715                         MemberKind kind;
716
717                         var ma = type.Attributes;
718                         switch (ma & TypeAttributes.VisibilityMask) {
719                         case TypeAttributes.Public:
720                         case TypeAttributes.NestedPublic:
721                                 mod = Modifiers.PUBLIC;
722                                 break;
723                         case TypeAttributes.NestedPrivate:
724                                 mod = Modifiers.PRIVATE;
725                                 break;
726                         case TypeAttributes.NestedFamily:
727                                 mod = Modifiers.PROTECTED;
728                                 break;
729                         case TypeAttributes.NestedFamORAssem:
730                                 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
731                                 break;
732                         default:
733                                 mod = Modifiers.INTERNAL;
734                                 break;
735                         }
736
737                         if ((ma & TypeAttributes.Interface) != 0) {
738                                 kind = MemberKind.Interface;
739                         } else if (type.IsGenericParameter) {
740                                 kind = MemberKind.TypeParameter;
741                         } else {
742                                 var base_type = type.BaseType;
743                                 if (base_type == null || (ma & TypeAttributes.Abstract) != 0) {
744                                         kind = MemberKind.Class;
745                                 } else {
746                                         kind = DetermineKindFromBaseType (base_type);
747                                         if (kind == MemberKind.Struct || kind == MemberKind.Delegate) {
748                                                 mod |= Modifiers.SEALED;
749                                         }
750                                 }
751
752                                 if (kind == MemberKind.Class) {
753                                         if ((ma & TypeAttributes.Sealed) != 0) {
754                                                 mod |= Modifiers.SEALED;
755                                                 if ((ma & TypeAttributes.Abstract) != 0)
756                                                         mod |= Modifiers.STATIC;
757                                         } else if ((ma & TypeAttributes.Abstract) != 0) {
758                                                 mod |= Modifiers.ABSTRACT;
759                                         }
760                                 }
761                         }
762
763                         var definition = new ImportedTypeDefinition (type, this);
764                         BuildinTypeSpec pt;
765
766                         if (kind == MemberKind.Enum) {
767                                 const BindingFlags underlying_member = BindingFlags.DeclaredOnly |
768                                         BindingFlags.Instance |
769                                         BindingFlags.Public | BindingFlags.NonPublic;
770
771                                 var type_members = type.GetFields (underlying_member);
772                                 foreach (var type_member in type_members) {
773                                         spec = new EnumSpec (declaringType, definition, CreateType (type_member.FieldType), type, mod);
774                                         break;
775                                 }
776
777                                 if (spec == null)
778                                         kind = MemberKind.Class;
779
780                         } else if (kind == MemberKind.TypeParameter) {
781                                 // Return as type_cache was updated
782                                 return CreateTypeParameter (type, declaringType);
783                         } else if (type.IsGenericTypeDefinition) {
784                                 definition.TypeParameters = CreateGenericParameters (type, declaringType);
785
786                                 // Constraints are not loaded on demand and can reference this type
787                                 if (import_cache.TryGetValue (type, out spec))
788                                         return spec;
789
790                         } else if (buildin_types.TryGetValue (type, out pt)) {
791                                 spec = pt;
792                                 pt.SetDefinition (definition, type, mod);
793                         }
794
795                         if (spec == null)
796                                 spec = new TypeSpec (kind, declaringType, definition, type, mod);
797
798                         import_cache.Add (type, spec);
799
800                         //
801                         // Two stage setup as the base type can be inflated declaring type or
802                         // another nested type inside same declaring type which has not been
803                         // loaded, therefore we can import a base type of nested types once
804                         // the types have been imported
805                         //
806                         if (canImportBaseType)
807                                 ImportTypeBase (spec, type);
808
809                         return spec;
810                 }
811
812                 public ImportedAssemblyDefinition GetAssemblyDefinition (Assembly assembly)
813                 {
814                         ImportedAssemblyDefinition def;
815                         if (!assembly_2_definition.TryGetValue (assembly, out def)) {
816
817                                 // This can happen in dynamic context only
818                                 def = new ImportedAssemblyDefinition (assembly, this);
819                                 assembly_2_definition.Add (assembly, def);
820                                 def.ReadAttributes ();
821                         }
822
823                         return def;
824                 }
825
826                 public void ImportTypeBase (MetaType type)
827                 {
828                         TypeSpec spec = import_cache[type];
829                         if (spec != null)
830                                 ImportTypeBase (spec, type);
831                 }
832
833                 void ImportTypeBase (TypeSpec spec, MetaType type)
834                 {
835                         if (spec.Kind == MemberKind.Interface)
836                                 spec.BaseType = TypeManager.object_type;
837                         else if (type.BaseType != null) {
838                                 TypeSpec base_type;
839                                 if (type.BaseType.IsGenericType)
840                                         base_type = CreateType (type.BaseType, new DynamicTypeReader (type), true);
841                                 else
842                                         base_type = CreateType (type.BaseType);
843
844                                 spec.BaseType = base_type;
845                         }
846
847                         var ifaces = type.GetInterfaces ();
848                         if (ifaces.Length > 0) {
849                                 foreach (var iface in ifaces) {
850                                         spec.AddInterface (CreateType (iface));
851                                 }
852                         }
853                 }
854
855                 TypeParameterSpec CreateTypeParameter (MetaType type, TypeSpec declaringType)
856                 {
857                         Variance variance;
858                         switch (type.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) {
859                         case GenericParameterAttributes.Covariant:
860                                 variance = Variance.Covariant;
861                                 break;
862                         case GenericParameterAttributes.Contravariant:
863                                 variance = Variance.Contravariant;
864                                 break;
865                         default:
866                                 variance = Variance.None;
867                                 break;
868                         }
869
870                         SpecialConstraint special = SpecialConstraint.None;
871                         var import_special = type.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask;
872
873                         if ((import_special & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) {
874                                 special |= SpecialConstraint.Struct;
875                         } else if ((import_special & GenericParameterAttributes.DefaultConstructorConstraint) != 0) {
876                                 special = SpecialConstraint.Constructor;
877                         }
878
879                         if ((import_special & GenericParameterAttributes.ReferenceTypeConstraint) != 0) {
880                                 special |= SpecialConstraint.Class;
881                         }
882
883                         TypeParameterSpec spec;
884                         var def = new ImportedTypeParameterDefinition (type, this);
885                         if (type.DeclaringMethod != null)
886                                 spec = new TypeParameterSpec (type.GenericParameterPosition, def, special, variance, type);
887                         else
888                                 spec = new TypeParameterSpec (declaringType, type.GenericParameterPosition, def, special, variance, type);
889
890                         // Add it now, so any constraint can reference it and get same instance
891                         import_cache.Add (type, spec);
892
893                         var constraints = type.GetGenericParameterConstraints ();
894                         List<TypeSpec> tparams = null;
895                         foreach (var ct in constraints) {
896                                 if (ct.IsGenericParameter) {
897                                         if (tparams == null)
898                                                 tparams = new List<TypeSpec> ();
899
900                                         tparams.Add (CreateType (ct));
901                                         continue;
902                                 }
903
904                                 if (ct.IsClass) {
905                                         spec.BaseType = CreateType (ct);
906                                         continue;
907                                 }
908
909                                 spec.AddInterface (CreateType (ct));
910                         }
911
912                         if (spec.BaseType == null)
913                                 spec.BaseType = TypeManager.object_type;
914
915                         if (tparams != null)
916                                 spec.TypeArguments = tparams.ToArray ();
917
918                         return spec;
919                 }
920
921                 //
922                 // Test for a custom attribute type match. Custom attributes are not really predefined globaly 
923                 // they can be assembly specific therefore we do check based on names only
924                 //
925                 public bool HasAttribute (IList<CustomAttributeData> attributesData, string attrName, string attrNamespace)
926                 {
927                         if (attributesData.Count == 0)
928                                 return false;
929
930                         string ns, name;
931                         foreach (var attr in attributesData) {
932                                 GetCustomAttributeTypeName (attr, out ns, out name);
933                                 if (name == attrName && ns == attrNamespace)
934                                         return true;
935                         }
936
937                         return false;
938                 }
939
940                 protected void ImportTypes (MetaType[] types, Namespace targetNamespace, bool hasExtensionTypes)
941                 {
942                         Namespace ns = targetNamespace;
943                         string prev_namespace = null;
944                         foreach (var t in types) {
945                                 if (t == null)
946                                         continue;
947
948                                 // Be careful not to trigger full parent type loading
949                                 if (t.MemberType == MemberTypes.NestedType)
950                                         continue;
951
952                                 if (t.Name[0] == '<')
953                                         continue;
954
955                                 var it = CreateType (t, null, new DynamicTypeReader (t), true);
956                                 if (it == null)
957                                         continue;
958
959                                 if (prev_namespace != t.Namespace) {
960                                         ns = t.Namespace == null ? targetNamespace : targetNamespace.GetNamespace (t.Namespace, true);
961                                         prev_namespace = t.Namespace;
962                                 }
963
964                                 ns.AddType (it);
965
966                                 if (it.IsStatic && hasExtensionTypes &&
967                                         HasAttribute (CustomAttributeData.GetCustomAttributes (t), "ExtensionAttribute", CompilerServicesNamespace)) {
968                                         it.SetExtensionMethodContainer ();
969                                 }
970                         }
971                 }
972
973                 static Constant ImportParameterConstant (object value)
974                 {
975                         //
976                         // Get type of underlying value as int constant can be used for object
977                         // parameter type. This is not allowed in C# but other languages can do that
978                         //
979                         switch (System.Type.GetTypeCode (value.GetType ())) {
980                         case TypeCode.Boolean:
981                                 return new BoolConstant ((bool) value, Location.Null);
982                         case TypeCode.Byte:
983                                 return new ByteConstant ((byte) value, Location.Null);
984                         case TypeCode.Char:
985                                 return new CharConstant ((char) value, Location.Null);
986                         case TypeCode.Decimal:
987                                 return new DecimalConstant ((decimal) value, Location.Null);
988                         case TypeCode.Double:
989                                 return new DoubleConstant ((double) value, Location.Null);
990                         case TypeCode.Int16:
991                                 return new ShortConstant ((short) value, Location.Null);
992                         case TypeCode.Int32:
993                                 return new IntConstant ((int) value, Location.Null);
994                         case TypeCode.Int64:
995                                 return new LongConstant ((long) value, Location.Null);
996                         case TypeCode.SByte:
997                                 return new SByteConstant ((sbyte) value, Location.Null);
998                         case TypeCode.Single:
999                                 return new FloatConstant ((float) value, Location.Null);
1000                         case TypeCode.String:
1001                                 return new StringConstant ((string) value, Location.Null);
1002                         case TypeCode.UInt16:
1003                                 return new UShortConstant ((ushort) value, Location.Null);
1004                         case TypeCode.UInt32:
1005                                 return new UIntConstant ((uint) value, Location.Null);
1006                         case TypeCode.UInt64:
1007                                 return new ULongConstant ((ulong) value, Location.Null);
1008                         }
1009
1010                         throw new NotImplementedException (value.GetType ().ToString ());
1011                 }
1012
1013                 public TypeSpec ImportType (MetaType type)
1014                 {
1015                         return ImportType (type, new DynamicTypeReader (type));
1016                 }
1017
1018                 TypeSpec ImportType (MetaType type, DynamicTypeReader dtype)
1019                 {
1020                         if (type.HasElementType) {
1021                                 var element = type.GetElementType ();
1022                                 ++dtype.Position;
1023                                 var spec = ImportType (element, dtype);
1024
1025                                 if (type.IsArray)
1026                                         return ArrayContainer.MakeType (spec, type.GetArrayRank ());
1027                                 if (type.IsByRef)
1028                                         return ReferenceContainer.MakeType (spec);
1029                                 if (type.IsPointer)
1030                                         return PointerContainer.MakeType (spec);
1031
1032                                 throw new NotImplementedException ("Unknown element type " + type.ToString ());
1033                         }
1034
1035                         return CreateType (type, dtype, true);
1036                 }
1037
1038                 //
1039                 // Decimal constants cannot be encoded in the constant blob, and thus are marked
1040                 // as IsInitOnly ('readonly' in C# parlance).  We get its value from the 
1041                 // DecimalConstantAttribute metadata.
1042                 //
1043                 Constant ReadDecimalConstant (IList<CustomAttributeData> attrs)
1044                 {
1045                         if (attrs.Count == 0)
1046                                 return null;
1047
1048                         string name, ns;
1049                         foreach (var ca in attrs) {
1050                                 GetCustomAttributeTypeName (ca, out ns, out name);
1051                                 if (name != "DecimalConstantAttribute" || ns != CompilerServicesNamespace)
1052                                         continue;
1053
1054                                 var value = new decimal (
1055                                         (int) (uint) ca.ConstructorArguments[4].Value,
1056                                         (int) (uint) ca.ConstructorArguments[3].Value,
1057                                         (int) (uint) ca.ConstructorArguments[2].Value,
1058                                         (byte) ca.ConstructorArguments[1].Value != 0,
1059                                         (byte) ca.ConstructorArguments[0].Value);
1060
1061                                 return new DecimalConstant (value, Location.Null).Resolve (null);
1062                         }
1063
1064                         return null;
1065                 }
1066
1067                 static Modifiers ReadMethodModifiers (MethodBase mb, TypeSpec declaringType)
1068                 {
1069                         Modifiers mod;
1070                         var ma = mb.Attributes;
1071                         switch (ma & MethodAttributes.MemberAccessMask) {
1072                         case MethodAttributes.Public:
1073                                 mod = Modifiers.PUBLIC;
1074                                 break;
1075                         case MethodAttributes.Assembly:
1076                                 mod = Modifiers.INTERNAL;
1077                                 break;
1078                         case MethodAttributes.Family:
1079                                 mod = Modifiers.PROTECTED;
1080                                 break;
1081                         case MethodAttributes.FamORAssem:
1082                                 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
1083                                 break;
1084                         default:
1085                                 mod = Modifiers.PRIVATE;
1086                                 break;
1087                         }
1088
1089                         if ((ma & MethodAttributes.Static) != 0) {
1090                                 mod |= Modifiers.STATIC;
1091                                 return mod;
1092                         }
1093                         if ((ma & MethodAttributes.Abstract) != 0 && declaringType.IsClass) {
1094                                 mod |= Modifiers.ABSTRACT;
1095                                 return mod;
1096                         }
1097
1098                         if ((ma & MethodAttributes.Final) != 0)
1099                                 mod |= Modifiers.SEALED;
1100
1101                         // It can be sealed and override
1102                         if ((ma & MethodAttributes.Virtual) != 0) {
1103                                 if ((ma & MethodAttributes.NewSlot) != 0 || !declaringType.IsClass) {
1104                                         // No private virtual or sealed virtual
1105                                         if ((mod & (Modifiers.PRIVATE | Modifiers.SEALED)) == 0)
1106                                                 mod |= Modifiers.VIRTUAL;
1107                                 } else {
1108                                         mod |= Modifiers.OVERRIDE;
1109                                 }
1110                         }
1111
1112                         return mod;
1113                 }
1114         }
1115
1116         abstract class ImportedDefinition : IMemberDefinition
1117         {
1118                 protected class AttributesBag
1119                 {
1120                         public static readonly AttributesBag Default = new AttributesBag ();
1121
1122                         public AttributeUsageAttribute AttributeUsage;
1123                         public ObsoleteAttribute Obsolete;
1124                         public string[] Conditionals;
1125                         public string DefaultIndexerName;
1126                         public bool IsNotCLSCompliant;
1127                         public TypeSpec CoClass;
1128                         
1129                         public static AttributesBag Read (MemberInfo mi, MetadataImporter importer)
1130                         {
1131                                 AttributesBag bag = null;
1132                                 List<string> conditionals = null;
1133
1134                                 // It should not throw any loading exception
1135                                 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (mi);
1136
1137                                 string ns, name;
1138                                 foreach (var a in attrs) {
1139                                         importer.GetCustomAttributeTypeName (a, out ns, out name);
1140                                         if (name == "ObsoleteAttribute") {
1141                                                 if (ns != "System")
1142                                                         continue;
1143
1144                                                 if (bag == null)
1145                                                         bag = new AttributesBag ();
1146
1147                                                 var args = a.ConstructorArguments;
1148
1149                                                 if (args.Count == 1) {
1150                                                         bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value);
1151                                                 } else if (args.Count == 2) {
1152                                                         bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value, (bool) args[1].Value);
1153                                                 } else {
1154                                                         bag.Obsolete = new ObsoleteAttribute ();
1155                                                 }
1156
1157                                                 continue;
1158                                         }
1159
1160                                         if (name == "ConditionalAttribute") {
1161                                                 if (ns != "System.Diagnostics")
1162                                                         continue;
1163
1164                                                 if (bag == null)
1165                                                         bag = new AttributesBag ();
1166
1167                                                 if (conditionals == null)
1168                                                         conditionals = new List<string> (2);
1169
1170                                                 conditionals.Add ((string) a.ConstructorArguments[0].Value);
1171                                                 continue;
1172                                         }
1173
1174                                         if (name == "CLSCompliantAttribute") {
1175                                                 if (ns != "System")
1176                                                         continue;
1177
1178                                                 if (bag == null)
1179                                                         bag = new AttributesBag ();
1180
1181                                                 bag.IsNotCLSCompliant = !(bool) a.ConstructorArguments[0].Value;
1182                                                 continue;
1183                                         }
1184
1185                                         // Type only attributes
1186                                         if (mi.MemberType == MemberTypes.TypeInfo || mi.MemberType == MemberTypes.NestedType) {
1187                                                 if (name == "DefaultMemberAttribute") {
1188                                                         if (ns != "System.Reflection")
1189                                                                 continue;
1190
1191                                                         if (bag == null)
1192                                                                 bag = new AttributesBag ();
1193
1194                                                         bag.DefaultIndexerName = (string) a.ConstructorArguments[0].Value;
1195                                                         continue;
1196                                                 }
1197
1198                                                 if (name == "AttributeUsageAttribute") {
1199                                                         if (ns != "System")
1200                                                                 continue;
1201
1202                                                         if (bag == null)
1203                                                                 bag = new AttributesBag ();
1204
1205                                                         bag.AttributeUsage = new AttributeUsageAttribute ((AttributeTargets) a.ConstructorArguments[0].Value);
1206                                                         foreach (var named in a.NamedArguments) {
1207                                                                 if (named.MemberInfo.Name == "AllowMultiple")
1208                                                                         bag.AttributeUsage.AllowMultiple = (bool) named.TypedValue.Value;
1209                                                                 else if (named.MemberInfo.Name == "Inherited")
1210                                                                         bag.AttributeUsage.Inherited = (bool) named.TypedValue.Value;
1211                                                         }
1212                                                         continue;
1213                                                 }
1214
1215                                                 // Interface only attribute
1216                                                 if (name == "CoClassAttribute") {
1217                                                         if (ns != "System.Runtime.InteropServices")
1218                                                                 continue;
1219
1220                                                         if (bag == null)
1221                                                                 bag = new AttributesBag ();
1222
1223                                                         bag.CoClass = importer.ImportType ((MetaType) a.ConstructorArguments[0].Value);
1224                                                         continue;
1225                                                 }
1226                                         }
1227                                 }
1228
1229                                 if (bag == null)
1230                                         return Default;
1231
1232                                 if (conditionals != null)
1233                                         bag.Conditionals = conditionals.ToArray ();
1234                                 
1235                                 return bag;
1236                         }
1237                 }
1238
1239                 protected readonly MemberInfo provider;
1240                 protected AttributesBag cattrs;
1241                 protected readonly MetadataImporter importer;
1242
1243                 public ImportedDefinition (MemberInfo provider, MetadataImporter importer)
1244                 {
1245                         this.provider = provider;
1246                         this.importer = importer;
1247                 }
1248
1249                 #region Properties
1250
1251                 public bool IsImported {
1252                         get {
1253                                 return true;
1254                         }
1255                 }
1256
1257                 public virtual string Name {
1258                         get {
1259                                 return provider.Name;
1260                         }
1261                 }
1262
1263                 #endregion
1264
1265                 public abstract List<MissingType> ResolveMissingDependencies ();
1266
1267                 public string[] ConditionalConditions ()
1268                 {
1269                         if (cattrs == null)
1270                                 ReadAttributes ();
1271
1272                         return cattrs.Conditionals;
1273                 }
1274
1275                 public ObsoleteAttribute GetAttributeObsolete ()
1276                 {
1277                         if (cattrs == null)
1278                                 ReadAttributes ();
1279
1280                         return cattrs.Obsolete;
1281                 }
1282
1283                 public bool IsNotCLSCompliant ()
1284                 {
1285                         if (cattrs == null)
1286                                 ReadAttributes ();
1287
1288                         return cattrs.IsNotCLSCompliant;
1289                 }
1290
1291                 protected void ReadAttributes ()
1292                 {
1293                         cattrs = AttributesBag.Read (provider, importer);
1294                 }
1295
1296                 public void SetIsAssigned ()
1297                 {
1298                         // Unused for imported members
1299                 }
1300
1301                 public void SetIsUsed ()
1302                 {
1303                         // Unused for imported members
1304                 }
1305         }
1306
1307         public class ImportedModuleDefinition
1308         {
1309                 readonly Module module;
1310                 bool cls_compliant;
1311                 readonly MetadataImporter importer;
1312                 
1313                 public ImportedModuleDefinition (Module module, MetadataImporter importer)
1314                 {
1315                         this.module = module;
1316                         this.importer = importer;
1317                 }
1318
1319                 #region Properties
1320
1321                 public bool IsCLSCompliant {
1322                         get {
1323                                 return cls_compliant;
1324                         }
1325                 }
1326
1327                 public string Name {
1328                         get {
1329                                 return module.Name;
1330                         }
1331                 }
1332
1333                 #endregion
1334
1335                 public void ReadAttributes ()
1336                 {
1337                         IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (module);
1338
1339                         string ns, name;
1340                         foreach (var a in attrs) {
1341                                 importer.GetCustomAttributeTypeName (a, out ns, out name);
1342                                 if (name == "CLSCompliantAttribute") {
1343                                         if (ns != "System")
1344                                                 continue;
1345
1346                                         cls_compliant = (bool) a.ConstructorArguments[0].Value;
1347                                         continue;
1348                                 }
1349                         }
1350                 }
1351
1352                 //
1353                 // Reads assembly attributes which where attached to a special type because
1354                 // module does have assembly manifest
1355                 //
1356                 public List<Attribute> ReadAssemblyAttributes ()
1357                 {
1358                         var t = module.GetType (AssemblyAttributesPlaceholder.GetGeneratedName (Name));
1359                         if (t == null)
1360                                 return null;
1361
1362                         var field = t.GetField (AssemblyAttributesPlaceholder.AssemblyFieldName, BindingFlags.NonPublic | BindingFlags.Static);
1363                         if (field == null)
1364                                 return null;
1365
1366                         // TODO: implement, the idea is to fabricate specil Attribute class and
1367                         // add it to OptAttributes before resolving the source code attributes
1368                         // Need to build module location as well for correct error reporting
1369
1370                         //var assembly_attributes = CustomAttributeData.GetCustomAttributes (field);
1371                         //var attrs = new List<Attribute> (assembly_attributes.Count);
1372                         //foreach (var a in assembly_attributes)
1373                         //{
1374                         //    var type = metaImporter.ImportType (a.Constructor.DeclaringType);
1375                         //    var ctor = metaImporter.CreateMethod (a.Constructor, type);
1376
1377                         //    foreach (var carg in a.ConstructorArguments) {
1378                         //        carg.Value
1379                         //    }
1380
1381                         //    attrs.Add (new Attribute ("assembly", ctor, null, Location.Null, true));
1382                         //}
1383
1384                         return null;
1385                 }
1386         }
1387
1388         public class ImportedAssemblyDefinition : IAssemblyDefinition
1389         {
1390                 readonly Assembly assembly;
1391                 readonly AssemblyName aname;
1392                 readonly MetadataImporter importer;
1393                 bool cls_compliant;
1394                 bool contains_extension_methods;
1395
1396                 List<AssemblyName> internals_visible_to;
1397                 Dictionary<IAssemblyDefinition, AssemblyName> internals_visible_to_cache;
1398
1399                 public ImportedAssemblyDefinition (Assembly assembly, MetadataImporter importer)
1400                 {
1401                         this.assembly = assembly;
1402                         this.aname = assembly.GetName ();
1403                         this.importer = importer;
1404                 }
1405
1406                 #region Properties
1407
1408                 public Assembly Assembly {
1409                         get {
1410                                 return assembly;
1411                         }
1412                 }
1413
1414                 public string FullName {
1415                         get {
1416                                 return aname.FullName;
1417                         }
1418                 }
1419
1420                 public bool HasExtensionMethod {
1421                         get {
1422                                 return contains_extension_methods;
1423                         }
1424                 }
1425
1426                 public bool HasStrongName {
1427                         get {
1428                                 return aname.GetPublicKey ().Length != 0;
1429                         }
1430                 }
1431
1432                 public bool IsCLSCompliant {
1433                         get {
1434                                 return cls_compliant;
1435                         }
1436                 }
1437
1438                 public string Location {
1439                         get {
1440                                 return assembly.Location;
1441                         }
1442                 }
1443
1444                 public string Name {
1445                         get {
1446                                 return aname.Name;
1447                         }
1448                 }
1449
1450                 #endregion
1451
1452                 public byte[] GetPublicKeyToken ()
1453                 {
1454                         return aname.GetPublicKeyToken ();
1455                 }
1456
1457                 public AssemblyName GetAssemblyVisibleToName (IAssemblyDefinition assembly)
1458                 {
1459                         return internals_visible_to_cache [assembly];
1460                 }
1461
1462                 public bool IsFriendAssemblyTo (IAssemblyDefinition assembly)
1463                 {
1464                         if (internals_visible_to == null)
1465                                 return false;
1466
1467                         AssemblyName is_visible = null;
1468                         if (internals_visible_to_cache == null) {
1469                                 internals_visible_to_cache = new Dictionary<IAssemblyDefinition, AssemblyName> ();
1470                         } else {
1471                                 if (internals_visible_to_cache.TryGetValue (assembly, out is_visible))
1472                                         return is_visible != null;
1473                         }
1474
1475                         var token = assembly.GetPublicKeyToken ();
1476                         if (token != null && token.Length == 0)
1477                                 token = null;
1478
1479                         foreach (var internals in internals_visible_to) {
1480                                 if (internals.Name != assembly.Name)
1481                                         continue;
1482
1483                                 if (token == null && assembly is AssemblyDefinition) {
1484                                         is_visible = internals;
1485                                         break;
1486                                 }
1487
1488                                 if (!ArrayComparer.IsEqual (token, internals.GetPublicKeyToken ()))
1489                                         continue;
1490
1491                                 is_visible = internals;
1492                                 break;
1493                         }
1494
1495                         internals_visible_to_cache.Add (assembly, is_visible);
1496                         return is_visible != null;
1497                 }
1498
1499                 public void ReadAttributes ()
1500                 {
1501                         IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (assembly);
1502
1503                         string ns, name;
1504                         foreach (var a in attrs) {
1505                                 importer.GetCustomAttributeTypeName (a, out ns, out name);
1506
1507                                 if (name == "CLSCompliantAttribute") {
1508                                         if (ns == "System")
1509                                                 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1510                                         continue;
1511                                 }
1512
1513                                 if (name == "InternalsVisibleToAttribute") {
1514                                         if (ns != MetadataImporter.CompilerServicesNamespace)
1515                                                 continue;
1516
1517                                         string s = a.ConstructorArguments[0].Value as string;
1518                                         if (s == null)
1519                                                 continue;
1520
1521                                         var an = new AssemblyName (s);
1522                                         if (internals_visible_to == null)
1523                                                 internals_visible_to = new List<AssemblyName> ();
1524
1525                                         internals_visible_to.Add (an);
1526                                         continue;
1527                                 }
1528
1529                                 if (name == "ExtensionAttribute") {
1530                                         if (ns == MetadataImporter.CompilerServicesNamespace)
1531                                                 contains_extension_methods = true;
1532
1533                                         continue;
1534                                 }
1535                         }
1536                 }
1537
1538                 public override string ToString ()
1539                 {
1540                         return FullName;
1541                 }
1542         }
1543
1544         class ImportedMemberDefinition : ImportedDefinition
1545         {
1546                 readonly TypeSpec type;
1547
1548                 public ImportedMemberDefinition (MemberInfo member, TypeSpec type, MetadataImporter importer)
1549                         : base (member, importer)
1550                 {
1551                         this.type = type;
1552                 }
1553
1554                 #region Properties
1555
1556                 public TypeSpec MemberType {
1557                         get {
1558                                 return type;
1559                         }
1560                 }
1561
1562                 #endregion
1563
1564                 public override List<MissingType> ResolveMissingDependencies ()
1565                 {
1566                         return type.GetMissingDependencies ();
1567                 }
1568         }
1569
1570         class ImportedParameterMemberDefinition : ImportedMemberDefinition, IParametersMember
1571         {
1572                 readonly AParametersCollection parameters;
1573
1574                 public ImportedParameterMemberDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1575                         : base (provider, type, importer)
1576                 {
1577                         this.parameters = parameters;
1578                 }
1579
1580                 public ImportedParameterMemberDefinition (PropertyInfo provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1581                         : base (provider, type, importer)
1582                 {
1583                         this.parameters = parameters;
1584                 }
1585
1586                 #region Properties
1587
1588                 public AParametersCollection Parameters {
1589                         get {
1590                                 return parameters;
1591                         }
1592                 }
1593
1594                 #endregion
1595
1596                 public override List<MissingType> ResolveMissingDependencies ()
1597                 {
1598                         var missing = base.ResolveMissingDependencies ();
1599                         foreach (var pt in parameters.Types) {
1600                                 var m = pt.GetMissingDependencies ();
1601                                 if (m == null)
1602                                         continue;
1603
1604                                 if (missing == null)
1605                                         missing = new List<MissingType> ();
1606
1607                                 missing.AddRange (m);
1608                         }
1609
1610                         return missing;
1611                 }
1612         }
1613
1614         class ImportedGenericMethodDefinition : ImportedParameterMemberDefinition, IGenericMethodDefinition
1615         {
1616                 readonly TypeParameterSpec[] tparams;
1617
1618                 public ImportedGenericMethodDefinition (MethodInfo provider, TypeSpec type, AParametersCollection parameters, TypeParameterSpec[] tparams, MetadataImporter importer)
1619                         : base (provider, type, parameters, importer)
1620                 {
1621                         this.tparams = tparams;
1622                 }
1623
1624                 #region Properties
1625
1626                 public TypeParameterSpec[] TypeParameters {
1627                         get {
1628                                 return tparams;
1629                         }
1630                 }
1631
1632                 public int TypeParametersCount {
1633                         get {
1634                                 return tparams.Length;
1635                         }
1636                 }
1637
1638                 #endregion
1639         }
1640
1641         class ImportedTypeDefinition : ImportedDefinition, ITypeDefinition
1642         {
1643                 TypeParameterSpec[] tparams;
1644                 string name;
1645
1646                 public ImportedTypeDefinition (MetaType type, MetadataImporter importer)
1647                         : base (type, importer)
1648                 {
1649                 }
1650
1651                 #region Properties
1652
1653                 public IAssemblyDefinition DeclaringAssembly {
1654                         get {
1655                                 return importer.GetAssemblyDefinition (provider.Module.Assembly);
1656                         }
1657                 }
1658
1659                 public override string Name {
1660                         get {
1661                                 if (name == null) {
1662                                         name = base.Name;
1663                                         if (tparams != null) {
1664                                                 int arity_start = name.IndexOf ('`');
1665                                                 if (arity_start > 0)
1666                                                         name = name.Substring (0, arity_start);
1667                                         }
1668                                 }
1669
1670                                 return name;
1671                         }
1672                 }
1673
1674                 public string Namespace {
1675                         get {
1676                                 return ((MetaType) provider).Namespace;
1677                         }
1678                 }
1679
1680                 public int TypeParametersCount {
1681                         get {
1682                                 return tparams == null ? 0 : tparams.Length;
1683                         }
1684                 }
1685
1686                 public TypeParameterSpec[] TypeParameters {
1687                         get {
1688                                 return tparams;
1689                         }
1690                         set {
1691                                 tparams = value;
1692                         }
1693                 }
1694
1695                 #endregion
1696
1697                 public static void Error_MissingDependency (IMemberContext ctx, List<MissingType> types, Location loc)
1698                 {
1699                         foreach (var t in types) {
1700                                 if (t.Module.Assembly.GetName ().Name == ctx.Module.DeclaringAssembly.Name) {
1701                                         ctx.Compiler.Report.Warning (1683, 1, loc,
1702                                                 "Reference to type `{0}' claims it is defined in this assembly, but it is not defined in source or any added modules",
1703                                                 t.Name);
1704                                 }
1705
1706                                 ctx.Compiler.Report.Error (12, loc,
1707                                         "The type `{0}' is defined in an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
1708                                         t.Name, t.Module.Assembly.FullName);
1709                         }
1710                 }
1711
1712                 public TypeSpec GetAttributeCoClass ()
1713                 {
1714                         if (cattrs == null)
1715                                 ReadAttributes ();
1716
1717                         return cattrs.CoClass;
1718                 }
1719
1720                 public string GetAttributeDefaultMember ()
1721                 {
1722                         if (cattrs == null)
1723                                 ReadAttributes ();
1724
1725                         return cattrs.DefaultIndexerName;
1726                 }
1727
1728                 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
1729                 {
1730                         if (cattrs == null)
1731                                 ReadAttributes ();
1732
1733                         return cattrs.AttributeUsage;
1734                 }
1735
1736                 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
1737                 {
1738                         var a = importer.GetAssemblyDefinition (provider.Module.Assembly);
1739                         return a == assembly || a.IsFriendAssemblyTo (assembly);
1740                 }
1741
1742                 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
1743                 {
1744                         //
1745                         // Not interested in members of nested private types unless the importer needs them
1746                         //
1747                         if (declaringType.IsPrivate && importer.IgnorePrivateMembers) {
1748                                 cache = MemberCache.Empty;
1749                                 return;
1750                         }
1751
1752                         var loading_type = (MetaType) provider;
1753                         const BindingFlags all_members = BindingFlags.DeclaredOnly |
1754                                 BindingFlags.Static | BindingFlags.Instance |
1755                                 BindingFlags.Public | BindingFlags.NonPublic;
1756
1757                         const MethodAttributes explicit_impl = MethodAttributes.NewSlot |
1758                                         MethodAttributes.Virtual | MethodAttributes.HideBySig |
1759                                         MethodAttributes.Final;
1760
1761                         Dictionary<MethodBase, MethodSpec> possible_accessors = null;
1762                         List<EventSpec> imported_events = null;
1763                         EventSpec event_spec;
1764                         MemberSpec imported;
1765                         MethodInfo m;
1766                         MemberInfo[] all;
1767                         try {
1768                                 all = loading_type.GetMembers (all_members);
1769                         } catch (Exception e) {
1770                                 throw new InternalErrorException (e, "Could not import type `{0}' from `{1}'",
1771                                         declaringType.GetSignatureForError (), declaringType.MemberDefinition.DeclaringAssembly.FullName);
1772                         }
1773
1774                         if (cache == null) {
1775                                 cache = new MemberCache (all.Length);
1776
1777                                 //
1778                                 // Do the types first as they can be referenced by the members before
1779                                 // they are found or inflated
1780                                 //
1781                                 foreach (var member in all) {
1782                                         if (member.MemberType != MemberTypes.NestedType)
1783                                                 continue;
1784
1785                                         var t = (MetaType) member;
1786
1787                                         // Ignore compiler generated types, mostly lambda containers
1788                                         if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate)
1789                                                 continue;
1790
1791                                         imported = importer.CreateNestedType (t, declaringType);
1792                                         cache.AddMember (imported);
1793                                 }
1794
1795                                 foreach (var member in all) {
1796                                         if (member.MemberType != MemberTypes.NestedType)
1797                                                 continue;
1798
1799                                         var t = (MetaType) member;
1800
1801                                         if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate)
1802                                                 continue;
1803
1804                                         importer.ImportTypeBase (t);
1805                                 }
1806                         }
1807
1808                         if (!onlyTypes) {
1809                                 //
1810                                 // The logic here requires methods to be returned first which seems to work for both Mono and .NET
1811                                 //
1812                                 foreach (var member in all) {
1813                                         switch (member.MemberType) {
1814                                         case MemberTypes.Constructor:
1815                                         case MemberTypes.Method:
1816                                                 MethodBase mb = (MethodBase) member;
1817                                                 var attrs = mb.Attributes;
1818
1819                                                 if ((attrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) {
1820                                                         if (importer.IgnorePrivateMembers)
1821                                                                 continue;
1822
1823                                                         // Ignore explicitly implemented members
1824                                                         if ((attrs & explicit_impl) == explicit_impl)
1825                                                                 continue;
1826
1827                                                         // Ignore compiler generated methods
1828                                                         if (importer.HasAttribute (CustomAttributeData.GetCustomAttributes (mb), "CompilerGeneratedAttribute", MetadataImporter.CompilerServicesNamespace))
1829                                                                 continue;
1830                                                 }
1831
1832                                                 imported = importer.CreateMethod (mb, declaringType);
1833                                                 if (imported.Kind == MemberKind.Method && !imported.IsGeneric) {
1834                                                         if (possible_accessors == null)
1835                                                                 possible_accessors = new Dictionary<MethodBase, MethodSpec> (ReferenceEquality<MethodBase>.Default);
1836
1837                                                         // There are no metadata rules for accessors, we have to consider any method as possible candidate
1838                                                         possible_accessors.Add (mb, (MethodSpec) imported);
1839                                                 }
1840
1841                                                 break;
1842                                         case MemberTypes.Property:
1843                                                 if (possible_accessors == null)
1844                                                         continue;
1845
1846                                                 var p = (PropertyInfo) member;
1847                                                 //
1848                                                 // Links possible accessors with property
1849                                                 //
1850                                                 MethodSpec get, set;
1851                                                 m = p.GetGetMethod (true);
1852                                                 if (m == null || !possible_accessors.TryGetValue (m, out get))
1853                                                         get = null;
1854
1855                                                 m = p.GetSetMethod (true);
1856                                                 if (m == null || !possible_accessors.TryGetValue (m, out set))
1857                                                         set = null;
1858
1859                                                 // No accessors registered (e.g. explicit implementation)
1860                                                 if (get == null && set == null)
1861                                                         continue;
1862
1863                                                 imported = importer.CreateProperty (p, declaringType, get, set);
1864                                                 if (imported == null)
1865                                                         continue;
1866
1867                                                 break;
1868                                         case MemberTypes.Event:
1869                                                 if (possible_accessors == null)
1870                                                         continue;
1871
1872                                                 var e = (EventInfo) member;
1873                                                 //
1874                                                 // Links accessors with event
1875                                                 //
1876                                                 MethodSpec add, remove;
1877                                                 m = e.GetAddMethod (true);
1878                                                 if (m == null || !possible_accessors.TryGetValue (m, out add))
1879                                                         add = null;
1880
1881                                                 m = e.GetRemoveMethod (true);
1882                                                 if (m == null || !possible_accessors.TryGetValue (m, out remove))
1883                                                         remove = null;
1884
1885                                                 // Both accessors are required
1886                                                 if (add == null || remove == null)
1887                                                         continue;
1888
1889                                                 event_spec = importer.CreateEvent (e, declaringType, add, remove);
1890                                                 if (!importer.IgnorePrivateMembers) {
1891                                                         if (imported_events == null)
1892                                                                 imported_events = new List<EventSpec> ();
1893
1894                                                         imported_events.Add (event_spec);
1895                                                 }
1896
1897                                                 imported = event_spec;
1898                                                 break;
1899                                         case MemberTypes.Field:
1900                                                 var fi = (FieldInfo) member;
1901
1902                                                 imported = importer.CreateField (fi, declaringType);
1903                                                 if (imported == null)
1904                                                         continue;
1905
1906                                                 //
1907                                                 // For dynamic binder event has to be fully restored to allow operations
1908                                                 // within the type container to work correctly
1909                                                 //
1910                                                 if (imported_events != null) {
1911                                                         // The backing event field should be private but it may not
1912                                                         int index = imported_events.FindIndex (l => l.Name == fi.Name);
1913                                                         if (index >= 0) {
1914                                                                 event_spec = imported_events[index];
1915                                                                 event_spec.BackingField = (FieldSpec) imported;
1916                                                                 imported_events.RemoveAt (index);
1917                                                                 continue;
1918                                                         }
1919                                                 }
1920
1921                                                 break;
1922                                         case MemberTypes.NestedType:
1923                                                 // Already in the cache from the first pass
1924                                                 continue;
1925                                         default:
1926                                                 throw new NotImplementedException (member.ToString ());
1927                                         }
1928
1929                                         cache.AddMember (imported);
1930                                 }
1931                         }
1932
1933                         if (declaringType.IsInterface && declaringType.Interfaces != null) {
1934                                 foreach (var iface in declaringType.Interfaces) {
1935                                         cache.AddInterface (iface);
1936                                 }
1937                         }
1938                 }
1939
1940                 public override List<MissingType> ResolveMissingDependencies ()
1941                 {
1942 #if STATIC
1943                         List<MissingType> missing = null;
1944
1945                         MetaType mt = (MetaType) provider;
1946                         do {
1947                                 if (mt is MissingType) {
1948                                         missing = new List<MissingType> ();
1949                                         missing.Add ((MissingType) mt);
1950                                 }
1951
1952                                 foreach (var iface in mt.GetInterfaces ()) {
1953                                         if (iface is MissingType) {
1954                                                 if (missing == null)
1955                                                         missing = new List<MissingType> ();
1956
1957                                                 missing.Add ((MissingType) iface);
1958                                         }
1959                                 }
1960
1961                                 if (missing != null)
1962                                         return missing;
1963
1964                                 mt = mt.BaseType;
1965                         } while (mt != null);
1966 #endif
1967                         return null;
1968                 }
1969         }
1970
1971         class ImportedTypeParameterDefinition : ImportedDefinition, ITypeDefinition
1972         {
1973                 public ImportedTypeParameterDefinition (MetaType type, MetadataImporter importer)
1974                         : base (type, importer)
1975                 {
1976                 }
1977
1978                 #region Properties
1979
1980                 public IAssemblyDefinition DeclaringAssembly {
1981                         get {
1982                                 throw new NotImplementedException ();
1983                         }
1984                 }
1985
1986                 public string Namespace {
1987                         get {
1988                                 return null;
1989                         }
1990                 }
1991
1992                 public int TypeParametersCount {
1993                         get {
1994                                 return 0;
1995                         }
1996                 }
1997
1998                 public TypeParameterSpec[] TypeParameters {
1999                         get {
2000                                 return null;
2001                         }
2002                 }
2003
2004                 #endregion
2005
2006                 public TypeSpec GetAttributeCoClass ()
2007                 {
2008                         return null;
2009                 }
2010
2011                 public string GetAttributeDefaultMember ()
2012                 {
2013                         throw new NotSupportedException ();
2014                 }
2015
2016                 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
2017                 {
2018                         throw new NotSupportedException ();
2019                 }
2020
2021                 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2022                 {
2023                         throw new NotImplementedException ();
2024                 }
2025
2026                 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2027                 {
2028                         throw new NotImplementedException ();
2029                 }
2030
2031                 public override List<MissingType> ResolveMissingDependencies ()
2032                 {
2033                         return null;
2034                 }
2035         }
2036 }