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