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