Remove some unused parameters
[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 (MetadataImporter importer)
60                         {
61                                 if (provider != null)
62                                         ReadAttribute (importer);
63
64                                 return flags != null && Position < flags.Length && flags[Position];
65                         }
66
67                         //
68                         // Returns true when DynamicAttribute exists
69                         //
70                         public bool HasDynamicAttribute (MetadataImporter importer)
71                         {
72                                 if (provider != null)
73                                         ReadAttribute (importer);
74
75                                 return flags != null;
76                         }
77
78                         void ReadAttribute (MetadataImporter importer)
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 (this))
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 (this))
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                                                 mod |= Modifiers.SEALED;
860                                                 if ((ma & TypeAttributes.Abstract) != 0)
861                                                         mod |= Modifiers.STATIC;
862                                         } else if ((ma & TypeAttributes.Abstract) != 0) {
863                                                 mod |= Modifiers.ABSTRACT;
864                                         }
865                                 }
866                         }
867
868                         var definition = new ImportedTypeDefinition (type, this);
869                         TypeSpec pt;
870
871                         if (kind == MemberKind.Enum) {
872                                 const BindingFlags underlying_member = BindingFlags.DeclaredOnly |
873                                         BindingFlags.Instance |
874                                         BindingFlags.Public | BindingFlags.NonPublic;
875
876                                 var type_members = type.GetFields (underlying_member);
877                                 foreach (var type_member in type_members) {
878                                         spec = new EnumSpec (declaringType, definition, CreateType (type_member.FieldType), type, mod);
879                                         break;
880                                 }
881
882                                 if (spec == null)
883                                         kind = MemberKind.Class;
884
885                         } else if (kind == MemberKind.TypeParameter) {
886                                 spec = CreateTypeParameter (type, declaringType);
887                         } else if (type.IsGenericTypeDefinition) {
888                                 definition.TypeParameters = CreateGenericParameters (type, declaringType);
889                         } else if (compiled_types.TryGetValue (type, out pt)) {
890                                 //
891                                 // Same type was found in inside compiled types. It's
892                                 // either build-in type or forward referenced typed
893                                 // which point into just compiled assembly.
894                                 //
895                                 spec = pt;
896                                 BuiltinTypeSpec bts = pt as BuiltinTypeSpec;
897                                 if (bts != null)
898                                         bts.SetDefinition (definition, type, mod);
899                         }
900
901                         if (spec == null)
902                                 spec = new TypeSpec (kind, declaringType, definition, type, mod);
903
904                         import_cache.Add (type, spec);
905
906                         if (kind == MemberKind.TypeParameter) {
907                                 if (canImportBaseType)
908                                         ImportTypeParameterTypeConstraints ((TypeParameterSpec) spec, type);
909
910                                 return spec;
911                         }
912
913                         //
914                         // Two stage setup as the base type can be inflated declaring type or
915                         // another nested type inside same declaring type which has not been
916                         // loaded, therefore we can import a base type of nested types once
917                         // the types have been imported
918                         //
919                         if (canImportBaseType)
920                                 ImportTypeBase (spec, type);
921
922                         return spec;
923                 }
924
925                 public IAssemblyDefinition GetAssemblyDefinition (Assembly assembly)
926                 {
927                         IAssemblyDefinition found;
928                         if (!assembly_2_definition.TryGetValue (assembly, out found)) {
929
930                                 // This can happen in dynamic context only
931                                 var def = new ImportedAssemblyDefinition (assembly);
932                                 assembly_2_definition.Add (assembly, def);
933                                 def.ReadAttributes ();
934                                 found = def;
935                         }
936
937                         return found;
938                 }
939
940                 public void ImportTypeBase (MetaType type)
941                 {
942                         TypeSpec spec = import_cache[type];
943                         if (spec != null)
944                                 ImportTypeBase (spec, type);
945                 }
946
947                 TypeParameterSpec CreateTypeParameter (MetaType type, TypeSpec declaringType)
948                 {
949                         Variance variance;
950                         switch (type.GenericParameterAttributes & GenericParameterAttributes.VarianceMask) {
951                         case GenericParameterAttributes.Covariant:
952                                 variance = Variance.Covariant;
953                                 break;
954                         case GenericParameterAttributes.Contravariant:
955                                 variance = Variance.Contravariant;
956                                 break;
957                         default:
958                                 variance = Variance.None;
959                                 break;
960                         }
961
962                         SpecialConstraint special = SpecialConstraint.None;
963                         var import_special = type.GenericParameterAttributes & GenericParameterAttributes.SpecialConstraintMask;
964
965                         if ((import_special & GenericParameterAttributes.NotNullableValueTypeConstraint) != 0) {
966                                 special |= SpecialConstraint.Struct;
967                         } else if ((import_special & GenericParameterAttributes.DefaultConstructorConstraint) != 0) {
968                                 special = SpecialConstraint.Constructor;
969                         }
970
971                         if ((import_special & GenericParameterAttributes.ReferenceTypeConstraint) != 0) {
972                                 special |= SpecialConstraint.Class;
973                         }
974
975                         TypeParameterSpec spec;
976                         var def = new ImportedTypeParameterDefinition (type, this);
977                         if (type.DeclaringMethod != null) {
978                                 spec = new TypeParameterSpec (type.GenericParameterPosition, def, special, variance, type);
979                         } else {
980                                 spec = new TypeParameterSpec (declaringType, type.GenericParameterPosition, def, special, variance, type);
981                         }
982
983                         return spec;
984                 }
985
986                 //
987                 // Test for a custom attribute type match. Custom attributes are not really predefined globaly 
988                 // they can be assembly specific therefore we do check based on names only
989                 //
990                 public static bool HasAttribute (IList<CustomAttributeData> attributesData, string attrName, string attrNamespace)
991                 {
992                         if (attributesData.Count == 0)
993                                 return false;
994
995                         foreach (var attr in attributesData) {
996                                 var dt = attr.Constructor.DeclaringType;
997                                 if (dt.Name == attrName && dt.Namespace == attrNamespace)
998                                         return true;
999                         }
1000
1001                         return false;
1002                 }
1003
1004                 void ImportTypeBase (TypeSpec spec, MetaType type)
1005                 {
1006                         if (spec.Kind == MemberKind.Interface)
1007                                 spec.BaseType = module.Compiler.BuiltinTypes.Object;
1008                         else if (type.BaseType != null) {
1009                                 TypeSpec base_type;
1010                                 if (!IsMissingType (type.BaseType) && type.BaseType.IsGenericType)
1011                                         base_type = CreateType (type.BaseType, new DynamicTypeReader (type), true);
1012                                 else
1013                                         base_type = CreateType (type.BaseType);
1014
1015                                 spec.BaseType = base_type;
1016                         }
1017
1018                         if (spec.MemberDefinition.TypeParametersCount > 0) {
1019                                 foreach (var tp in spec.MemberDefinition.TypeParameters) {
1020                                         ImportTypeParameterTypeConstraints (tp, tp.GetMetaInfo ());
1021                                 }
1022                         }
1023                 }
1024
1025                 protected void ImportTypes (MetaType[] types, Namespace targetNamespace, bool importExtensionTypes)
1026                 {
1027                         Namespace ns = targetNamespace;
1028                         string prev_namespace = null;
1029                         foreach (var t in types) {
1030                                 if (t == null)
1031                                         continue;
1032
1033                                 // Be careful not to trigger full parent type loading
1034                                 if (t.MemberType == MemberTypes.NestedType)
1035                                         continue;
1036
1037                                 if (t.Name[0] == '<')
1038                                         continue;
1039
1040                                 var it = CreateType (t, null, new DynamicTypeReader (t), true);
1041                                 if (it == null)
1042                                         continue;
1043
1044                                 if (prev_namespace != t.Namespace) {
1045                                         ns = t.Namespace == null ? targetNamespace : targetNamespace.GetNamespace (t.Namespace, true);
1046                                         prev_namespace = t.Namespace;
1047                                 }
1048
1049                                 // Cannot rely on assembly level Extension attribute or static modifier because they
1050                                 // are not followed by other compilers (e.g. F#).
1051                                 if (it.IsClass && it.Arity == 0 && importExtensionTypes &&
1052                                         HasAttribute (CustomAttributeData.GetCustomAttributes (t), "ExtensionAttribute", CompilerServicesNamespace)) {
1053                                         it.SetExtensionMethodContainer ();
1054                                 }
1055
1056                                 ns.AddType (module, it);
1057                         }
1058                 }
1059
1060                 void ImportTypeParameterTypeConstraints (TypeParameterSpec spec, MetaType type)
1061                 {
1062                         var constraints = type.GetGenericParameterConstraints ();
1063                         List<TypeSpec> tparams = null;
1064                         foreach (var ct in constraints) {
1065                                 if (ct.IsGenericParameter) {
1066                                         if (tparams == null)
1067                                                 tparams = new List<TypeSpec> ();
1068
1069                                         tparams.Add (CreateType (ct));
1070                                         continue;
1071                                 }
1072
1073                                 var constraint_type = CreateType (ct);
1074                                 if (constraint_type.IsClass) {
1075                                         spec.BaseType = constraint_type;
1076                                         continue;
1077                                 }
1078
1079                                 spec.AddInterface (constraint_type);
1080                         }
1081
1082                         if (spec.BaseType == null)
1083                                 spec.BaseType = module.Compiler.BuiltinTypes.Object;
1084
1085                         if (tparams != null)
1086                                 spec.TypeArguments = tparams.ToArray ();
1087                 }
1088
1089                 Constant ImportParameterConstant (object value)
1090                 {
1091                         //
1092                         // Get type of underlying value as int constant can be used for object
1093                         // parameter type. This is not allowed in C# but other languages can do that
1094                         //
1095                         var types = module.Compiler.BuiltinTypes;
1096                         switch (System.Type.GetTypeCode (value.GetType ())) {
1097                         case TypeCode.Boolean:
1098                                 return new BoolConstant (types, (bool) value, Location.Null);
1099                         case TypeCode.Byte:
1100                                 return new ByteConstant (types, (byte) value, Location.Null);
1101                         case TypeCode.Char:
1102                                 return new CharConstant (types, (char) value, Location.Null);
1103                         case TypeCode.Decimal:
1104                                 return new DecimalConstant (types, (decimal) value, Location.Null);
1105                         case TypeCode.Double:
1106                                 return new DoubleConstant (types, (double) value, Location.Null);
1107                         case TypeCode.Int16:
1108                                 return new ShortConstant (types, (short) value, Location.Null);
1109                         case TypeCode.Int32:
1110                                 return new IntConstant (types, (int) value, Location.Null);
1111                         case TypeCode.Int64:
1112                                 return new LongConstant (types, (long) value, Location.Null);
1113                         case TypeCode.SByte:
1114                                 return new SByteConstant (types, (sbyte) value, Location.Null);
1115                         case TypeCode.Single:
1116                                 return new FloatConstant (types, (float) value, Location.Null);
1117                         case TypeCode.String:
1118                                 return new StringConstant (types, (string) value, Location.Null);
1119                         case TypeCode.UInt16:
1120                                 return new UShortConstant (types, (ushort) value, Location.Null);
1121                         case TypeCode.UInt32:
1122                                 return new UIntConstant (types, (uint) value, Location.Null);
1123                         case TypeCode.UInt64:
1124                                 return new ULongConstant (types, (ulong) value, Location.Null);
1125                         }
1126
1127                         throw new NotImplementedException (value.GetType ().ToString ());
1128                 }
1129
1130                 public TypeSpec ImportType (MetaType type)
1131                 {
1132                         return ImportType (type, new DynamicTypeReader (type));
1133                 }
1134
1135                 TypeSpec ImportType (MetaType type, DynamicTypeReader dtype)
1136                 {
1137                         if (type.HasElementType) {
1138                                 var element = type.GetElementType ();
1139                                 ++dtype.Position;
1140                                 var spec = ImportType (element, dtype);
1141
1142                                 if (type.IsArray)
1143                                         return ArrayContainer.MakeType (module, spec, type.GetArrayRank ());
1144                                 if (type.IsByRef)
1145                                         return ReferenceContainer.MakeType (module, spec);
1146                                 if (type.IsPointer)
1147                                         return PointerContainer.MakeType (module, spec);
1148
1149                                 throw new NotImplementedException ("Unknown element type " + type.ToString ());
1150                         }
1151
1152                         return CreateType (type, dtype, true);
1153                 }
1154
1155                 static bool IsMissingType (MetaType type)
1156                 {
1157 #if STATIC
1158                         return type.__IsMissing;
1159 #else
1160                         return false;
1161 #endif
1162                 }
1163
1164                 //
1165                 // Decimal constants cannot be encoded in the constant blob, and thus are marked
1166                 // as IsInitOnly ('readonly' in C# parlance).  We get its value from the 
1167                 // DecimalConstantAttribute metadata.
1168                 //
1169                 Constant ReadDecimalConstant (IList<CustomAttributeData> attrs)
1170                 {
1171                         if (attrs.Count == 0)
1172                                 return null;
1173
1174                         foreach (var ca in attrs) {
1175                                 var dt = ca.Constructor.DeclaringType;
1176                                 if (dt.Name != "DecimalConstantAttribute" || dt.Namespace != CompilerServicesNamespace)
1177                                         continue;
1178
1179                                 var value = new decimal (
1180                                         (int) (uint) ca.ConstructorArguments[4].Value,
1181                                         (int) (uint) ca.ConstructorArguments[3].Value,
1182                                         (int) (uint) ca.ConstructorArguments[2].Value,
1183                                         (byte) ca.ConstructorArguments[1].Value != 0,
1184                                         (byte) ca.ConstructorArguments[0].Value);
1185
1186                                 return new DecimalConstant (module.Compiler.BuiltinTypes, value, Location.Null);
1187                         }
1188
1189                         return null;
1190                 }
1191
1192                 static Modifiers ReadMethodModifiers (MethodBase mb, TypeSpec declaringType)
1193                 {
1194                         Modifiers mod;
1195                         var ma = mb.Attributes;
1196                         switch (ma & MethodAttributes.MemberAccessMask) {
1197                         case MethodAttributes.Public:
1198                                 mod = Modifiers.PUBLIC;
1199                                 break;
1200                         case MethodAttributes.Assembly:
1201                                 mod = Modifiers.INTERNAL;
1202                                 break;
1203                         case MethodAttributes.Family:
1204                                 mod = Modifiers.PROTECTED;
1205                                 break;
1206                         case MethodAttributes.FamORAssem:
1207                                 mod = Modifiers.PROTECTED | Modifiers.INTERNAL;
1208                                 break;
1209                         default:
1210                                 mod = Modifiers.PRIVATE;
1211                                 break;
1212                         }
1213
1214                         if ((ma & MethodAttributes.Static) != 0) {
1215                                 mod |= Modifiers.STATIC;
1216                                 return mod;
1217                         }
1218                         if ((ma & MethodAttributes.Abstract) != 0 && declaringType.IsClass) {
1219                                 mod |= Modifiers.ABSTRACT;
1220                                 return mod;
1221                         }
1222
1223                         // It can be sealed and override
1224                         if ((ma & MethodAttributes.Final) != 0)
1225                                 mod |= Modifiers.SEALED;
1226
1227                         if ((ma & MethodAttributes.Virtual) != 0) {
1228                                 // Not every member can be detected based on MethodAttribute, we
1229                                 // set virtual or non-virtual only when we are certain. Further checks
1230                                 // to really find out what `virtual' means for this member are done
1231                                 // later
1232                                 if ((ma & MethodAttributes.NewSlot) != 0) {
1233                                         if ((mod & Modifiers.SEALED) != 0) {
1234                                                 mod &= ~Modifiers.SEALED;
1235                                         } else {
1236                                                 mod |= Modifiers.VIRTUAL;
1237                                         }
1238                                 } else {
1239                                         mod |= Modifiers.OVERRIDE;
1240                                 }
1241                         }
1242
1243                         return mod;
1244                 }
1245         }
1246
1247         abstract class ImportedDefinition : IMemberDefinition
1248         {
1249                 protected class AttributesBag
1250                 {
1251                         public static readonly AttributesBag Default = new AttributesBag ();
1252
1253                         public AttributeUsageAttribute AttributeUsage;
1254                         public ObsoleteAttribute Obsolete;
1255                         public string[] Conditionals;
1256                         public string DefaultIndexerName;
1257                         public bool? CLSAttributeValue;
1258                         public TypeSpec CoClass;
1259                         
1260                         public static AttributesBag Read (MemberInfo mi, MetadataImporter importer)
1261                         {
1262                                 AttributesBag bag = null;
1263                                 List<string> conditionals = null;
1264
1265                                 // It should not throw any loading exception
1266                                 IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (mi);
1267
1268                                 foreach (var a in attrs) {
1269                                         var dt = a.Constructor.DeclaringType;
1270                                         string name = dt.Name;
1271                                         if (name == "ObsoleteAttribute") {
1272                                                 if (dt.Namespace != "System")
1273                                                         continue;
1274
1275                                                 if (bag == null)
1276                                                         bag = new AttributesBag ();
1277
1278                                                 var args = a.ConstructorArguments;
1279
1280                                                 if (args.Count == 1) {
1281                                                         bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value);
1282                                                 } else if (args.Count == 2) {
1283                                                         bag.Obsolete = new ObsoleteAttribute ((string) args[0].Value, (bool) args[1].Value);
1284                                                 } else {
1285                                                         bag.Obsolete = new ObsoleteAttribute ();
1286                                                 }
1287
1288                                                 continue;
1289                                         }
1290
1291                                         if (name == "ConditionalAttribute") {
1292                                                 if (dt.Namespace != "System.Diagnostics")
1293                                                         continue;
1294
1295                                                 if (bag == null)
1296                                                         bag = new AttributesBag ();
1297
1298                                                 if (conditionals == null)
1299                                                         conditionals = new List<string> (2);
1300
1301                                                 conditionals.Add ((string) a.ConstructorArguments[0].Value);
1302                                                 continue;
1303                                         }
1304
1305                                         if (name == "CLSCompliantAttribute") {
1306                                                 if (dt.Namespace != "System")
1307                                                         continue;
1308
1309                                                 if (bag == null)
1310                                                         bag = new AttributesBag ();
1311
1312                                                 bag.CLSAttributeValue = (bool) a.ConstructorArguments[0].Value;
1313                                                 continue;
1314                                         }
1315
1316                                         // Type only attributes
1317                                         if (mi.MemberType == MemberTypes.TypeInfo || mi.MemberType == MemberTypes.NestedType) {
1318                                                 if (name == "DefaultMemberAttribute") {
1319                                                         if (dt.Namespace != "System.Reflection")
1320                                                                 continue;
1321
1322                                                         if (bag == null)
1323                                                                 bag = new AttributesBag ();
1324
1325                                                         bag.DefaultIndexerName = (string) a.ConstructorArguments[0].Value;
1326                                                         continue;
1327                                                 }
1328
1329                                                 if (name == "AttributeUsageAttribute") {
1330                                                         if (dt.Namespace != "System")
1331                                                                 continue;
1332
1333                                                         if (bag == null)
1334                                                                 bag = new AttributesBag ();
1335
1336                                                         bag.AttributeUsage = new AttributeUsageAttribute ((AttributeTargets) a.ConstructorArguments[0].Value);
1337                                                         foreach (var named in a.NamedArguments) {
1338                                                                 if (named.MemberInfo.Name == "AllowMultiple")
1339                                                                         bag.AttributeUsage.AllowMultiple = (bool) named.TypedValue.Value;
1340                                                                 else if (named.MemberInfo.Name == "Inherited")
1341                                                                         bag.AttributeUsage.Inherited = (bool) named.TypedValue.Value;
1342                                                         }
1343                                                         continue;
1344                                                 }
1345
1346                                                 // Interface only attribute
1347                                                 if (name == "CoClassAttribute") {
1348                                                         if (dt.Namespace != "System.Runtime.InteropServices")
1349                                                                 continue;
1350
1351                                                         if (bag == null)
1352                                                                 bag = new AttributesBag ();
1353
1354                                                         bag.CoClass = importer.ImportType ((MetaType) a.ConstructorArguments[0].Value);
1355                                                         continue;
1356                                                 }
1357                                         }
1358                                 }
1359
1360                                 if (bag == null)
1361                                         return Default;
1362
1363                                 if (conditionals != null)
1364                                         bag.Conditionals = conditionals.ToArray ();
1365                                 
1366                                 return bag;
1367                         }
1368                 }
1369
1370                 protected readonly MemberInfo provider;
1371                 protected AttributesBag cattrs;
1372                 protected readonly MetadataImporter importer;
1373
1374                 public ImportedDefinition (MemberInfo provider, MetadataImporter importer)
1375                 {
1376                         this.provider = provider;
1377                         this.importer = importer;
1378                 }
1379
1380                 #region Properties
1381
1382                 public bool IsImported {
1383                         get {
1384                                 return true;
1385                         }
1386                 }
1387
1388                 public virtual string Name {
1389                         get {
1390                                 return provider.Name;
1391                         }
1392                 }
1393
1394                 #endregion
1395
1396                 public string[] ConditionalConditions ()
1397                 {
1398                         if (cattrs == null)
1399                                 ReadAttributes ();
1400
1401                         return cattrs.Conditionals;
1402                 }
1403
1404                 public ObsoleteAttribute GetAttributeObsolete ()
1405                 {
1406                         if (cattrs == null)
1407                                 ReadAttributes ();
1408
1409                         return cattrs.Obsolete;
1410                 }
1411
1412                 public bool? CLSAttributeValue {
1413                         get {
1414                                 if (cattrs == null)
1415                                         ReadAttributes ();
1416
1417                                 return cattrs.CLSAttributeValue;
1418                         }
1419                 }
1420
1421                 protected void ReadAttributes ()
1422                 {
1423                         cattrs = AttributesBag.Read (provider, importer);
1424                 }
1425
1426                 public void SetIsAssigned ()
1427                 {
1428                         // Unused for imported members
1429                 }
1430
1431                 public void SetIsUsed ()
1432                 {
1433                         // Unused for imported members
1434                 }
1435         }
1436
1437         public class ImportedModuleDefinition
1438         {
1439                 readonly Module module;
1440                 bool cls_compliant;
1441                 
1442                 public ImportedModuleDefinition (Module module)
1443                 {
1444                         this.module = module;
1445                 }
1446
1447                 #region Properties
1448
1449                 public bool IsCLSCompliant {
1450                         get {
1451                                 return cls_compliant;
1452                         }
1453                 }
1454
1455                 public string Name {
1456                         get {
1457                                 return module.Name;
1458                         }
1459                 }
1460
1461                 #endregion
1462
1463                 public void ReadAttributes ()
1464                 {
1465                         IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (module);
1466
1467                         foreach (var a in attrs) {
1468                                 var dt = a.Constructor.DeclaringType;
1469                                 if (dt.Name == "CLSCompliantAttribute") {
1470                                         if (dt.Namespace != "System")
1471                                                 continue;
1472
1473                                         cls_compliant = (bool) a.ConstructorArguments[0].Value;
1474                                         continue;
1475                                 }
1476                         }
1477                 }
1478
1479                 //
1480                 // Reads assembly attributes which where attached to a special type because
1481                 // module does have assembly manifest
1482                 //
1483                 public List<Attribute> ReadAssemblyAttributes ()
1484                 {
1485                         var t = module.GetType (AssemblyAttributesPlaceholder.GetGeneratedName (Name));
1486                         if (t == null)
1487                                 return null;
1488
1489                         var field = t.GetField (AssemblyAttributesPlaceholder.AssemblyFieldName, BindingFlags.NonPublic | BindingFlags.Static);
1490                         if (field == null)
1491                                 return null;
1492
1493                         // TODO: implement, the idea is to fabricate specil Attribute class and
1494                         // add it to OptAttributes before resolving the source code attributes
1495                         // Need to build module location as well for correct error reporting
1496
1497                         //var assembly_attributes = CustomAttributeData.GetCustomAttributes (field);
1498                         //var attrs = new List<Attribute> (assembly_attributes.Count);
1499                         //foreach (var a in assembly_attributes)
1500                         //{
1501                         //    var type = metaImporter.ImportType (a.Constructor.DeclaringType);
1502                         //    var ctor = metaImporter.CreateMethod (a.Constructor, type);
1503
1504                         //    foreach (var carg in a.ConstructorArguments) {
1505                         //        carg.Value
1506                         //    }
1507
1508                         //    attrs.Add (new Attribute ("assembly", ctor, null, Location.Null, true));
1509                         //}
1510
1511                         return null;
1512                 }
1513         }
1514
1515         public class ImportedAssemblyDefinition : IAssemblyDefinition
1516         {
1517                 readonly Assembly assembly;
1518                 readonly AssemblyName aname;
1519                 bool cls_compliant;
1520
1521                 List<AssemblyName> internals_visible_to;
1522                 Dictionary<IAssemblyDefinition, AssemblyName> internals_visible_to_cache;
1523
1524                 public ImportedAssemblyDefinition (Assembly assembly)
1525                 {
1526                         this.assembly = assembly;
1527                         this.aname = assembly.GetName ();
1528                 }
1529
1530                 #region Properties
1531
1532                 public Assembly Assembly {
1533                         get {
1534                                 return assembly;
1535                         }
1536                 }
1537
1538                 public string FullName {
1539                         get {
1540                                 return aname.FullName;
1541                         }
1542                 }
1543
1544                 public bool HasStrongName {
1545                         get {
1546                                 return aname.GetPublicKey ().Length != 0;
1547                         }
1548                 }
1549
1550                 public bool IsMissing {
1551                         get {
1552 #if STATIC
1553                                 return assembly.__IsMissing;
1554 #else
1555                                 return false;
1556 #endif
1557                         }
1558                 }
1559
1560                 public bool IsCLSCompliant {
1561                         get {
1562                                 return cls_compliant;
1563                         }
1564                 }
1565
1566                 public string Location {
1567                         get {
1568                                 return assembly.Location;
1569                         }
1570                 }
1571
1572                 public string Name {
1573                         get {
1574                                 return aname.Name;
1575                         }
1576                 }
1577
1578                 #endregion
1579
1580                 public byte[] GetPublicKeyToken ()
1581                 {
1582                         return aname.GetPublicKeyToken ();
1583                 }
1584
1585                 public AssemblyName GetAssemblyVisibleToName (IAssemblyDefinition assembly)
1586                 {
1587                         return internals_visible_to_cache [assembly];
1588                 }
1589
1590                 public bool IsFriendAssemblyTo (IAssemblyDefinition assembly)
1591                 {
1592                         if (internals_visible_to == null)
1593                                 return false;
1594
1595                         AssemblyName is_visible = null;
1596                         if (internals_visible_to_cache == null) {
1597                                 internals_visible_to_cache = new Dictionary<IAssemblyDefinition, AssemblyName> ();
1598                         } else {
1599                                 if (internals_visible_to_cache.TryGetValue (assembly, out is_visible))
1600                                         return is_visible != null;
1601                         }
1602
1603                         var token = assembly.GetPublicKeyToken ();
1604                         if (token != null && token.Length == 0)
1605                                 token = null;
1606
1607                         foreach (var internals in internals_visible_to) {
1608                                 if (internals.Name != assembly.Name)
1609                                         continue;
1610
1611                                 if (token == null && assembly is AssemblyDefinition) {
1612                                         is_visible = internals;
1613                                         break;
1614                                 }
1615
1616                                 if (!ArrayComparer.IsEqual (token, internals.GetPublicKeyToken ()))
1617                                         continue;
1618
1619                                 is_visible = internals;
1620                                 break;
1621                         }
1622
1623                         internals_visible_to_cache.Add (assembly, is_visible);
1624                         return is_visible != null;
1625                 }
1626
1627                 public void ReadAttributes ()
1628                 {
1629 #if STATIC
1630                         if (assembly.__IsMissing)
1631                                 return;
1632 #endif
1633
1634                         IList<CustomAttributeData> attrs = CustomAttributeData.GetCustomAttributes (assembly);
1635
1636                         foreach (var a in attrs) {
1637                                 var dt = a.Constructor.DeclaringType;
1638                                 var name = dt.Name;
1639                                 if (name == "CLSCompliantAttribute") {
1640                                         if (dt.Namespace == "System") {
1641                                                 cls_compliant = (bool) a.ConstructorArguments[0].Value;
1642                                         }
1643                                         continue;
1644                                 }
1645
1646                                 if (name == "InternalsVisibleToAttribute") {
1647                                         if (dt.Namespace != MetadataImporter.CompilerServicesNamespace)
1648                                                 continue;
1649
1650                                         string s = a.ConstructorArguments[0].Value as string;
1651                                         if (s == null)
1652                                                 continue;
1653
1654                                         var an = new AssemblyName (s);
1655                                         if (internals_visible_to == null)
1656                                                 internals_visible_to = new List<AssemblyName> ();
1657
1658                                         internals_visible_to.Add (an);
1659                                         continue;
1660                                 }
1661                         }
1662                 }
1663
1664                 public override string ToString ()
1665                 {
1666                         return FullName;
1667                 }
1668         }
1669
1670         class ImportedMemberDefinition : ImportedDefinition
1671         {
1672                 readonly TypeSpec type;
1673
1674                 public ImportedMemberDefinition (MemberInfo member, TypeSpec type, MetadataImporter importer)
1675                         : base (member, importer)
1676                 {
1677                         this.type = type;
1678                 }
1679
1680                 #region Properties
1681
1682                 public TypeSpec MemberType {
1683                         get {
1684                                 return type;
1685                         }
1686                 }
1687
1688                 #endregion
1689         }
1690
1691         class ImportedParameterMemberDefinition : ImportedMemberDefinition, IParametersMember
1692         {
1693                 readonly AParametersCollection parameters;
1694
1695                 protected ImportedParameterMemberDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1696                         : base (provider, type, importer)
1697                 {
1698                         this.parameters = parameters;
1699                 }
1700
1701                 public ImportedParameterMemberDefinition (PropertyInfo provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1702                         : base (provider, type, importer)
1703                 {
1704                         this.parameters = parameters;
1705                 }
1706
1707                 #region Properties
1708
1709                 public AParametersCollection Parameters {
1710                         get {
1711                                 return parameters;
1712                         }
1713                 }
1714
1715                 #endregion
1716         }
1717
1718         class ImportedMethodDefinition : ImportedParameterMemberDefinition, IMethodDefinition
1719         {
1720                 public ImportedMethodDefinition (MethodBase provider, TypeSpec type, AParametersCollection parameters, MetadataImporter importer)
1721                         : base (provider, type, parameters, importer)
1722                 {
1723                 }
1724
1725                 MethodBase IMethodDefinition.Metadata {
1726                         get {
1727                                 return (MethodBase) provider;
1728                         }
1729                 }
1730         }
1731
1732         class ImportedGenericMethodDefinition : ImportedMethodDefinition, IGenericMethodDefinition
1733         {
1734                 readonly TypeParameterSpec[] tparams;
1735
1736                 public ImportedGenericMethodDefinition (MethodInfo provider, TypeSpec type, AParametersCollection parameters, TypeParameterSpec[] tparams, MetadataImporter importer)
1737                         : base (provider, type, parameters, importer)
1738                 {
1739                         this.tparams = tparams;
1740                 }
1741
1742                 #region Properties
1743
1744                 public TypeParameterSpec[] TypeParameters {
1745                         get {
1746                                 return tparams;
1747                         }
1748                 }
1749
1750                 public int TypeParametersCount {
1751                         get {
1752                                 return tparams.Length;
1753                         }
1754                 }
1755
1756                 #endregion
1757         }
1758
1759         class ImportedTypeDefinition : ImportedDefinition, ITypeDefinition
1760         {
1761                 TypeParameterSpec[] tparams;
1762                 string name;
1763
1764                 public ImportedTypeDefinition (MetaType type, MetadataImporter importer)
1765                         : base (type, importer)
1766                 {
1767                 }
1768
1769                 #region Properties
1770
1771                 public IAssemblyDefinition DeclaringAssembly {
1772                         get {
1773                                 return importer.GetAssemblyDefinition (provider.Module.Assembly);
1774                         }
1775                 }
1776
1777                 bool ITypeDefinition.IsComImport {
1778                         get {
1779                                 return ((MetaType) provider).IsImport;
1780                         }
1781                 }
1782
1783
1784                 bool ITypeDefinition.IsPartial {
1785                         get {
1786                                 return false;
1787                         }
1788                 }
1789
1790                 bool ITypeDefinition.IsTypeForwarder {
1791                         get {
1792 #if STATIC
1793                                 return ((MetaType) provider).__IsTypeForwarder;
1794 #else
1795                                 return false;
1796 #endif
1797                         }
1798                 }
1799
1800                 public override string Name {
1801                         get {
1802                                 if (name == null) {
1803                                         name = base.Name;
1804                                         if (tparams != null) {
1805                                                 int arity_start = name.IndexOf ('`');
1806                                                 if (arity_start > 0)
1807                                                         name = name.Substring (0, arity_start);
1808                                         }
1809                                 }
1810
1811                                 return name;
1812                         }
1813                 }
1814
1815                 public string Namespace {
1816                         get {
1817                                 return ((MetaType) provider).Namespace;
1818                         }
1819                 }
1820
1821                 public int TypeParametersCount {
1822                         get {
1823                                 return tparams == null ? 0 : tparams.Length;
1824                         }
1825                 }
1826
1827                 public TypeParameterSpec[] TypeParameters {
1828                         get {
1829                                 return tparams;
1830                         }
1831                         set {
1832                                 tparams = value;
1833                         }
1834                 }
1835
1836                 #endregion
1837
1838                 public void DefineInterfaces (TypeSpec spec)
1839                 {
1840                         var type = (MetaType) provider;
1841                         MetaType[] ifaces;
1842 #if STATIC
1843                         ifaces = type.__GetDeclaredInterfaces ();
1844                         if (ifaces.Length != 0) {
1845                                 foreach (var iface in ifaces) {
1846                                         var it = importer.CreateType (iface);
1847                                         if (it == null)
1848                                                 continue;
1849
1850                                         spec.AddInterfaceDefined (it);
1851
1852                                         // Unfortunately not all languages expand inherited interfaces
1853                                         var bifaces = it.Interfaces;
1854                                         if (bifaces != null) {
1855                                                 foreach (var biface in bifaces) {
1856                                                         spec.AddInterfaceDefined (biface);
1857                                                 }
1858                                         }
1859                                 }
1860                         }
1861                         
1862                         //
1863                         // It's impossible to get declared interfaces only using System.Reflection
1864                         // hence we need to mimic the behavior with ikvm-reflection too to keep
1865                         // our type look-up logic same
1866                         //
1867                         if (spec.BaseType != null) {
1868                                 var bifaces = spec.BaseType.Interfaces;
1869                                 if (bifaces != null) {
1870                                         //
1871                                         // Before adding base class interfaces close defined interfaces
1872                                         // on type parameter
1873                                         //
1874                                         var tp = spec as TypeParameterSpec;
1875                                         if (tp != null && tp.InterfacesDefined == null) {
1876                                                 tp.InterfacesDefined = TypeSpec.EmptyTypes;
1877                                         }
1878
1879                                         foreach (var iface in bifaces)
1880                                                 spec.AddInterfaceDefined (iface);
1881                                 }
1882                         }
1883 #else
1884                         ifaces = type.GetInterfaces ();
1885
1886                         if (ifaces.Length > 0) {
1887                                 foreach (var iface in ifaces) {
1888                                         spec.AddInterface (importer.CreateType (iface));
1889                                 }
1890                         }
1891 #endif
1892
1893                 }
1894
1895                 public static void Error_MissingDependency (IMemberContext ctx, List<MissingTypeSpecReference> missing, Location loc)
1896                 {
1897                         // 
1898                         // Report details about missing type and most likely cause of the problem.
1899                         // csc reports 1683, 1684 as warnings but we report them only when used
1900                         // or referenced from the user core in which case compilation error has to
1901                         // be reported because compiler cannot continue anyway
1902                         //
1903
1904                         var report = ctx.Module.Compiler.Report;
1905
1906                         for (int i = 0; i < missing.Count; ++i) {
1907                                 var t = missing [i].Type;
1908
1909                                 //
1910                                 // Report missing types only once
1911                                 //
1912                                 if (report.Printer.MissingTypeReported (t.MemberDefinition))
1913                                         continue;
1914
1915                                 string name = t.GetSignatureForError ();
1916
1917                                 var caller = missing[i].Caller;
1918                                 if (caller.Kind != MemberKind.MissingType)
1919                                         report.SymbolRelatedToPreviousError (caller);
1920
1921                                 if (t.MemberDefinition.DeclaringAssembly == ctx.Module.DeclaringAssembly) {
1922                                         report.Error (1683, loc,
1923                                                 "Reference to type `{0}' claims it is defined in this assembly, but it is not defined in source or any added modules",
1924                                                 name);
1925                                 } else if (t.MemberDefinition.DeclaringAssembly.IsMissing) {
1926                                         if (t.MemberDefinition.IsTypeForwarder) {
1927                                                 report.Error (1070, loc,
1928                                                         "The type `{0}' has been forwarded to an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
1929                                                         name, t.MemberDefinition.DeclaringAssembly.FullName);
1930                                         } else {
1931                                                 report.Error (12, loc,
1932                                                         "The type `{0}' is defined in an assembly that is not referenced. Consider adding a reference to assembly `{1}'",
1933                                                         name, t.MemberDefinition.DeclaringAssembly.FullName);
1934                                         }
1935                                 } else {
1936                                         report.Error (1684, loc,
1937                                                 "Reference to type `{0}' claims it is defined assembly `{1}', but it could not be found",
1938                                                 name, t.MemberDefinition.DeclaringAssembly.FullName);
1939                                 }
1940                         }
1941                 }
1942
1943                 public TypeSpec GetAttributeCoClass ()
1944                 {
1945                         if (cattrs == null)
1946                                 ReadAttributes ();
1947
1948                         return cattrs.CoClass;
1949                 }
1950
1951                 public string GetAttributeDefaultMember ()
1952                 {
1953                         if (cattrs == null)
1954                                 ReadAttributes ();
1955
1956                         return cattrs.DefaultIndexerName;
1957                 }
1958
1959                 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
1960                 {
1961                         if (cattrs == null)
1962                                 ReadAttributes ();
1963
1964                         return cattrs.AttributeUsage;
1965                 }
1966
1967                 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
1968                 {
1969                         var a = importer.GetAssemblyDefinition (provider.Module.Assembly);
1970                         return a == assembly || a.IsFriendAssemblyTo (assembly);
1971                 }
1972
1973                 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
1974                 {
1975                         //
1976                         // Not interested in members of nested private types unless the importer needs them
1977                         //
1978                         if (declaringType.IsPrivate && importer.IgnorePrivateMembers) {
1979                                 cache = MemberCache.Empty;
1980                                 return;
1981                         }
1982
1983                         var loading_type = (MetaType) provider;
1984                         const BindingFlags all_members = BindingFlags.DeclaredOnly |
1985                                 BindingFlags.Static | BindingFlags.Instance |
1986                                 BindingFlags.Public | BindingFlags.NonPublic;
1987
1988                         const MethodAttributes explicit_impl = MethodAttributes.NewSlot |
1989                                         MethodAttributes.Virtual | MethodAttributes.HideBySig |
1990                                         MethodAttributes.Final;
1991
1992                         Dictionary<MethodBase, MethodSpec> possible_accessors = null;
1993                         List<EventSpec> imported_events = null;
1994                         EventSpec event_spec;
1995                         MemberSpec imported;
1996                         MethodInfo m;
1997                         MemberInfo[] all;
1998                         try {
1999                                 all = loading_type.GetMembers (all_members);
2000                         } catch (Exception e) {
2001                                 throw new InternalErrorException (e, "Could not import type `{0}' from `{1}'",
2002                                         declaringType.GetSignatureForError (), declaringType.MemberDefinition.DeclaringAssembly.FullName);
2003                         }
2004
2005                         if (cache == null) {
2006                                 cache = new MemberCache (all.Length);
2007
2008                                 //
2009                                 // Do the types first as they can be referenced by the members before
2010                                 // they are found or inflated
2011                                 //
2012                                 foreach (var member in all) {
2013                                         if (member.MemberType != MemberTypes.NestedType)
2014                                                 continue;
2015
2016                                         var t = (MetaType) member;
2017
2018                                         // Ignore compiler generated types, mostly lambda containers
2019                                         if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
2020                                                 continue;
2021
2022                                         try {
2023                                                 imported = importer.CreateNestedType (t, declaringType);
2024                                         } catch (Exception e) {
2025                                                 throw new InternalErrorException (e, "Could not import nested type `{0}' from `{1}'",
2026                                                         t.FullName, declaringType.MemberDefinition.DeclaringAssembly.FullName);
2027                                         }
2028
2029                                         cache.AddMemberImported (imported);
2030                                 }
2031
2032                                 foreach (var member in all) {
2033                                         if (member.MemberType != MemberTypes.NestedType)
2034                                                 continue;
2035
2036                                         var t = (MetaType) member;
2037
2038                                         if ((t.Attributes & TypeAttributes.VisibilityMask) == TypeAttributes.NestedPrivate && importer.IgnorePrivateMembers)
2039                                                 continue;
2040
2041                                         importer.ImportTypeBase (t);
2042                                 }
2043                         }
2044
2045                         //
2046                         // Load base interfaces first to minic behaviour of compiled members
2047                         //
2048                         if (declaringType.IsInterface && declaringType.Interfaces != null) {
2049                                 foreach (var iface in declaringType.Interfaces) {
2050                                         cache.AddInterface (iface);
2051                                 }
2052                         }
2053
2054                         if (!onlyTypes) {
2055                                 //
2056                                 // The logic here requires methods to be returned first which seems to work for both Mono and .NET
2057                                 //
2058                                 foreach (var member in all) {
2059                                         switch (member.MemberType) {
2060                                         case MemberTypes.Constructor:
2061                                                 if (declaringType.IsInterface)
2062                                                         continue;
2063
2064                                                 goto case MemberTypes.Method;
2065                                         case MemberTypes.Method:
2066                                                 MethodBase mb = (MethodBase) member;
2067                                                 var attrs = mb.Attributes;
2068
2069                                                 if ((attrs & MethodAttributes.MemberAccessMask) == MethodAttributes.Private) {
2070                                                         if (importer.IgnorePrivateMembers)
2071                                                                 continue;
2072
2073                                                         // Ignore explicitly implemented members
2074                                                         if ((attrs & explicit_impl) == explicit_impl)
2075                                                                 continue;
2076
2077                                                         // Ignore compiler generated methods
2078                                                         if (MetadataImporter.HasAttribute (CustomAttributeData.GetCustomAttributes (mb), "CompilerGeneratedAttribute", MetadataImporter.CompilerServicesNamespace))
2079                                                                 continue;
2080                                                 }
2081
2082                                                 imported = importer.CreateMethod (mb, declaringType);
2083                                                 if (imported.Kind == MemberKind.Method && !imported.IsGeneric) {
2084                                                         if (possible_accessors == null)
2085                                                                 possible_accessors = new Dictionary<MethodBase, MethodSpec> (ReferenceEquality<MethodBase>.Default);
2086
2087                                                         // There are no metadata rules for accessors, we have to consider any method as possible candidate
2088                                                         possible_accessors.Add (mb, (MethodSpec) imported);
2089                                                 }
2090
2091                                                 break;
2092                                         case MemberTypes.Property:
2093                                                 if (possible_accessors == null)
2094                                                         continue;
2095
2096                                                 var p = (PropertyInfo) member;
2097                                                 //
2098                                                 // Links possible accessors with property
2099                                                 //
2100                                                 MethodSpec get, set;
2101                                                 m = p.GetGetMethod (true);
2102                                                 if (m == null || !possible_accessors.TryGetValue (m, out get))
2103                                                         get = null;
2104
2105                                                 m = p.GetSetMethod (true);
2106                                                 if (m == null || !possible_accessors.TryGetValue (m, out set))
2107                                                         set = null;
2108
2109                                                 // No accessors registered (e.g. explicit implementation)
2110                                                 if (get == null && set == null)
2111                                                         continue;
2112
2113                                                 try {
2114                                                         imported = importer.CreateProperty (p, declaringType, get, set);
2115                                                 } catch (Exception ex) {
2116                                                         throw new InternalErrorException (ex, "Could not import property `{0}' inside `{1}'",
2117                                                                 p.Name, declaringType.GetSignatureForError ());
2118                                                 }
2119
2120                                                 if (imported == null)
2121                                                         continue;
2122
2123                                                 break;
2124                                         case MemberTypes.Event:
2125                                                 if (possible_accessors == null)
2126                                                         continue;
2127
2128                                                 var e = (EventInfo) member;
2129                                                 //
2130                                                 // Links accessors with event
2131                                                 //
2132                                                 MethodSpec add, remove;
2133                                                 m = e.GetAddMethod (true);
2134                                                 if (m == null || !possible_accessors.TryGetValue (m, out add))
2135                                                         add = null;
2136
2137                                                 m = e.GetRemoveMethod (true);
2138                                                 if (m == null || !possible_accessors.TryGetValue (m, out remove))
2139                                                         remove = null;
2140
2141                                                 // Both accessors are required
2142                                                 if (add == null || remove == null)
2143                                                         continue;
2144
2145                                                 event_spec = importer.CreateEvent (e, declaringType, add, remove);
2146                                                 if (!importer.IgnorePrivateMembers) {
2147                                                         if (imported_events == null)
2148                                                                 imported_events = new List<EventSpec> ();
2149
2150                                                         imported_events.Add (event_spec);
2151                                                 }
2152
2153                                                 imported = event_spec;
2154                                                 break;
2155                                         case MemberTypes.Field:
2156                                                 var fi = (FieldInfo) member;
2157
2158                                                 imported = importer.CreateField (fi, declaringType);
2159                                                 if (imported == null)
2160                                                         continue;
2161
2162                                                 //
2163                                                 // For dynamic binder event has to be fully restored to allow operations
2164                                                 // within the type container to work correctly
2165                                                 //
2166                                                 if (imported_events != null) {
2167                                                         // The backing event field should be private but it may not
2168                                                         int i;
2169                                                         for (i = 0; i < imported_events.Count; ++i) {
2170                                                                 var ev = imported_events[i];
2171                                                                 if (ev.Name == fi.Name) {
2172                                                                         ev.BackingField = (FieldSpec) imported;
2173                                                                         imported_events.RemoveAt (i);
2174                                                                         i = -1;
2175                                                                         break;
2176                                                                 }
2177                                                         }
2178
2179                                                         if (i < 0)
2180                                                                 continue;
2181                                                 }
2182
2183                                                 break;
2184                                         case MemberTypes.NestedType:
2185                                                 // Already in the cache from the first pass
2186                                                 continue;
2187                                         default:
2188                                                 throw new NotImplementedException (member.ToString ());
2189                                         }
2190
2191                                         if (imported.IsStatic && declaringType.IsInterface)
2192                                                 continue;
2193
2194                                         cache.AddMemberImported (imported);
2195                                 }
2196                         }
2197                 }
2198         }
2199
2200         class ImportedTypeParameterDefinition : ImportedDefinition, ITypeDefinition
2201         {
2202                 public ImportedTypeParameterDefinition (MetaType type, MetadataImporter importer)
2203                         : base (type, importer)
2204                 {
2205                 }
2206
2207                 #region Properties
2208
2209                 public IAssemblyDefinition DeclaringAssembly {
2210                         get {
2211                                 throw new NotImplementedException ();
2212                         }
2213                 }
2214
2215                 bool ITypeDefinition.IsComImport {
2216                         get {
2217                                 return false;
2218                         }
2219                 }
2220
2221                 bool ITypeDefinition.IsPartial {
2222                         get {
2223                                 return false;
2224                         }
2225                 }
2226
2227                 bool ITypeDefinition.IsTypeForwarder {
2228                         get {
2229                                 return false;
2230                         }
2231                 }
2232
2233                 public string Namespace {
2234                         get {
2235                                 return null;
2236                         }
2237                 }
2238
2239                 public int TypeParametersCount {
2240                         get {
2241                                 return 0;
2242                         }
2243                 }
2244
2245                 public TypeParameterSpec[] TypeParameters {
2246                         get {
2247                                 return null;
2248                         }
2249                 }
2250
2251                 #endregion
2252
2253                 public TypeSpec GetAttributeCoClass ()
2254                 {
2255                         return null;
2256                 }
2257
2258                 public string GetAttributeDefaultMember ()
2259                 {
2260                         throw new NotSupportedException ();
2261                 }
2262
2263                 public AttributeUsageAttribute GetAttributeUsage (PredefinedAttribute pa)
2264                 {
2265                         throw new NotSupportedException ();
2266                 }
2267
2268                 bool ITypeDefinition.IsInternalAsPublic (IAssemblyDefinition assembly)
2269                 {
2270                         throw new NotImplementedException ();
2271                 }
2272
2273                 public void LoadMembers (TypeSpec declaringType, bool onlyTypes, ref MemberCache cache)
2274                 {
2275                         throw new NotImplementedException ();
2276                 }
2277         }
2278 }