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