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