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