e000540abe88fc86ae37238ed535b93b31c3b001
[mono.git] / mcs / mcs / typemanager.cs
1 //
2 // typemanager.cs: C# type manager
3 //
4 // Author: Miguel de Icaza (miguel@gnu.org)
5 //         Ravi Pratap     (ravi@ximian.com)
6 //         Marek Safar     (marek.safar@seznam.cz)
7 //
8 // Dual licensed under the terms of the MIT X11 or GNU GPL
9 //
10 // Copyright 2001-2003 Ximian, Inc (http://www.ximian.com)
11 // Copyright 2003-2008 Novell, Inc.
12 //
13
14 //
15 // We will eventually remove the SIMPLE_SPEEDUP, and should never change 
16 // the behavior of the compilation.  This can be removed if we rework
17 // the code to get a list of namespaces available.
18 //
19 #define SIMPLE_SPEEDUP
20
21 using System;
22 using System.IO;
23 using System.Globalization;
24 using System.Collections;
25 using System.Reflection;
26 using System.Reflection.Emit;
27 using System.Text;
28 using System.Runtime.CompilerServices;
29 using System.Diagnostics;
30
31 namespace Mono.CSharp {
32
33 #if GMCS_SOURCE
34         partial
35 #endif
36         class TypeManager {
37         //
38         // A list of core types that the compiler requires or uses
39         //
40         static public Type object_type;
41         static public Type value_type;
42         static public Type string_type;
43         static public Type int32_type;
44         static public Type uint32_type;
45         static public Type int64_type;
46         static public Type uint64_type;
47         static public Type float_type;
48         static public Type double_type;
49         static public Type char_type;
50         static public Type char_ptr_type;
51         static public Type short_type;
52         static public Type decimal_type;
53         static public Type bool_type;
54         static public Type sbyte_type;
55         static public Type byte_type;
56         static public Type ushort_type;
57         static public Type enum_type;
58         static public Type delegate_type;
59         static public Type multicast_delegate_type;
60         static public Type void_type;
61         static public Type null_type;
62         static public Type array_type;
63         static public Type runtime_handle_type;
64         static public Type type_type;
65         static public Type ienumerator_type;
66         static public Type ienumerable_type;
67         static public Type idisposable_type;
68         static public Type default_member_type;
69         static public Type iasyncresult_type;
70         static public Type asynccallback_type;
71         static public Type intptr_type;
72         static public Type uintptr_type;
73         static public Type runtime_field_handle_type;
74         static public Type runtime_argument_handle_type;
75         static public Type attribute_type;
76         static public Type attribute_usage_type;
77         static public Type decimal_constant_attribute_type;
78         static public Type dllimport_type;
79         static public Type methodimpl_attr_type;
80 #if !NET_2_0
81         static public Type marshal_as_attr_type;
82 #endif
83         static public Type param_array_type;
84         static public Type void_ptr_type;
85         static public Type indexer_name_type;
86         static public Type exception_type;
87         static public Type obsolete_attribute_type;
88         static public Type conditional_attribute_type;
89         static public Type in_attribute_type;
90         static public Type out_attribute_type;
91         static public Type extension_attribute_type;
92         static public Type default_parameter_value_attribute_type;
93
94         static public Type anonymous_method_type;
95         static public Type cls_compliant_attribute_type;
96         static public Type typed_reference_type;
97         static public Type arg_iterator_type;
98         static public Type mbr_type;
99         static public Type struct_layout_attribute_type;
100         static public Type field_offset_attribute_type;
101         static public Type security_attr_type;
102         static public Type required_attr_type;
103         static public Type guid_attr_type;
104         static public Type assembly_culture_attribute_type;
105         static public Type assembly_version_attribute_type;
106         static public Type coclass_attr_type;
107         static public Type comimport_attr_type;
108         public static Type runtime_helpers_type;
109         public static Type internals_visible_attr_type;
110
111         // 
112         // C# 2.0
113         //
114         static internal Type fixed_buffer_attr_type;
115         static internal Type default_charset_type;
116         static internal Type type_forwarder_attr_type;
117         static internal Type isvolatile_type;
118         static public Type generic_ilist_type;
119         static public Type generic_icollection_type;
120         static public Type generic_ienumerator_type;
121         static public Type generic_ienumerable_type;
122         static public Type generic_nullable_type;
123
124         //
125         // C# 3.0
126         //
127         static internal Type expression_type;
128         public static Type parameter_expression_type;
129
130         // 
131         // Expressions representing the internal types.  Used during declaration
132         // definition.
133         //
134         static public TypeExpr system_object_expr, system_string_expr; 
135         static public TypeExpr system_boolean_expr, system_decimal_expr;
136         static public TypeExpr system_single_expr, system_double_expr;
137         static public TypeExpr system_sbyte_expr, system_byte_expr;
138         static public TypeExpr system_int16_expr, system_uint16_expr;
139         static public TypeExpr system_int32_expr, system_uint32_expr;
140         static public TypeExpr system_int64_expr, system_uint64_expr;
141         static public TypeExpr system_char_expr, system_void_expr;
142         static public TypeExpr system_valuetype_expr;
143         static public TypeExpr system_intptr_expr;
144         public static TypeExpr expression_type_expr;
145
146
147         //
148         // These methods are called by code generated by the compiler
149         //
150         static public FieldInfo string_empty;
151         static public MethodInfo system_type_get_type_from_handle;
152         static public MethodInfo bool_movenext_void;
153         static public MethodInfo void_dispose_void;
154         static public MethodInfo void_monitor_enter_object;
155         static public MethodInfo void_monitor_exit_object;
156         static public MethodInfo void_initializearray_array_fieldhandle;
157         static public MethodInfo delegate_combine_delegate_delegate;
158         static public MethodInfo delegate_remove_delegate_delegate;
159         static public MethodInfo int_get_offset_to_string_data;
160         static public MethodInfo int_interlocked_compare_exchange;
161         static public PropertyInfo ienumerator_getcurrent;
162         public static MethodInfo methodbase_get_type_from_handle;
163         public static MethodInfo methodbase_get_type_from_handle_generic;
164         public static MethodInfo fieldinfo_get_field_from_handle;
165         static public MethodInfo activator_create_instance;
166         
167         //
168         // The attribute constructors.
169         //
170         static public ConstructorInfo void_decimal_ctor_five_args;
171         static public ConstructorInfo void_decimal_ctor_int_arg;
172         static public ConstructorInfo default_member_ctor;
173         static public ConstructorInfo decimal_constant_attribute_ctor;
174         static internal ConstructorInfo struct_layout_attribute_ctor;
175         static public ConstructorInfo field_offset_attribute_ctor;
176         public static ConstructorInfo invalid_operation_exception_ctor;
177
178         static public CustomAttributeBuilder param_array_attr;
179         static CustomAttributeBuilder compiler_generated_attr;
180         static CustomAttributeBuilder debugger_hidden_attr;
181
182         // C# 2.0
183         static internal ConstructorInfo fixed_buffer_attr_ctor;
184
185         // C# 3.0
186         static internal CustomAttributeBuilder extension_attribute_attr;
187
188         static PtrHashtable builder_to_declspace;
189
190         static PtrHashtable builder_to_member_cache;
191
192         // <remarks>
193         //   Tracks the interfaces implemented by typebuilders.  We only
194         //   enter those who do implement or or more interfaces
195         // </remarks>
196         static PtrHashtable builder_to_ifaces;
197
198         // <remarks>
199         //   Maps a MethodBase to its ParameterData (either InternalParameters or ReflectionParameters)
200         // <remarks>
201         static Hashtable method_params;
202
203         // <remarks>
204         //  A hash table from override methods to their base virtual method.
205         // <remarks>
206         static Hashtable method_overrides;
207
208         // <remarks>
209         //  Keeps track of methods
210         // </remarks>
211
212         static Hashtable builder_to_method;
213
214         // <remarks>
215         //  Contains all public types from referenced assemblies.
216         //  This member is used only if CLS Compliance verification is required.
217         // </remarks>
218         public static Hashtable AllClsTopLevelTypes;
219
220         static Hashtable fieldbuilders_to_fields;
221         static Hashtable propertybuilder_to_property;
222         static Hashtable fields;
223         static Hashtable events;
224         static PtrHashtable assembly_internals_vis_attrs;
225
226         public static void CleanUp ()
227         {
228                 // Lets get everything clean so that we can collect before generating code
229                 builder_to_declspace = null;
230                 builder_to_member_cache = null;
231                 builder_to_ifaces = null;
232                 builder_to_type_param = null;
233                 method_params = null;
234                 builder_to_method = null;
235                 
236                 fields = null;
237                 events = null;
238                 type_hash = null;
239                 propertybuilder_to_property = null;
240                 assembly_internals_vis_attrs = null;
241
242                 TypeHandle.CleanUp ();
243         }
244
245         //
246         // These are expressions that represent some of the internal data types, used
247         // elsewhere
248         //
249         static void InitExpressionTypes ()
250         {
251                 system_object_expr  = new TypeLookupExpression ("System.Object");
252                 system_string_expr  = new TypeLookupExpression ("System.String");
253                 system_boolean_expr = new TypeLookupExpression ("System.Boolean");
254                 system_decimal_expr = new TypeLookupExpression ("System.Decimal");
255                 system_single_expr  = new TypeLookupExpression ("System.Single");
256                 system_double_expr  = new TypeLookupExpression ("System.Double");
257                 system_sbyte_expr   = new TypeLookupExpression ("System.SByte");
258                 system_byte_expr    = new TypeLookupExpression ("System.Byte");
259                 system_int16_expr   = new TypeLookupExpression ("System.Int16");
260                 system_uint16_expr  = new TypeLookupExpression ("System.UInt16");
261                 system_int32_expr   = new TypeLookupExpression ("System.Int32");
262                 system_uint32_expr  = new TypeLookupExpression ("System.UInt32");
263                 system_int64_expr   = new TypeLookupExpression ("System.Int64");
264                 system_uint64_expr  = new TypeLookupExpression ("System.UInt64");
265                 system_char_expr    = new TypeLookupExpression ("System.Char");
266                 system_void_expr    = new TypeLookupExpression ("System.Void");
267                 system_valuetype_expr  = new TypeLookupExpression ("System.ValueType");
268                 system_intptr_expr  = new TypeLookupExpression ("System.IntPtr");
269         }
270
271         static TypeManager ()
272         {
273                 Reset ();
274
275                 InitExpressionTypes ();
276         }
277
278         static public void Reset ()
279         {
280                 builder_to_declspace = new PtrHashtable ();
281                 builder_to_member_cache = new PtrHashtable ();
282                 builder_to_method = new PtrHashtable ();
283                 builder_to_type_param = new PtrHashtable ();
284                 method_params = new PtrHashtable ();
285                 method_overrides = new PtrHashtable ();
286                 builder_to_ifaces = new PtrHashtable ();
287                 
288                 fieldbuilders_to_fields = new Hashtable ();
289                 propertybuilder_to_property = new Hashtable ();
290                 fields = new Hashtable ();
291                 type_hash = new DoubleHash ();
292                 assembly_internals_vis_attrs = new PtrHashtable ();
293
294                 // TODO: I am really bored by all this static stuff
295                 system_type_get_type_from_handle =
296                 bool_movenext_void =
297                 void_dispose_void =
298                 void_monitor_enter_object =
299                 void_monitor_exit_object =
300                 void_initializearray_array_fieldhandle =
301                 delegate_combine_delegate_delegate =
302                 delegate_remove_delegate_delegate =
303                 int_get_offset_to_string_data =
304                 int_interlocked_compare_exchange =
305                 methodbase_get_type_from_handle =
306                 methodbase_get_type_from_handle_generic =
307                 fieldinfo_get_field_from_handle =
308                 activator_create_instance = null;
309
310                 ienumerator_getcurrent = null;
311
312                 void_decimal_ctor_five_args =
313                 void_decimal_ctor_int_arg =
314                 default_member_ctor =
315                 decimal_constant_attribute_ctor =
316                 struct_layout_attribute_ctor =
317                 field_offset_attribute_ctor =
318                 invalid_operation_exception_ctor =
319                 fixed_buffer_attr_ctor = null;
320
321                 param_array_attr =
322                 compiler_generated_attr =
323                 extension_attribute_attr = null;
324
325                 isvolatile_type = null;
326                         
327                 // to uncover regressions
328                 AllClsTopLevelTypes = null;
329         }
330
331         public static void AddUserType (DeclSpace ds)
332         {
333                 builder_to_declspace.Add (ds.TypeBuilder, ds);
334         }
335
336         //
337         // This entry point is used by types that we define under the covers
338         // 
339         public static void RegisterBuilder (Type tb, Type [] ifaces)
340         {
341                 if (ifaces != null)
342                         builder_to_ifaces [tb] = ifaces;
343         }       
344
345         public static void AddMethod (MethodBase builder, IMethodData method)
346         {
347                 builder_to_method.Add (builder, method);
348                 method_params.Add (builder, method.ParameterInfo);
349         }
350
351         public static IMethodData GetMethod (MethodBase builder)
352         {
353                 return (IMethodData) builder_to_method [builder];
354         }
355
356         /// <summary>
357         ///   Returns the DeclSpace whose Type is `t' or null if there is no
358         ///   DeclSpace for `t' (ie, the Type comes from a library)
359         /// </summary>
360         public static DeclSpace LookupDeclSpace (Type t)
361         {
362                 return builder_to_declspace [t] as DeclSpace;
363         }
364
365         /// <summary>
366         ///   Returns the TypeContainer whose Type is `t' or null if there is no
367         ///   TypeContainer for `t' (ie, the Type comes from a library)
368         /// </summary>
369         public static TypeContainer LookupTypeContainer (Type t)
370         {
371                 return builder_to_declspace [t] as TypeContainer;
372         }
373
374         public static MemberCache LookupMemberCache (Type t)
375         {
376                 if (t.Module == CodeGen.Module.Builder) {
377                         DeclSpace container = (DeclSpace)builder_to_declspace [t];
378                         if (container != null)
379                                 return container.MemberCache;
380                 }
381
382 #if GMCS_SOURCE
383                 if (t is GenericTypeParameterBuilder) {
384                         TypeParameter container = builder_to_type_param [t] as TypeParameter;
385
386                         if (container != null)
387                                 return container.MemberCache;
388                 }
389 #endif
390
391                 return TypeHandle.GetMemberCache (t);
392         }
393
394         public static MemberCache LookupBaseInterfacesCache (Type t)
395         {
396                 Type [] ifaces = GetInterfaces (t);
397
398                 if (ifaces != null && ifaces.Length == 1)
399                         return LookupMemberCache (ifaces [0]);
400
401                 // TODO: the builder_to_member_cache should be indexed by 'ifaces', not 't'
402                 MemberCache cache = builder_to_member_cache [t] as MemberCache;
403                 if (cache != null)
404                         return cache;
405
406                 cache = new MemberCache (ifaces);
407                 builder_to_member_cache.Add (t, cache);
408                 return cache;
409         }
410
411         public static TypeContainer LookupInterface (Type t)
412         {
413                 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
414                 if ((tc == null) || (tc.Kind != Kind.Interface))
415                         return null;
416
417                 return tc;
418         }
419
420         public static Delegate LookupDelegate (Type t)
421         {
422                 return builder_to_declspace [t] as Delegate;
423         }
424
425         public static Class LookupClass (Type t)
426         {
427                 return (Class) builder_to_declspace [t];
428         }
429
430         //
431         // We use this hash for multiple kinds of constructed types:
432         //
433         //    (T, "&")  Given T, get T &
434         //    (T, "*")  Given T, get T *
435         //    (T, "[]") Given T and a array dimension, get T []
436         //    (T, X)    Given a type T and a simple name X, get the type T+X
437         //
438         // Accessibility tests, if necessary, should be done by the user
439         //
440         static DoubleHash type_hash = new DoubleHash ();
441
442         //
443         // Gets the reference to T version of the Type (T&)
444         //
445         public static Type GetReferenceType (Type t)
446         {
447 #if GMCS_SOURCE
448                 return t.MakeByRefType ();
449 #else
450                 return GetConstructedType (t, "&");
451 #endif
452         }
453
454         //
455         // Gets the pointer to T version of the Type  (T*)
456         //
457         public static Type GetPointerType (Type t)
458         {
459                 return GetConstructedType (t, "*");
460         }
461
462         public static Type GetConstructedType (Type t, string dim)
463         {
464                 object ret = null;
465                 if (type_hash.Lookup (t, dim, out ret))
466                         return (Type) ret;
467
468                 ret = t.Module.GetType (t.ToString () + dim);
469                 if (ret != null) {
470                         type_hash.Insert (t, dim, ret);
471                         return (Type) ret;
472                 }
473
474                 if (dim == "&") {
475                         ret = GetReferenceType (t);
476                         type_hash.Insert (t, dim, ret);
477                         return (Type) ret;
478                 }
479
480 #if GMCS_SOURCE
481                 if (t.IsGenericParameter || t.IsGenericType) {
482                         int pos = 0;
483                         Type result = t;
484                         while ((pos < dim.Length) && (dim [pos] == '[')) {
485                                 pos++;
486
487                                 if (dim [pos] == ']') {
488                                         result = result.MakeArrayType ();
489                                         pos++;
490
491                                         if (pos < dim.Length)
492                                                 continue;
493
494                                         type_hash.Insert (t, dim, result);
495                                         return result;
496                                 }
497
498                                 int rank = 0;
499                                 while (dim [pos] == ',') {
500                                         pos++; rank++;
501                                 }
502
503                                 if ((dim [pos] != ']') || (pos != dim.Length-1))
504                                         break;
505
506                                 result = result.MakeArrayType (rank + 1);
507                                 type_hash.Insert (t, dim, result);
508                                 return result;
509                         }
510                 }
511 #endif
512
513                 type_hash.Insert (t, dim, null);
514                 return null;
515         }
516
517         public static CustomAttributeBuilder GetCompilerGeneratedAttribute (Location loc)
518         {
519                 if (compiler_generated_attr != null)
520                         return compiler_generated_attr;
521
522                 Type t = TypeManager.CoreLookupType (
523                         "System.Runtime.CompilerServices", "CompilerGeneratedAttribute", Kind.Class, true);
524
525                 // TODO: it cannot be null
526                 if (t == null)
527                         return null;
528
529                 compiler_generated_attr = new CustomAttributeBuilder (
530                         GetPredefinedConstructor (t, loc, Type.EmptyTypes), new object[0]);
531
532                 return compiler_generated_attr;
533         }
534
535         public static CustomAttributeBuilder GetDebuggerHiddenAttribute (Location loc)
536         {
537                 if (debugger_hidden_attr != null)
538                         return debugger_hidden_attr;
539
540                 Type t = TypeManager.CoreLookupType (
541                         "System.Diagnostics", "DebuggerHiddenAttribute", Kind.Class, true);
542
543                 // TODO: it cannot be null
544                 if (t == null)
545                         return null;
546
547                 debugger_hidden_attr = new CustomAttributeBuilder (
548                         GetPredefinedConstructor (t, loc, Type.EmptyTypes), new object[0]);
549
550                 return debugger_hidden_attr;
551         }
552
553         public static Type GetNestedType (Type t, string name)
554         {
555                 object ret = null;
556                 if (!type_hash.Lookup (t, name, out ret)) {
557                         ret = t.GetNestedType (name,
558                                BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly);
559                         type_hash.Insert (t, name, ret);
560                 }
561                 return (Type) ret;
562         }
563
564         /// <summary>
565         /// Fills static table with exported types from all referenced assemblies.
566         /// This information is required for CLS Compliance tests.
567         /// </summary>
568         public static void LoadAllImportedTypes ()
569         {
570                 AllClsTopLevelTypes = new Hashtable (1500);
571                 foreach (Assembly a in RootNamespace.Global.Assemblies) {
572                         foreach (Type t in a.GetExportedTypes ()) {
573                                 AllClsTopLevelTypes [t.FullName.ToLower (System.Globalization.CultureInfo.InvariantCulture)] = null;
574                         }
575                 }
576         }
577
578         public static bool NamespaceClash (string name, Location loc)
579         {
580                 if (! RootNamespace.Global.IsNamespace (name))
581                         return false;
582
583                 Report.Error (519, loc, String.Format ("`{0}' clashes with a predefined namespace", name));
584                 return true;
585         }
586
587         /// <summary>
588         ///   Returns the C# name of a type if possible, or the full type name otherwise
589         /// </summary>
590         static public string CSharpName (Type t)
591         {
592                 if (t == null_type)
593                         return "null";
594
595                 if (t == typeof (ArglistParameter))
596                         return "__arglist";
597                         
598                 if (t == typeof (AnonymousMethodBody))
599                         return "anonymous method";
600
601                 return CSharpName (GetFullName (t));
602     }
603
604         static readonly char [] elements = new char [] { '*', '[' };
605
606         public static string CSharpName (string name)
607         {
608                 if (name.Length > 10) {
609                         switch (name) {
610                         case "System.Int32": return "int";
611                         case "System.Int64": return "long";
612                         case "System.String": return "string";
613                         case "System.Boolean": return "bool";
614                         case "System.Void": return "void";
615                         case "System.Object": return "object";
616                         case "System.UInt32": return "uint";
617                         case "System.Int16": return "short";
618                         case "System.UInt16": return "ushort";
619                         case "System.UInt64": return "ulong";
620                         case "System.Single": return "float";
621                         case "System.Double": return "double";
622                         case "System.Decimal": return "decimal";
623                         case "System.Char": return "char";
624                         case "System.Byte": return "byte";
625                         case "System.SByte": return "sbyte";
626                         }
627
628                         int idx = name.IndexOfAny (elements, 10);
629                         if (idx > 0)
630                                 return CSharpName (name.Substring (0, idx)) + name.Substring (idx);
631                 }
632
633                 if (name [0] == AnonymousTypeClass.ClassNamePrefix [0] && name.StartsWith (AnonymousTypeClass.ClassNamePrefix))
634                         return AnonymousTypeClass.SignatureForError;
635
636                 return name.Replace ('+', '.');
637         }
638
639         static public string CSharpName (Type[] types)
640         {
641                 if (types.Length == 0)
642                         return string.Empty;
643
644                 StringBuilder sb = new StringBuilder ();
645                 for (int i = 0; i < types.Length; ++i) {
646                         if (i > 0)
647                                 sb.Append (", ");
648
649                         sb.Append (CSharpName (types [i]));
650                 }
651                 return sb.ToString ();
652         }
653
654         /// <summary>
655         ///  Returns the signature of the method with full namespace classification
656         /// </summary>
657         static public string GetFullNameSignature (MemberInfo mi)
658         {
659                 PropertyInfo pi = mi as PropertyInfo;
660                 if (pi != null) {
661                         MethodBase pmi = pi.GetGetMethod (true);
662                         if (pmi == null)
663                                 pmi = pi.GetSetMethod (true);
664                         if (GetParameterData (pmi).Count > 0)
665                                 mi = pmi;
666                 }
667                 return (mi is MethodBase)
668                         ? CSharpSignature (mi as MethodBase) 
669                         : CSharpName (mi.DeclaringType) + '.' + mi.Name;
670         }
671
672 #if GMCS_SOURCE
673         private static int GetFullName (Type t, StringBuilder sb)
674         {
675                 int pos = 0;
676
677                 if (!t.IsGenericType) {
678                         sb.Append (t.FullName);
679                         return 0;
680                 }
681
682                 if (t.DeclaringType != null) {
683                         pos = GetFullName (t.DeclaringType, sb);
684                         sb.Append ('.');
685                 } else if (t.Namespace != null && t.Namespace.Length != 0) {
686                         sb.Append (t.Namespace);
687                         sb.Append ('.');
688                 }
689                 sb.Append (RemoveGenericArity (t.Name));
690
691                 Type[] this_args = GetTypeArguments (t);
692
693                 if (this_args.Length < pos)
694                         throw new InternalErrorException (
695                                 "Enclosing class " + t.DeclaringType + " has more type arguments than " + t);
696                 if (this_args.Length == pos)
697                         return pos;
698
699                 sb.Append ('<');
700                 for (;;) {
701                         sb.Append (CSharpName (this_args [pos++]));
702                         if (pos == this_args.Length)
703                                 break;
704                         sb.Append (',');
705                 }
706                 sb.Append ('>');
707                 return pos;
708         }
709
710         static string GetFullName (Type t)
711         {
712                 if (t.IsArray) {
713                         string dimension = t.Name.Substring (t.Name.LastIndexOf ('['));
714                         return GetFullName (t.GetElementType ()) + dimension;
715                 }
716
717                 if (IsNullableType (t) && !t.IsGenericTypeDefinition) {
718                         t = GetTypeArguments (t)[0];
719                         return CSharpName (t) + "?";
720                 }
721
722                 if (t.IsGenericParameter)
723                         return t.Name;
724                 if (!t.IsGenericType)
725                         return t.FullName;
726
727                 StringBuilder sb = new StringBuilder ();
728                 int pos = GetFullName (t, sb);
729                 if (pos <= 0)
730                         throw new InternalErrorException ("Generic Type " + t + " doesn't have type arguments");
731                 return sb.ToString ();
732         }
733 #else
734         public static string GetFullName (Type t)
735         {
736                 return t.FullName;
737         }
738 #endif
739
740         public static string RemoveGenericArity (string from)
741         {
742                 int i = from.IndexOf ('`');
743                 if (i > 0)
744                         return from.Substring (0, i);
745                 return from;
746         }
747
748         /// <summary>
749         /// When we need to report accessors as well
750         /// </summary>
751         static public string CSharpSignature (MethodBase mb)
752         {
753                 return CSharpSignature (mb, false);
754         }
755
756         /// <summary>
757         ///   Returns the signature of the method
758         /// </summary>
759         static public string CSharpSignature (MethodBase mb, bool show_accessor)
760         {
761                 StringBuilder sig = new StringBuilder (CSharpName (mb.DeclaringType));
762                 sig.Append ('.');
763
764                 AParametersCollection iparams = GetParameterData (mb);
765                 string parameters = iparams.GetSignatureForError ();
766                 int accessor_end = 0;
767
768                 if (!mb.IsConstructor && TypeManager.IsSpecialMethod (mb)) {
769                         string op_name = Operator.GetName (mb.Name);
770                         if (op_name != null) {
771                                 sig.Append ("operator ");
772                                 sig.Append (op_name);
773                                 sig.Append (parameters);
774                                 return sig.ToString ();
775                         }
776
777                         bool is_getter = mb.Name.StartsWith ("get_");
778                         bool is_setter = mb.Name.StartsWith ("set_");
779                         if (is_getter || is_setter || mb.Name.StartsWith ("add_")) {
780                                 accessor_end = 3;
781                         } else if (mb.Name.StartsWith ("remove_")) {
782                                 accessor_end = 6;
783                         }
784
785                         // Is indexer
786                         if (iparams.Count > (is_getter ? 0 : 1)) {
787                                 sig.Append ("this[");
788                                 if (is_getter)
789                                         sig.Append (parameters.Substring (1, parameters.Length - 2));
790                                 else
791                                         sig.Append (parameters.Substring (1, parameters.LastIndexOf (',') - 1));
792                                 sig.Append (']');
793                         } else {
794                                 sig.Append (mb.Name.Substring (accessor_end + 1));
795                         }
796                 } else {
797                         if (mb.Name == ".ctor")
798                                 sig.Append (RemoveGenericArity (mb.DeclaringType.Name));
799                         else {
800                                 sig.Append (mb.Name);
801
802 #if GMCS_SOURCE
803                                 if (TypeManager.IsGenericMethod (mb)) {
804                                         Type[] args = mb.GetGenericArguments ();
805                                         sig.Append ('<');
806                                         for (int i = 0; i < args.Length; i++) {
807                                                 if (i > 0)
808                                                         sig.Append (',');
809                                                 sig.Append (CSharpName (args [i]));
810                                         }
811                                         sig.Append ('>');
812                                 }
813 #endif
814                         }
815
816                         sig.Append (parameters);
817                 }
818
819                 if (show_accessor && accessor_end > 0) {
820                         sig.Append ('.');
821                         sig.Append (mb.Name.Substring (0, accessor_end));
822                 }
823
824                 return sig.ToString ();
825         }
826
827         public static string GetMethodName (MethodInfo m)
828         {
829 #if GMCS_SOURCE
830                 if (!IsGenericMethodDefinition (m) && !IsGenericMethod (m))
831                         return m.Name;
832
833                 return MemberName.MakeName (m.Name, m.GetGenericArguments ().Length);
834 #else
835                 return m.Name;
836 #endif
837         }
838
839         static public string CSharpSignature (EventInfo ei)
840         {
841                 return CSharpName (ei.DeclaringType) + "." + ei.Name;
842         }
843
844         //
845         // Looks up a type, and aborts if it is not found.  This is used
846         // by predefined types required by the compiler
847         //
848         public static Type CoreLookupType (string ns_name, string name, Kind type_kind, bool required)
849         {
850                 Expression expr;
851                 if (RootContext.StdLib) {
852                         Namespace ns = RootNamespace.Global.GetNamespace (ns_name, true);
853                         expr = ns.Lookup (RootContext.ToplevelTypes, name, Location.Null);
854                 } else {
855                         if (!required)
856                                 Report.DisableReporting ();
857
858                         TypeLookupExpression tle = new TypeLookupExpression (ns_name + "." + name);
859                         expr = tle.ResolveAsTypeTerminal (RootContext.ToplevelTypes, false);
860
861                         if (!required)
862                                 Report.EnableReporting ();
863                 }
864
865                 if (expr == null) {
866                         if (required) {
867                                 Report.Error (518, "The predefined type `{0}.{1}' is not defined or imported",
868                                         ns_name, name);
869                         }
870                         return null;
871                 }
872
873                 Type t = expr.Type;
874                 if (RootContext.StdLib || t == null || !required)
875                         return t;
876
877                 // TODO: All predefined imported types have to have correct signature
878                 if (t.Module != CodeGen.Module.Builder)
879                         return t;
880
881                 DeclSpace ds = (DeclSpace)RootContext.ToplevelTypes.GetDefinition (t.FullName);
882                 if (ds is Delegate) {
883                         if (type_kind == Kind.Delegate)
884                                 return t;
885                 } else {
886                         TypeContainer tc = (TypeContainer)ds;
887                         if (tc.Kind == type_kind)
888                                 return t;
889                 }
890
891                 Report.Error (520, ds.Location, "The predefined type `{0}.{1}' is not declared correctly",
892                         ns_name, name);
893                 return null;
894         }
895
896         static MemberInfo GetPredefinedMember (Type t, string name, MemberTypes mt, Location loc, params Type [] args)
897         {
898                 const BindingFlags flags = instance_and_static | BindingFlags.Public | BindingFlags.DeclaredOnly;
899
900                 MemberInfo [] members = MemberLookup (null, null, t, mt, flags, name, null);
901                 if (members != null) {
902                         for (int i = 0; i < members.Length; ++i) {
903                                 MemberInfo member = members [i];
904                                 if (mt == MemberTypes.Method || mt == MemberTypes.Constructor) {
905                                         MethodBase mb = member as MethodBase;
906                                         if (mb == null)
907                                                 continue;
908
909                                         AParametersCollection pd = TypeManager.GetParameterData (mb);
910                                         if (IsEqual (pd.Types, args))
911                                                 return member;
912                                 }
913                                 if (mt == MemberTypes.Field) {
914                                         FieldInfo fi = member as FieldInfo;
915                                         if (fi == null)
916                                                 continue;
917
918                                         if (args.Length >= 1 && !IsEqual (TypeToCoreType (fi.FieldType), args [0]))
919                                                 continue;
920
921                                         return member;
922                                 }
923
924                                 if (mt == MemberTypes.Property) {
925                                         PropertyInfo pi = member as PropertyInfo;
926                                         if (pi == null)
927                                                 continue;
928
929                                         if (args.Length >= 1 && !IsEqual (TypeToCoreType (pi.PropertyType), args [0]))
930                                                 continue;
931
932                                         return member;
933                                 }
934                         }
935                 }
936
937                 string method_args = null;
938                 if (mt == MemberTypes.Method || mt == MemberTypes.Constructor)
939                         method_args = "(" + TypeManager.CSharpName (args) + ")";
940
941                 Report.Error (656, loc, "The compiler required member `{0}.{1}{2}' could not be found or is inaccessible",
942                         TypeManager.CSharpName (t), name, method_args);
943
944                 return null;
945         }
946
947         //
948         // Returns the ConstructorInfo for "args"
949         //
950         public static ConstructorInfo GetPredefinedConstructor (Type t, Location loc, params Type [] args)
951         {
952                 return (ConstructorInfo) GetPredefinedMember (t, ConstructorInfo.ConstructorName, MemberTypes.Constructor, loc, args);
953         }
954
955         //
956         // Returns the MethodInfo for a method named `name' defined
957         // in type `t' which takes arguments of types `args'
958         //
959         public static MethodInfo GetPredefinedMethod (Type t, string name, Location loc, params Type [] args)
960         {
961                 return (MethodInfo)GetPredefinedMember (t, name, MemberTypes.Method, loc, args);
962         }
963
964         public static FieldInfo GetPredefinedField (Type t, string name, Location loc, params Type [] args)
965         {
966                 return (FieldInfo) GetPredefinedMember (t, name, MemberTypes.Field, loc, args);
967         }
968
969         public static PropertyInfo GetPredefinedProperty (Type t, string name, Location loc, params Type [] args)
970         {
971                 return (PropertyInfo) GetPredefinedMember (t, name, MemberTypes.Property, loc, args);
972         }
973
974         /// <remarks>
975         ///   The types have to be initialized after the initial
976         ///   population of the type has happened (for example, to
977         ///   bootstrap the corlib.dll
978         /// </remarks>
979         public static bool InitCoreTypes ()
980         {
981                 object_type   = CoreLookupType ("System", "Object", Kind.Class, true);
982                 system_object_expr.Type = object_type;
983                 value_type    = CoreLookupType ("System", "ValueType", Kind.Class, true);
984                 system_valuetype_expr.Type = value_type;
985                 attribute_type = CoreLookupType ("System", "Attribute", Kind.Class, true);
986
987                 int32_type    = CoreLookupType ("System", "Int32", Kind.Struct, true);
988                 int64_type    = CoreLookupType ("System", "Int64", Kind.Struct, true);
989                 uint32_type   = CoreLookupType ("System", "UInt32", Kind.Struct, true); 
990                 uint64_type   = CoreLookupType ("System", "UInt64", Kind.Struct, true); 
991                 byte_type     = CoreLookupType ("System", "Byte", Kind.Struct, true);
992                 sbyte_type    = CoreLookupType ("System", "SByte", Kind.Struct, true);
993                 short_type    = CoreLookupType ("System", "Int16", Kind.Struct, true);
994                 ushort_type   = CoreLookupType ("System", "UInt16", Kind.Struct, true);
995
996                 ienumerator_type     = CoreLookupType ("System.Collections", "IEnumerator", Kind.Interface, true);
997                 ienumerable_type     = CoreLookupType ("System.Collections", "IEnumerable", Kind.Interface, true);
998                 idisposable_type     = CoreLookupType ("System", "IDisposable", Kind.Interface, true);
999
1000                 // HACK: DefineType immediately resolves iterators (very wrong)
1001                 generic_ienumerator_type = CoreLookupType ("System.Collections.Generic", "IEnumerator`1", Kind.Interface, false);
1002
1003                 char_type     = CoreLookupType ("System", "Char", Kind.Struct, true);
1004                 string_type   = CoreLookupType ("System", "String", Kind.Class, true);
1005                 float_type    = CoreLookupType ("System", "Single", Kind.Struct, true);
1006                 double_type   = CoreLookupType ("System", "Double", Kind.Struct, true);
1007                 decimal_type  = CoreLookupType ("System", "Decimal", Kind.Struct, true);
1008                 bool_type     = CoreLookupType ("System", "Boolean", Kind.Struct, true);
1009                 intptr_type = CoreLookupType ("System", "IntPtr", Kind.Struct, true);
1010                 uintptr_type = CoreLookupType ("System", "UIntPtr", Kind.Struct, true);
1011
1012                 multicast_delegate_type = CoreLookupType ("System", "MulticastDelegate", Kind.Class, true);
1013                 delegate_type           = CoreLookupType ("System", "Delegate", Kind.Class, true);
1014
1015                 enum_type       = CoreLookupType ("System", "Enum", Kind.Class, true);
1016                 array_type      = CoreLookupType ("System", "Array", Kind.Class, true);
1017                 void_type       = CoreLookupType ("System", "Void", Kind.Struct, true);
1018                 type_type       = CoreLookupType ("System", "Type", Kind.Class, true);
1019                 exception_type = CoreLookupType ("System", "Exception", Kind.Class, true);
1020
1021                 runtime_field_handle_type = CoreLookupType ("System", "RuntimeFieldHandle", Kind.Struct, true);
1022                 runtime_handle_type = CoreLookupType ("System", "RuntimeTypeHandle", Kind.Struct, true);
1023
1024                 param_array_type = CoreLookupType ("System", "ParamArrayAttribute", Kind.Class, true);
1025                 out_attribute_type = CoreLookupType ("System.Runtime.InteropServices", "OutAttribute", Kind.Class, true);
1026
1027                 return Report.Errors == 0;
1028         }
1029
1030         //
1031         // Initializes optional core types
1032         //
1033         public static void InitOptionalCoreTypes ()
1034         {
1035                 void_ptr_type = GetPointerType (void_type);
1036                 char_ptr_type = GetPointerType (char_type);
1037
1038                 //
1039                 // Initialize InternalsVisibleTo as the very first optional type. Otherwise we would populate
1040                 // types cache with incorrect accessiblity when any of optional types is internal.
1041                 //
1042                 internals_visible_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "InternalsVisibleToAttribute", Kind.Class, false);
1043
1044                 runtime_argument_handle_type = CoreLookupType ("System", "RuntimeArgumentHandle", Kind.Struct, false);
1045                 asynccallback_type = CoreLookupType ("System", "AsyncCallback", Kind.Delegate, false);
1046                 iasyncresult_type = CoreLookupType ("System", "IAsyncResult", Kind.Interface, false);
1047                 typed_reference_type = CoreLookupType ("System", "TypedReference", Kind.Struct, false);
1048                 arg_iterator_type = CoreLookupType ("System", "ArgIterator", Kind.Struct, false);
1049                 mbr_type = CoreLookupType ("System", "MarshalByRefObject", Kind.Class, false);
1050
1051                 //
1052                 // Optional attributes, used for error reporting only
1053                 //
1054                 obsolete_attribute_type = CoreLookupType ("System", "ObsoleteAttribute", Kind.Class, false);
1055                 if (obsolete_attribute_type != null) {
1056                         Class c = TypeManager.LookupClass (obsolete_attribute_type);
1057                         if (c != null)
1058                                 c.DefineMembers ();
1059                 }
1060
1061                 dllimport_type = CoreLookupType ("System.Runtime.InteropServices", "DllImportAttribute", Kind.Class, false);
1062                 methodimpl_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "MethodImplAttribute", Kind.Class, false);
1063 #if !NET_2_0
1064                 marshal_as_attr_type = CoreLookupType ("System.Runtime.InteropServices", "MarshalAsAttribute", Kind.Class, false);
1065 #endif
1066                 in_attribute_type = CoreLookupType ("System.Runtime.InteropServices", "InAttribute", Kind.Class, false);
1067                 indexer_name_type = CoreLookupType ("System.Runtime.CompilerServices", "IndexerNameAttribute", Kind.Class, false);
1068                 conditional_attribute_type = CoreLookupType ("System.Diagnostics", "ConditionalAttribute", Kind.Class, false);
1069                 cls_compliant_attribute_type = CoreLookupType ("System", "CLSCompliantAttribute", Kind.Class, false);
1070                 security_attr_type = CoreLookupType ("System.Security.Permissions", "SecurityAttribute", Kind.Class, false);
1071                 required_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "RequiredAttributeAttribute", Kind.Class, false);
1072                 guid_attr_type = CoreLookupType ("System.Runtime.InteropServices", "GuidAttribute", Kind.Class, false);
1073                 assembly_culture_attribute_type = CoreLookupType ("System.Reflection", "AssemblyCultureAttribute", Kind.Class, false);
1074                 assembly_version_attribute_type = CoreLookupType ("System.Reflection", "AssemblyVersionAttribute", Kind.Class, false);
1075                 comimport_attr_type = CoreLookupType ("System.Runtime.InteropServices", "ComImportAttribute", Kind.Class, false);
1076                 coclass_attr_type = CoreLookupType ("System.Runtime.InteropServices", "CoClassAttribute", Kind.Class, false);
1077                 attribute_usage_type = CoreLookupType ("System", "AttributeUsageAttribute", Kind.Class, false);
1078                 default_parameter_value_attribute_type = CoreLookupType ("System.Runtime.InteropServices", "DefaultParameterValueAttribute", Kind.Class, false);
1079
1080                 // New in .NET 2.0
1081                 default_charset_type = CoreLookupType ("System.Runtime.InteropServices", "DefaultCharSetAttribute", Kind.Class, false);
1082                 type_forwarder_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "TypeForwardedToAttribute", Kind.Class, false);
1083                 generic_ilist_type = CoreLookupType ("System.Collections.Generic", "IList`1", Kind.Interface, false);
1084                 generic_icollection_type = CoreLookupType ("System.Collections.Generic", "ICollection`1", Kind.Interface, false);
1085                 generic_ienumerable_type = CoreLookupType ("System.Collections.Generic", "IEnumerable`1", Kind.Interface, false);
1086                 generic_nullable_type = CoreLookupType ("System", "Nullable`1", Kind.Struct, false);
1087
1088                 //
1089                 // Optional types which are used as types and for member lookup
1090                 //
1091                 default_member_type = CoreLookupType ("System.Reflection", "DefaultMemberAttribute", Kind.Class, false);
1092                 runtime_helpers_type = CoreLookupType ("System.Runtime.CompilerServices", "RuntimeHelpers", Kind.Class, false);
1093                 decimal_constant_attribute_type = CoreLookupType ("System.Runtime.CompilerServices", "DecimalConstantAttribute", Kind.Class, false);
1094                 struct_layout_attribute_type = CoreLookupType ("System.Runtime.InteropServices", "StructLayoutAttribute", Kind.Class, false);
1095                 field_offset_attribute_type = CoreLookupType ("System.Runtime.InteropServices", "FieldOffsetAttribute", Kind.Class, false);
1096
1097                 // New in .NET 2.0
1098                 fixed_buffer_attr_type = CoreLookupType ("System.Runtime.CompilerServices", "FixedBufferAttribute", Kind.Class, false);
1099
1100                 // New in .NET 3.5
1101                 extension_attribute_type = CoreLookupType ("System.Runtime.CompilerServices", "ExtensionAttribute", Kind.Class, false);
1102                 expression_type = CoreLookupType ("System.Linq.Expressions", "Expression`1", Kind.Class, false);
1103
1104                 if (!RootContext.StdLib) {
1105                         //
1106                         // HACK: When building Mono corlib mcs uses loaded mscorlib which
1107                         // has different predefined types and this method sets mscorlib types
1108                         // to be same to avoid any type check errors.
1109                         //
1110
1111                         Type type = typeof (Type);
1112                         Type [] system_4_type_arg = { type, type, type, type };
1113                                 
1114                         MethodInfo set_corlib_type_builders = 
1115                                 typeof (System.Reflection.Emit.AssemblyBuilder).GetMethod (
1116                                 "SetCorlibTypeBuilders", BindingFlags.NonPublic | BindingFlags.Instance, null,
1117                                 system_4_type_arg, null);
1118
1119                         if (set_corlib_type_builders != null) {
1120                                 object[] args = new object [4];
1121                                 args [0] = object_type;
1122                                 args [1] = value_type;
1123                                 args [2] = enum_type;
1124                                 args [3] = void_type;
1125                                 
1126                                 set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
1127                         } else {
1128                                 Report.Warning (-26, 3, "The compilation may fail due to missing `{0}.SetCorlibTypeBuilders({1})' method",
1129                                         TypeManager.CSharpName (typeof (System.Reflection.Emit.AssemblyBuilder)),
1130                                         TypeManager.CSharpName (system_4_type_arg));
1131                         }
1132                 }
1133
1134                 system_string_expr.Type = string_type;
1135                 system_boolean_expr.Type = bool_type;
1136                 system_decimal_expr.Type = decimal_type;
1137                 system_single_expr.Type = float_type;
1138                 system_double_expr.Type = double_type;
1139                 system_sbyte_expr.Type = sbyte_type;
1140                 system_byte_expr.Type = byte_type;
1141                 system_int16_expr.Type = short_type;
1142                 system_uint16_expr.Type = ushort_type;
1143                 system_int32_expr.Type = int32_type;
1144                 system_uint32_expr.Type = uint32_type;
1145                 system_int64_expr.Type = int64_type;
1146                 system_uint64_expr.Type = uint64_type;
1147                 system_char_expr.Type = char_type;
1148                 system_void_expr.Type = void_type;
1149
1150                 //
1151                 // These are only used for compare purposes
1152                 //
1153                 anonymous_method_type = typeof (AnonymousMethodBody);
1154                 null_type = typeof (NullLiteral);
1155         }
1156
1157         const BindingFlags instance_and_static = BindingFlags.Static | BindingFlags.Instance;
1158
1159         /// <remarks>
1160         ///   This is the "old", non-cache based FindMembers() function.  We cannot use
1161         ///   the cache here because there is no member name argument.
1162         /// </remarks>
1163         public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1164                                               MemberFilter filter, object criteria)
1165         {
1166 #if MS_COMPATIBLE && GMCS_SOURCE
1167                 if (t.IsGenericType)
1168                         t = t.GetGenericTypeDefinition ();
1169 #endif
1170
1171                 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1172
1173                 //
1174                 // `builder_to_declspace' contains all dynamic types.
1175                 //
1176                 if (decl != null) {
1177                         MemberList list;
1178                         Timer.StartTimer (TimerType.FindMembers);
1179                         list = decl.FindMembers (mt, bf, filter, criteria);
1180                         Timer.StopTimer (TimerType.FindMembers);
1181                         return list;
1182                 }
1183
1184                 //
1185                 // We have to take care of arrays specially, because GetType on
1186                 // a TypeBuilder array will return a Type, not a TypeBuilder,
1187                 // and we can not call FindMembers on this type.
1188                 //
1189                 if (
1190 #if MS_COMPATIBLE && GMCS_SOURCE
1191                         !t.IsGenericType &&
1192 #endif
1193                         t.IsSubclassOf (TypeManager.array_type))
1194                         return new MemberList (TypeManager.array_type.FindMembers (mt, bf, filter, criteria));
1195
1196 #if GMCS_SOURCE
1197                 if (t is GenericTypeParameterBuilder) {
1198                         TypeParameter tparam = (TypeParameter) builder_to_type_param [t];
1199
1200                         Timer.StartTimer (TimerType.FindMembers);
1201                         MemberList list = tparam.FindMembers (
1202                                 mt, bf | BindingFlags.DeclaredOnly, filter, criteria);
1203                         Timer.StopTimer (TimerType.FindMembers);
1204                         return list;
1205                 }
1206 #endif
1207
1208                 //
1209                 // Since FindMembers will not lookup both static and instance
1210                 // members, we emulate this behaviour here.
1211                 //
1212                 if ((bf & instance_and_static) == instance_and_static){
1213                         MemberInfo [] i_members = t.FindMembers (
1214                                 mt, bf & ~BindingFlags.Static, filter, criteria);
1215
1216                         int i_len = i_members.Length;
1217                         if (i_len == 1){
1218                                 MemberInfo one = i_members [0];
1219
1220                                 //
1221                                 // If any of these are present, we are done!
1222                                 //
1223                                 if ((one is Type) || (one is EventInfo) || (one is FieldInfo))
1224                                         return new MemberList (i_members);
1225                         }
1226                                 
1227                         MemberInfo [] s_members = t.FindMembers (
1228                                 mt, bf & ~BindingFlags.Instance, filter, criteria);
1229
1230                         int s_len = s_members.Length;
1231                         if (i_len > 0 || s_len > 0)
1232                                 return new MemberList (i_members, s_members);
1233                         else {
1234                                 if (i_len > 0)
1235                                         return new MemberList (i_members);
1236                                 else
1237                                         return new MemberList (s_members);
1238                         }
1239                 }
1240
1241                 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1242         }
1243
1244
1245         /// <summary>
1246         ///   This method is only called from within MemberLookup.  It tries to use the member
1247         ///   cache if possible and falls back to the normal FindMembers if not.  The `used_cache'
1248         ///   flag tells the caller whether we used the cache or not.  If we used the cache, then
1249         ///   our return value will already contain all inherited members and the caller don't need
1250         ///   to check base classes and interfaces anymore.
1251         /// </summary>
1252         private static MemberInfo [] MemberLookup_FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1253                                                                string name, out bool used_cache)
1254         {
1255                 MemberCache cache;
1256
1257                 //
1258                 // If this is a dynamic type, it's always in the `builder_to_declspace' hash table
1259                 // and we can ask the DeclSpace for the MemberCache.
1260                 //
1261 #if MS_COMPATIBLE
1262                 if (t.Assembly == CodeGen.Assembly.Builder) {
1263                         if (t.IsGenericParameter) {
1264                                 TypeParameter tparam = (TypeParameter) builder_to_type_param[t];
1265
1266                                 used_cache = true;
1267                                 if (tparam.MemberCache == null)
1268                                         return new MemberInfo[0];
1269
1270                                 return tparam.MemberCache.FindMembers (
1271                                         mt, bf, name, FilterWithClosure_delegate, null);
1272                         }
1273
1274                         if (t.IsGenericType && !t.IsGenericTypeDefinition)
1275                                 t = t.GetGenericTypeDefinition ();
1276 #else
1277                 if (t is TypeBuilder) {
1278 #endif
1279                         DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1280                         cache = decl.MemberCache;
1281
1282                         //
1283                         // If this DeclSpace has a MemberCache, use it.
1284                         //
1285
1286                         if (cache != null) {
1287                                 used_cache = true;
1288                                 return cache.FindMembers (
1289                                         mt, bf, name, FilterWithClosure_delegate, null);
1290                         }
1291
1292                         // If there is no MemberCache, we need to use the "normal" FindMembers.
1293                         // Note, this is a VERY uncommon route!
1294
1295                         MemberList list;
1296                         Timer.StartTimer (TimerType.FindMembers);
1297                         list = decl.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
1298                                                  FilterWithClosure_delegate, name);
1299                         Timer.StopTimer (TimerType.FindMembers);
1300                         used_cache = false;
1301                         return (MemberInfo []) list;
1302                 }
1303
1304                 //
1305                 // We have to take care of arrays specially, because GetType on
1306                 // a TypeBuilder array will return a Type, not a TypeBuilder,
1307                 // and we can not call FindMembers on this type.
1308                 //
1309                 if (t.IsArray) {
1310                         used_cache = true;
1311                         return TypeHandle.ArrayType.MemberCache.FindMembers (
1312                                 mt, bf, name, FilterWithClosure_delegate, null);
1313                 }
1314
1315 #if GMCS_SOURCE
1316                 if (t is GenericTypeParameterBuilder) {
1317                         TypeParameter tparam = (TypeParameter) builder_to_type_param [t];
1318
1319                         used_cache = true;
1320                         if (tparam.MemberCache == null)
1321                                 return new MemberInfo [0];
1322
1323                         return tparam.MemberCache.FindMembers (
1324                                 mt, bf, name, FilterWithClosure_delegate, null);
1325                 }
1326 #endif
1327
1328                 if (IsGenericType (t) && (mt == MemberTypes.NestedType)) {
1329                         //
1330                         // This happens if we're resolving a class'es base class and interfaces
1331                         // in TypeContainer.DefineType().  At this time, the types aren't
1332                         // populated yet, so we can't use the cache.
1333                         //
1334                         MemberInfo[] info = t.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
1335                                                            FilterWithClosure_delegate, name);
1336                         used_cache = false;
1337                         return info;
1338                 }
1339
1340                 //
1341                 // This call will always succeed.  There is exactly one TypeHandle instance per
1342                 // type, TypeHandle.GetMemberCache() will, if necessary, create a new one, and return
1343                 // the corresponding MemberCache.
1344                 //
1345                 cache = TypeHandle.GetMemberCache (t);
1346
1347                 used_cache = true;
1348                 return cache.FindMembers (mt, bf, name, FilterWithClosure_delegate, null);
1349         }
1350
1351         public static bool IsBuiltinType (Type t)
1352         {
1353                 t = TypeToCoreType (t);
1354                 if (t == object_type || t == string_type || t == int32_type || t == uint32_type ||
1355                     t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1356                     t == char_type || t == short_type || t == decimal_type || t == bool_type ||
1357                     t == sbyte_type || t == byte_type || t == ushort_type || t == void_type)
1358                         return true;
1359                 else
1360                         return false;
1361         }
1362
1363         //
1364         // This is like IsBuiltinType, but lacks decimal_type, we should also clean up
1365         // the pieces in the code where we use IsBuiltinType and special case decimal_type.
1366         // 
1367         public static bool IsPrimitiveType (Type t)
1368         {
1369                 return (t == int32_type || t == uint32_type ||
1370                     t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1371                     t == char_type || t == short_type || t == bool_type ||
1372                     t == sbyte_type || t == byte_type || t == ushort_type);
1373         }
1374
1375         public static bool IsDelegateType (Type t)
1376         {
1377 #if GMCS_SOURCE
1378                 if (t.IsGenericParameter)
1379                         return false;
1380 #endif
1381
1382                 if (t == TypeManager.delegate_type || t == TypeManager.multicast_delegate_type)
1383                         return false;
1384
1385                 t = DropGenericTypeArguments (t);
1386                 return IsSubclassOf (t, TypeManager.delegate_type);
1387         }
1388         
1389         public static bool IsEnumType (Type t)
1390         {
1391                 t = DropGenericTypeArguments (t);
1392                 return t.BaseType == TypeManager.enum_type;
1393         }
1394
1395         public static bool IsBuiltinOrEnum (Type t)
1396         {
1397                 if (IsBuiltinType (t))
1398                         return true;
1399                 
1400                 if (IsEnumType (t))
1401                         return true;
1402
1403                 return false;
1404         }
1405
1406         public static bool IsAttributeType (Type t)
1407         {
1408                 return t == attribute_type && t.BaseType != null || IsSubclassOf (t, attribute_type);
1409         }
1410         
1411         static Stack unmanaged_enclosing_types = new Stack (4);
1412
1413         //
1414         // Whether a type is unmanaged.  This is used by the unsafe code (25.2)
1415         //
1416         public static bool IsUnmanagedType (Type t)
1417         {
1418                 // Avoid infloops in the case of: unsafe struct Foo { Foo *x; }
1419                 if (unmanaged_enclosing_types.Contains (t))
1420                         return true;
1421
1422                 // builtins that are not unmanaged types
1423                 if (t == TypeManager.object_type || t == TypeManager.string_type)
1424                         return false;
1425
1426                 if (IsGenericType (t) || IsGenericParameter (t))
1427                         return false;
1428
1429                 if (IsBuiltinOrEnum (t))
1430                         return true;
1431
1432                 // Someone did the work of checking if the ElementType of t is unmanaged.  Let's not repeat it.
1433                 if (t.IsPointer)
1434                         return true;
1435
1436                 // Arrays are disallowed, even if we mark them with [MarshalAs(UnmanagedType.ByValArray, ...)]
1437                 if (t.IsArray)
1438                         return false;
1439
1440                 if (!IsValueType (t))
1441                         return false;
1442
1443 #if GMCS_SOURCE
1444                 for (Type p = t.DeclaringType; p != null; p = p.DeclaringType) {
1445                         if (p.IsGenericTypeDefinition)
1446                                 return false;
1447                 }
1448 #endif
1449
1450                 unmanaged_enclosing_types.Push (t);
1451
1452                 bool retval = true;
1453
1454                 if (t is TypeBuilder) {
1455                         TypeContainer tc = LookupTypeContainer (t);
1456                         if (tc.Fields != null){
1457                                 foreach (FieldBase f in tc.Fields){
1458                                         // Avoid using f.FieldBuilder: f.Define () may not yet have been invoked.
1459                                         if ((f.ModFlags & Modifiers.STATIC) != 0)
1460                                                 continue;
1461                                         if (f.MemberType == null)
1462                                                 continue;
1463                                         if (!IsUnmanagedType (f.MemberType)){
1464                                                 Report.SymbolRelatedToPreviousError (f.Location, CSharpName (t) + "." + f.Name);
1465                                                 retval = false;
1466                                         }
1467                                 }
1468                         }
1469                 } else {
1470                         FieldInfo [] fields = t.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
1471                         
1472                         foreach (FieldInfo f in fields){
1473                                 if (!IsUnmanagedType (f.FieldType)){
1474                                         Report.SymbolRelatedToPreviousError (f);
1475                                         retval = false;
1476                                 }
1477                         }
1478                 }
1479
1480                 unmanaged_enclosing_types.Pop ();
1481
1482                 return retval;
1483         }
1484
1485         //
1486         // Null is considered to be a reference type
1487         //                      
1488         public static bool IsReferenceType (Type t)
1489         {
1490                 if (TypeManager.IsGenericParameter (t)) {
1491                         GenericConstraints constraints = TypeManager.GetTypeParameterConstraints (t);
1492                         if (constraints == null)
1493                                 return false;
1494
1495                         return constraints.IsReferenceType;
1496                 }
1497
1498                 return !t.IsValueType;
1499         }                       
1500                 
1501         public static bool IsValueType (Type t)
1502         {
1503                 return t.IsValueType || IsGenericParameter (t);
1504         }
1505         
1506         public static bool IsInterfaceType (Type t)
1507         {
1508                 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
1509                 if (tc == null)
1510                         return false;
1511
1512                 return tc.Kind == Kind.Interface;
1513         }
1514
1515         public static bool IsSubclassOf (Type type, Type base_type)
1516         {
1517                 TypeParameter tparam = LookupTypeParameter (type);
1518                 TypeParameter pparam = LookupTypeParameter (base_type);
1519
1520                 if ((tparam != null) && (pparam != null)) {
1521                         if (tparam == pparam)
1522                                 return true;
1523
1524                         return tparam.IsSubclassOf (base_type);
1525                 }
1526
1527 #if MS_COMPATIBLE && GMCS_SOURCE
1528                 if (type.IsGenericType)
1529                         type = type.GetGenericTypeDefinition ();
1530 #endif
1531
1532                 if (type.IsSubclassOf (base_type))
1533                         return true;
1534
1535                 do {
1536                         if (IsEqual (type, base_type))
1537                                 return true;
1538
1539                         type = type.BaseType;
1540                 } while (type != null);
1541
1542                 return false;
1543         }
1544
1545         public static bool IsPrivateAccessible (Type type, Type parent)
1546         {
1547                 if (type == null)
1548                         return false;
1549
1550                 if (type.Equals (parent))
1551                         return true;
1552
1553                 return DropGenericTypeArguments (type) == DropGenericTypeArguments (parent);
1554         }
1555
1556         public static bool IsFamilyAccessible (Type type, Type parent)
1557         {
1558                 TypeParameter tparam = LookupTypeParameter (type);
1559                 TypeParameter pparam = LookupTypeParameter (parent);
1560
1561                 if ((tparam != null) && (pparam != null)) {
1562                         if (tparam == pparam)
1563                                 return true;
1564
1565                         return tparam.IsSubclassOf (parent);
1566                 }
1567
1568                 do {
1569                         if (IsInstantiationOfSameGenericType (type, parent))
1570                                 return true;
1571
1572                         type = type.BaseType;
1573                 } while (type != null);
1574
1575                 return false;
1576         }
1577
1578         //
1579         // Checks whether `type' is a subclass or nested child of `base_type'.
1580         //
1581         public static bool IsNestedFamilyAccessible (Type type, Type base_type)
1582         {
1583                 do {
1584                         if (IsFamilyAccessible (type, base_type))
1585                                 return true;
1586
1587                         // Handle nested types.
1588                         type = type.DeclaringType;
1589                 } while (type != null);
1590
1591                 return false;
1592         }
1593
1594         //
1595         // Checks whether `type' is a nested child of `parent'.
1596         //
1597         public static bool IsNestedChildOf (Type type, Type parent)
1598         {
1599                 if (type == null)
1600                         return false;
1601
1602                 type = DropGenericTypeArguments (type);
1603                 parent = DropGenericTypeArguments (parent);
1604
1605                 if (IsEqual (type, parent))
1606                         return false;
1607
1608                 type = type.DeclaringType;
1609                 while (type != null) {
1610                         if (IsEqual (type, parent))
1611                                 return true;
1612
1613                         type = type.DeclaringType;
1614                 }
1615
1616                 return false;
1617         }
1618
1619         //
1620         // Checks whether `extern_type' is friend of the output assembly
1621         //
1622         public static bool IsThisOrFriendAssembly (Assembly assembly)
1623         {
1624                 if (assembly == CodeGen.Assembly.Builder)
1625                         return true;
1626
1627                 if (assembly_internals_vis_attrs.Contains (assembly))
1628                         return (bool)(assembly_internals_vis_attrs [assembly]);
1629                                 
1630                 if (internals_visible_attr_type == null)
1631                         return false;
1632                 
1633                 object [] attrs = assembly.GetCustomAttributes (internals_visible_attr_type, false);
1634                 if (attrs.Length == 0) {
1635                         assembly_internals_vis_attrs.Add (assembly, false);
1636                         return false;
1637                 }
1638
1639                 bool is_friend = false;
1640 #if GMCS_SOURCE
1641                 AssemblyName this_name = CodeGen.Assembly.Name;
1642                 byte [] this_token = this_name.GetPublicKeyToken ();
1643                 foreach (InternalsVisibleToAttribute attr in attrs) {
1644                         if (attr.AssemblyName == null || attr.AssemblyName.Length == 0)
1645                                 continue;
1646                         
1647                         AssemblyName aname = null;
1648                         try {
1649                                 aname = new AssemblyName (attr.AssemblyName);
1650                         } catch (FileLoadException) {
1651                         } catch (ArgumentException) {
1652                         }
1653
1654                         if (aname == null || aname.Name != this_name.Name)
1655                                 continue;
1656                         
1657                         byte [] key_token = aname.GetPublicKeyToken ();
1658                         if (key_token != null) {
1659                                 if (this_token.Length == 0) {
1660                                         // Same name, but assembly is not strongnamed
1661                                         Error_FriendAccessNameNotMatching (aname.FullName);
1662                                         break;
1663                                 }
1664                                 
1665                                 if (!CompareKeyTokens (this_token, key_token))
1666                                         continue;
1667                         }
1668
1669                         is_friend = true;
1670                         break;
1671                 }
1672 #endif
1673                 assembly_internals_vis_attrs.Add (assembly, is_friend);
1674                 return is_friend;
1675         }
1676
1677 #if GMCS_SOURCE
1678         static bool CompareKeyTokens (byte [] token1, byte [] token2)
1679         {
1680                 for (int i = 0; i < token1.Length; i++)
1681                         if (token1 [i] != token2 [i])
1682                                 return false;
1683
1684                 return true;
1685         }
1686
1687         static void Error_FriendAccessNameNotMatching (string other_name)
1688         {
1689                 Report.Error (281, "Friend access was granted to `" + other_name + 
1690                                 "', but the output assembly is named `" + CodeGen.Assembly.Name.FullName +
1691                                 "'. Try adding a reference to `" + other_name + 
1692                                 "' or change the output assembly name to match it");
1693         }
1694 #endif
1695
1696         //
1697         // Do the right thing when returning the element type of an
1698         // array type based on whether we are compiling corlib or not
1699         //
1700         public static Type GetElementType (Type t)
1701         {
1702                 if (RootContext.StdLib)
1703                         return t.GetElementType ();
1704                 else
1705                         return TypeToCoreType (t.GetElementType ());
1706         }
1707
1708         /// <summary>
1709         /// This method is not implemented by MS runtime for dynamic types
1710         /// </summary>
1711         public static bool HasElementType (Type t)
1712         {
1713                 return t.IsArray || t.IsPointer || t.IsByRef;
1714         }
1715
1716         public static Type GetEnumUnderlyingType (Type t)
1717         {
1718                 t = DropGenericTypeArguments (t);
1719                 Enum e = LookupTypeContainer (t) as Enum;
1720                 if (e != null)
1721                         return e.UnderlyingType;
1722
1723                 // TODO: cache it ?
1724                 FieldInfo fi = GetPredefinedField (t, Enum.UnderlyingValueField, Location.Null, Type.EmptyTypes);
1725                 if (fi == null)
1726                         return TypeManager.int32_type;
1727
1728                 return TypeToCoreType (fi.FieldType);
1729         }
1730         
1731         /// <summary>
1732         ///   Gigantic work around for missing features in System.Reflection.Emit follows.
1733         /// </summary>
1734         ///
1735         /// <remarks>
1736         ///   Since System.Reflection.Emit can not return MethodBase.GetParameters
1737         ///   for anything which is dynamic, and we need this in a number of places,
1738         ///   we register this information here, and use it afterwards.
1739         /// </remarks>
1740         static public void RegisterMethod (MethodBase mb, AParametersCollection ip)
1741         {
1742                 method_params.Add (mb, ip);
1743         }
1744
1745         static public void RegisterIndexer (PropertyBuilder pb, AParametersCollection p)
1746         {
1747                 method_params.Add (pb, p);
1748         }
1749         
1750         static public AParametersCollection GetParameterData (MethodBase mb)
1751         {
1752                 AParametersCollection pd = (AParametersCollection) method_params [mb];
1753                 if (pd == null) {
1754 #if MS_COMPATIBLE
1755                         if (mb.IsGenericMethod && !mb.IsGenericMethodDefinition) {
1756                                 MethodInfo mi = ((MethodInfo) mb).GetGenericMethodDefinition ();
1757                                 pd = GetParameterData (mi);
1758                                 /*
1759                                 if (mi.IsGenericMethod)
1760                                         pd = pd.InflateTypes (mi.GetGenericArguments (), mb.GetGenericArguments ());
1761                                 else
1762                                         pd = pd.InflateTypes (mi.DeclaringType.GetGenericArguments (), mb.GetGenericArguments ());
1763                                 */
1764                                 method_params.Add (mb, pd);
1765                                 return pd;
1766                         }
1767
1768                         if (mb.DeclaringType.Assembly == CodeGen.Assembly.Builder) {
1769                                 throw new InternalErrorException ("Parameters are not registered for method `{0}'",
1770                                         TypeManager.CSharpName (mb.DeclaringType) + "." + mb.Name);
1771                         }
1772
1773                         pd = ParametersCollection.Create (mb);
1774 #else
1775                         MethodBase generic = TypeManager.DropGenericMethodArguments (mb);
1776                         if (generic != mb) {
1777                                 pd = TypeManager.GetParameterData (generic);
1778                                 pd = ParametersCollection.Create (pd, mb);
1779                         } else {
1780                                 pd = ParametersCollection.Create (mb);
1781                         }
1782 #endif
1783                         method_params.Add (mb, pd);
1784                 }
1785                 return pd;
1786         }
1787
1788         public static AParametersCollection GetParameterData (PropertyInfo pi)
1789         {
1790                 AParametersCollection pd = (AParametersCollection)method_params [pi];
1791                 if (pd == null) {
1792                         if (pi is PropertyBuilder)
1793                                 return Parameters.EmptyReadOnlyParameters;
1794
1795                         ParameterInfo [] p = pi.GetIndexParameters ();
1796                         if (p == null)
1797                                 return Parameters.EmptyReadOnlyParameters;
1798
1799                         pd = ParametersCollection.Create (p, null);
1800                         method_params.Add (pi, pd);
1801                 }
1802
1803                 return pd;
1804         }
1805
1806         public static AParametersCollection GetDelegateParameters (Type t)
1807         {
1808                 Delegate d = builder_to_declspace [t] as Delegate;
1809                 if (d != null)
1810                         return d.Parameters;
1811
1812                 MethodInfo invoke_mb = Delegate.GetInvokeMethod (t, t);
1813                 return GetParameterData (invoke_mb);
1814         }
1815
1816         static public void RegisterOverride (MethodBase override_method, MethodBase base_method)
1817         {
1818                 if (!method_overrides.Contains (override_method))
1819                         method_overrides [override_method] = base_method;
1820                 if (method_overrides [override_method] != base_method)
1821                         throw new InternalErrorException ("Override mismatch: " + override_method);
1822         }
1823
1824         static public bool IsOverride (MethodBase m)
1825         {
1826                 m = DropGenericMethodArguments (m);
1827
1828                 return m.IsVirtual &&
1829                         (m.Attributes & MethodAttributes.NewSlot) == 0 &&
1830                         (m is MethodBuilder || method_overrides.Contains (m));
1831         }
1832
1833         static public MethodBase TryGetBaseDefinition (MethodBase m)
1834         {
1835                 m = DropGenericMethodArguments (m);
1836
1837                 return (MethodBase) method_overrides [m];
1838         }
1839
1840         public static void RegisterConstant (FieldInfo fb, IConstant ic)
1841         {
1842                 fields.Add (fb, ic);
1843         }
1844
1845         public static IConstant GetConstant (FieldInfo fb)
1846         {
1847                 if (fb == null)
1848                         return null;
1849
1850                 return (IConstant)fields [fb];
1851         }
1852
1853         public static void RegisterProperty (PropertyInfo pi, PropertyBase pb)
1854         {
1855                 propertybuilder_to_property.Add (pi, pb);
1856         }
1857
1858         public static PropertyBase GetProperty (PropertyInfo pi)
1859         {
1860                 return (PropertyBase)propertybuilder_to_property [pi];
1861         }
1862
1863         static public void RegisterFieldBase (FieldBuilder fb, FieldBase f)
1864         {
1865                 fieldbuilders_to_fields.Add (fb, f);
1866         }
1867
1868         //
1869         // The return value can be null;  This will be the case for
1870         // auxiliary FieldBuilders created by the compiler that have no
1871         // real field being declared on the source code
1872         //
1873         static public FieldBase GetField (FieldInfo fb)
1874         {
1875 #if GMCS_SOURCE
1876                 fb = GetGenericFieldDefinition (fb);
1877 #endif
1878                 return (FieldBase) fieldbuilders_to_fields [fb];
1879         }
1880
1881         static public MethodInfo GetAddMethod (EventInfo ei)
1882         {
1883                 if (ei is MyEventBuilder) {
1884                         return ((MyEventBuilder)ei).GetAddMethod (true);
1885                 }
1886                 return ei.GetAddMethod (true);
1887         }
1888
1889         static public MethodInfo GetRemoveMethod (EventInfo ei)
1890         {
1891                 if (ei is MyEventBuilder) {
1892                         return ((MyEventBuilder)ei).GetRemoveMethod (true);
1893                 }
1894                 return ei.GetRemoveMethod (true);
1895         }
1896
1897         static public void RegisterEventField (EventInfo einfo, EventField e)
1898         {
1899                 if (events == null)
1900                         events = new Hashtable ();
1901
1902                 events.Add (einfo, e);
1903         }
1904
1905         static public EventField GetEventField (EventInfo ei)
1906         {
1907                 if (events == null)
1908                         return null;
1909
1910                 return (EventField) events [ei];
1911         }
1912
1913         public static bool CheckStructCycles (TypeContainer tc, Hashtable seen)
1914         {
1915                 Hashtable hash = new Hashtable ();
1916                 return CheckStructCycles (tc, seen, hash);
1917         }
1918
1919         public static bool CheckStructCycles (TypeContainer tc, Hashtable seen,
1920                                               Hashtable hash)
1921         {
1922                 if ((tc.Kind != Kind.Struct) || IsBuiltinType (tc.TypeBuilder))
1923                         return true;
1924
1925                 //
1926                 // `seen' contains all types we've already visited.
1927                 //
1928                 if (seen.Contains (tc))
1929                         return true;
1930                 seen.Add (tc, null);
1931
1932                 if (tc.Fields == null)
1933                         return true;
1934
1935                 foreach (FieldBase field in tc.Fields) {
1936                         if (field.FieldBuilder == null || field.FieldBuilder.IsStatic)
1937                                 continue;
1938
1939                         Type ftype = field.FieldBuilder.FieldType;
1940                         TypeContainer ftc = LookupTypeContainer (ftype);
1941                         if (ftc == null)
1942                                 continue;
1943
1944                         if (hash.Contains (ftc)) {
1945                                 Report.Error (523, tc.Location,
1946                                               "Struct member `{0}.{1}' of type `{2}' " +
1947                                               "causes a cycle in the struct layout",
1948                                               tc.Name, field.Name, ftc.Name);
1949                                 return false;
1950                         }
1951
1952                         //
1953                         // `hash' contains all types in the current path.
1954                         //
1955                         hash.Add (tc, null);
1956
1957                         bool ok = CheckStructCycles (ftc, seen, hash);
1958
1959                         hash.Remove (tc);
1960
1961                         if (!ok)
1962                                 return false;
1963
1964                         if (!seen.Contains (ftc))
1965                                 seen.Add (ftc, null);
1966                 }
1967
1968                 return true;
1969         }
1970
1971         /// <summary>
1972         ///   Given an array of interface types, expand and eliminate repeated ocurrences
1973         ///   of an interface.  
1974         /// </summary>
1975         ///
1976         /// <remarks>
1977         ///   This expands in context like: IA; IB : IA; IC : IA, IB; the interface "IC" to
1978         ///   be IA, IB, IC.
1979         /// </remarks>
1980         public static Type[] ExpandInterfaces (TypeExpr [] base_interfaces)
1981         {
1982                 ArrayList new_ifaces = new ArrayList ();
1983
1984                 foreach (TypeExpr iface in base_interfaces){
1985                         Type itype = iface.Type;
1986
1987                         if (new_ifaces.Contains (itype))
1988                                 continue;
1989
1990                         new_ifaces.Add (itype);
1991                         
1992                         Type [] implementing = GetInterfaces (itype);
1993
1994                         foreach (Type imp in implementing){
1995                                 if (!new_ifaces.Contains (imp))
1996                                         new_ifaces.Add (imp);
1997                         }
1998                 }
1999                 Type [] ret = new Type [new_ifaces.Count];
2000                 new_ifaces.CopyTo (ret, 0);
2001                 return ret;
2002         }
2003
2004         public static Type[] ExpandInterfaces (Type [] base_interfaces)
2005         {
2006                 ArrayList new_ifaces = new ArrayList ();
2007
2008                 foreach (Type itype in base_interfaces){
2009                         if (new_ifaces.Contains (itype))
2010                                 continue;
2011
2012                         new_ifaces.Add (itype);
2013                         
2014                         Type [] implementing = GetInterfaces (itype);
2015
2016                         foreach (Type imp in implementing){
2017                                 if (!new_ifaces.Contains (imp))
2018                                         new_ifaces.Add (imp);
2019                         }
2020                 }
2021                 Type [] ret = new Type [new_ifaces.Count];
2022                 new_ifaces.CopyTo (ret, 0);
2023                 return ret;
2024         }
2025                 
2026         static PtrHashtable iface_cache = new PtrHashtable ();
2027                 
2028         /// <summary>
2029         ///   This function returns the interfaces in the type `t'.  Works with
2030         ///   both types and TypeBuilders.
2031         /// </summary>
2032         public static Type [] GetInterfaces (Type t)
2033         {
2034                 Type [] cached = iface_cache [t] as Type [];
2035                 if (cached != null)
2036                         return cached;
2037                 
2038                 //
2039                 // The reason for catching the Array case is that Reflection.Emit
2040                 // will not return a TypeBuilder for Array types of TypeBuilder types,
2041                 // but will still throw an exception if we try to call GetInterfaces
2042                 // on the type.
2043                 //
2044                 // Since the array interfaces are always constant, we return those for
2045                 // the System.Array
2046                 //
2047                 
2048                 if (t.IsArray)
2049                         t = TypeManager.array_type;
2050                 
2051                 if ((t is TypeBuilder) || IsGenericType (t)) {
2052                         Type [] base_ifaces;
2053                         
2054                         if (t.BaseType == null)
2055                                 base_ifaces = Type.EmptyTypes;
2056                         else
2057                                 base_ifaces = GetInterfaces (t.BaseType);
2058                         Type[] type_ifaces;
2059                         if (IsGenericType (t))
2060 #if MS_COMPATIBLE && GMCS_SOURCE
2061                                 type_ifaces = t.GetGenericTypeDefinition().GetInterfaces ();
2062 #else
2063                                 type_ifaces = t.GetInterfaces ();
2064 #endif
2065                         else
2066                                 type_ifaces = (Type []) builder_to_ifaces [t];
2067                         if (type_ifaces == null || type_ifaces.Length == 0)
2068                                 type_ifaces = Type.EmptyTypes;
2069
2070                         int base_count = base_ifaces.Length;
2071                         Type [] result = new Type [base_count + type_ifaces.Length];
2072                         base_ifaces.CopyTo (result, 0);
2073                         type_ifaces.CopyTo (result, base_count);
2074
2075                         iface_cache [t] = result;
2076                         return result;
2077 #if GMCS_SOURCE
2078                 } else if (t is GenericTypeParameterBuilder){
2079                         Type[] type_ifaces = (Type []) builder_to_ifaces [t];
2080                         if (type_ifaces == null || type_ifaces.Length == 0)
2081                                 type_ifaces = Type.EmptyTypes;
2082
2083                         iface_cache [t] = type_ifaces;
2084                         return type_ifaces;
2085 #endif
2086                 } else {
2087                         Type[] ifaces = t.GetInterfaces ();
2088                         iface_cache [t] = ifaces;
2089                         return ifaces;
2090                 }
2091         }
2092         
2093         //
2094         // gets the interfaces that are declared explicitly on t
2095         //
2096         public static Type [] GetExplicitInterfaces (TypeBuilder t)
2097         {
2098                 return (Type []) builder_to_ifaces [t];
2099         }
2100         
2101         /// <remarks>
2102         ///  The following is used to check if a given type implements an interface.
2103         ///  The cache helps us reduce the expense of hitting Type.GetInterfaces everytime.
2104         /// </remarks>
2105         public static bool ImplementsInterface (Type t, Type iface)
2106         {
2107                 Type [] interfaces;
2108
2109                 //
2110                 // FIXME OPTIMIZATION:
2111                 // as soon as we hit a non-TypeBuiler in the interface
2112                 // chain, we could return, as the `Type.GetInterfaces'
2113                 // will return all the interfaces implement by the type
2114                 // or its bases.
2115                 //
2116                 do {
2117                         interfaces = GetInterfaces (t);
2118
2119                         if (interfaces != null){
2120                                 foreach (Type i in interfaces){
2121                                         if (i == iface)
2122                                                 return true;
2123                                 }
2124                         }
2125                         
2126                         t = t.BaseType;
2127                 } while (t != null);
2128                 
2129                 return false;
2130         }
2131
2132         static NumberFormatInfo nf_provider = CultureInfo.CurrentCulture.NumberFormat;
2133
2134         // This is a custom version of Convert.ChangeType() which works
2135         // with the TypeBuilder defined types when compiling corlib.
2136         public static object ChangeType (object value, Type conversionType, out bool error)
2137         {
2138                 IConvertible convert_value = value as IConvertible;
2139                 
2140                 if (convert_value == null){
2141                         error = true;
2142                         return null;
2143                 }
2144                 
2145                 //
2146                 // NOTE 1:
2147                 // We must use Type.Equals() here since `conversionType' is
2148                 // the TypeBuilder created version of a system type and not
2149                 // the system type itself.  You cannot use Type.GetTypeCode()
2150                 // on such a type - it'd always return TypeCode.Object.
2151                 //
2152                 // NOTE 2:
2153                 // We cannot rely on build-in type conversions as they are
2154                 // more limited than what C# supports.
2155                 // See char -> float/decimal/double conversion
2156                 //
2157
2158                 error = false;
2159                 try {
2160                         if (conversionType.Equals (typeof (Boolean)))
2161                                 return (object)(convert_value.ToBoolean (nf_provider));
2162                         if (conversionType.Equals (typeof (Byte)))
2163                                 return (object)(convert_value.ToByte (nf_provider));
2164                         if (conversionType.Equals (typeof (Char)))
2165                                 return (object)(convert_value.ToChar (nf_provider));
2166                         if (conversionType.Equals (typeof (DateTime)))
2167                                 return (object)(convert_value.ToDateTime (nf_provider));
2168
2169                         if (conversionType.Equals (decimal_type)) {
2170                                 if (convert_value.GetType () == TypeManager.char_type)
2171                                         return (decimal)convert_value.ToInt32 (nf_provider);
2172                                 return convert_value.ToDecimal (nf_provider);
2173                         }
2174
2175                         if (conversionType.Equals (typeof (Double))) {
2176                                 if (convert_value.GetType () == TypeManager.char_type)
2177                                         return (double)convert_value.ToInt32 (nf_provider);
2178                                 return convert_value.ToDouble (nf_provider);
2179                         }
2180
2181                         if (conversionType.Equals (typeof (Int16)))
2182                                 return (object)(convert_value.ToInt16 (nf_provider));
2183                         if (conversionType.Equals (int32_type))
2184                                 return (object)(convert_value.ToInt32 (nf_provider));
2185                         if (conversionType.Equals (int64_type))
2186                                 return (object)(convert_value.ToInt64 (nf_provider));
2187                         if (conversionType.Equals (typeof (SByte)))
2188                                 return (object)(convert_value.ToSByte (nf_provider));
2189
2190                         if (conversionType.Equals (typeof (Single))) {
2191                                 if (convert_value.GetType () == TypeManager.char_type)
2192                                         return (float)convert_value.ToInt32 (nf_provider);
2193                                 return convert_value.ToSingle (nf_provider);
2194                         }
2195
2196                         if (conversionType.Equals (typeof (String)))
2197                                 return (object)(convert_value.ToString (nf_provider));
2198                         if (conversionType.Equals (typeof (UInt16)))
2199                                 return (object)(convert_value.ToUInt16 (nf_provider));
2200                         if (conversionType.Equals (typeof (UInt32)))
2201                                 return (object)(convert_value.ToUInt32 (nf_provider));
2202                         if (conversionType.Equals (typeof (UInt64)))
2203                                 return (object)(convert_value.ToUInt64 (nf_provider));
2204                         if (conversionType.Equals (typeof (Object)))
2205                                 return (object)(value);
2206                         else 
2207                                 error = true;
2208                 } catch {
2209                         error = true;
2210                 }
2211                 return null;
2212         }
2213
2214         //
2215         // When compiling with -nostdlib and the type is imported from an external assembly
2216         // SRE uses "wrong" type and we have to convert it to the right compiler instance.
2217         //
2218         public static Type TypeToCoreType (Type t)
2219         {
2220                 if (RootContext.StdLib || t.Module != typeof (object).Module)
2221                         return t;
2222
2223                 TypeCode tc = Type.GetTypeCode (t);
2224
2225                 switch (tc){
2226                 case TypeCode.Boolean:
2227                         return TypeManager.bool_type;
2228                 case TypeCode.Byte:
2229                         return TypeManager.byte_type;
2230                 case TypeCode.SByte:
2231                         return TypeManager.sbyte_type;
2232                 case TypeCode.Char:
2233                         return TypeManager.char_type;
2234                 case TypeCode.Int16:
2235                         return TypeManager.short_type;
2236                 case TypeCode.UInt16:
2237                         return TypeManager.ushort_type;
2238                 case TypeCode.Int32:
2239                         return TypeManager.int32_type;
2240                 case TypeCode.UInt32:
2241                         return TypeManager.uint32_type;
2242                 case TypeCode.Int64:
2243                         return TypeManager.int64_type;
2244                 case TypeCode.UInt64:
2245                         return TypeManager.uint64_type;
2246                 case TypeCode.Single:
2247                         return TypeManager.float_type;
2248                 case TypeCode.Double:
2249                         return TypeManager.double_type;
2250                 case TypeCode.String:
2251                         return TypeManager.string_type;
2252                 case TypeCode.Decimal:
2253                         return TypeManager.decimal_type;
2254                 }
2255
2256                 if (t == typeof (void))
2257                         return TypeManager.void_type;
2258                 if (t == typeof (object))
2259                         return TypeManager.object_type;
2260                 if (t == typeof (System.Type))
2261                         return TypeManager.type_type;
2262                 if (t == typeof (System.IntPtr))
2263                         return TypeManager.intptr_type;
2264                 if (t == typeof (System.UIntPtr))
2265                         return TypeManager.uintptr_type;
2266 #if GMCS_SOURCE
2267                 if (t.IsArray) {
2268                         int dim = t.GetArrayRank ();
2269                         t = GetElementType (t);
2270                         return t.MakeArrayType (dim);
2271                 }
2272                 if (t.IsByRef) {
2273                         t = GetElementType (t);
2274                         return t.MakeByRefType ();
2275                 }
2276                 if (t.IsPointer) {
2277                         t = GetElementType (t);
2278                         return t.MakePointerType ();
2279                 }
2280 #endif
2281                 return t;
2282         }
2283
2284         /// <summary>
2285         ///   Utility function that can be used to probe whether a type
2286         ///   is managed or not.  
2287         /// </summary>
2288         public static bool VerifyUnManaged (Type t, Location loc)
2289         {
2290                 if (IsUnmanagedType (t))
2291                         return true;
2292
2293                 Report.Error (208, loc, "Cannot take the address of, get the size of, or declare a pointer to a managed type `{0}'",
2294                         CSharpName (t));
2295
2296                 return false;   
2297         }
2298         
2299         /// <summary>
2300         ///   Returns the name of the indexer in a given type.
2301         /// </summary>
2302         /// <remarks>
2303         ///   The default is not always `Item'.  The user can change this behaviour by
2304         ///   using the IndexerNameAttribute in the container.
2305         ///   For example, the String class indexer is named `Chars' not `Item' 
2306         /// </remarks>
2307         public static string IndexerPropertyName (Type t)
2308         {
2309                 t = DropGenericTypeArguments (t);
2310                 if (t is TypeBuilder) {
2311                         TypeContainer tc = t.IsInterface ? LookupInterface (t) : LookupTypeContainer (t);
2312                         return tc == null ? TypeContainer.DefaultIndexerName : tc.IndexerName;
2313                 }
2314                 
2315                 System.Attribute attr = System.Attribute.GetCustomAttribute (
2316                         t, TypeManager.default_member_type);
2317                 if (attr != null){
2318                         DefaultMemberAttribute dma = (DefaultMemberAttribute) attr;
2319                         return dma.MemberName;
2320                 }
2321
2322                 return TypeContainer.DefaultIndexerName;
2323         }
2324
2325         static MethodInfo declare_local_method = null;
2326         
2327         public static LocalBuilder DeclareLocalPinned (ILGenerator ig, Type t)
2328         {
2329                 if (declare_local_method == null){
2330                         declare_local_method = typeof (ILGenerator).GetMethod (
2331                                 "DeclareLocal",
2332                                 BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
2333                                 null, 
2334                                 new Type [] { typeof (Type), typeof (bool)},
2335                                 null);
2336                         if (declare_local_method == null){
2337                                 Report.RuntimeMissingSupport (Location.Null, "pinned local variables");
2338                                 return ig.DeclareLocal (t);
2339                         }
2340                 }
2341                 return (LocalBuilder) declare_local_method.Invoke (ig, new object [] { t, true });
2342         }
2343
2344         private static bool IsSignatureEqual (Type a, Type b)
2345         {
2346                 ///
2347                 /// Consider the following example (bug #77674):
2348                 ///
2349                 ///     public abstract class A
2350                 ///     {
2351                 ///        public abstract T Foo<T> ();
2352                 ///     }
2353                 ///
2354                 ///     public abstract class B : A
2355                 ///     {
2356                 ///        public override U Foo<T> ()
2357                 ///        { return default (U); }
2358                 ///     }
2359                 ///
2360                 /// Here, `T' and `U' are method type parameters from different methods
2361                 /// (A.Foo and B.Foo), so both `==' and Equals() will fail.
2362                 ///
2363                 /// However, since we're determining whether B.Foo() overrides A.Foo(),
2364                 /// we need to do a signature based comparision and consider them equal.
2365
2366                 if (a == b)
2367                         return true;
2368
2369 #if GMCS_SOURCE
2370                 if (a.IsGenericParameter && b.IsGenericParameter &&
2371                     (a.DeclaringMethod != null) && (b.DeclaringMethod != null)) {
2372                         return a.GenericParameterPosition == b.GenericParameterPosition;
2373                 }
2374 #endif
2375
2376                 if (a.IsArray && b.IsArray) {
2377                         if (a.GetArrayRank () != b.GetArrayRank ())
2378                                 return false;
2379
2380                         return IsSignatureEqual (a.GetElementType (), b.GetElementType ());
2381                 }
2382
2383                 if (a.IsByRef && b.IsByRef)
2384                         return IsSignatureEqual (a.GetElementType (), b.GetElementType ());
2385
2386 #if GMCS_SOURCE
2387                 if (a.IsGenericType && b.IsGenericType) {
2388                         if (a.GetGenericTypeDefinition () != b.GetGenericTypeDefinition ())
2389                                 return false;
2390
2391                         Type[] aargs = a.GetGenericArguments ();
2392                         Type[] bargs = b.GetGenericArguments ();
2393
2394                         if (aargs.Length != bargs.Length)
2395                                 return false;
2396
2397                         for (int i = 0; i < aargs.Length; i++) {
2398                                 if (!IsSignatureEqual (aargs [i], bargs [i]))
2399                                         return false;
2400                         }
2401
2402                         return true;
2403                 }
2404 #endif
2405
2406                 return false;
2407         }
2408
2409         //
2410         // Returns whether the array of memberinfos contains the given method
2411         //
2412         public static bool ArrayContainsMethod (MemberInfo [] array, MethodBase new_method, bool ignoreDeclType)
2413         {
2414                 Type [] new_args = TypeManager.GetParameterData (new_method).Types;
2415                 
2416                 foreach (MethodBase method in array) {
2417                         if (!ignoreDeclType && method.DeclaringType != new_method.DeclaringType)
2418                                 continue;
2419                 
2420                         if (method.Name != new_method.Name)
2421                                 continue;
2422
2423                         if (method is MethodInfo && new_method is MethodInfo &&
2424                                 !IsSignatureEqual (
2425                                         TypeToCoreType (((MethodInfo) method).ReturnType),
2426                                         TypeToCoreType (((MethodInfo) new_method).ReturnType)))
2427                                 continue;
2428                         
2429                         Type [] old_args = TypeManager.GetParameterData (method).Types;
2430                         int old_count = old_args.Length;
2431                         int i;
2432                         
2433                         if (new_args.Length != old_count)
2434                                 continue;
2435                         
2436                         for (i = 0; i < old_count; i++){
2437                                 if (!IsSignatureEqual (old_args [i], new_args [i]))
2438                                         break;
2439                         }
2440                         if (i != old_count)
2441                                 continue;
2442
2443                         return true;
2444                 }
2445                 
2446                 return false;
2447         }
2448         
2449         //
2450         // We copy methods from `new_members' into `target_list' if the signature
2451         // for the method from in the new list does not exist in the target_list
2452         //
2453         // The name is assumed to be the same.
2454         //
2455         public static ArrayList CopyNewMethods (ArrayList target_list, IList new_members)
2456         {
2457                 if (target_list == null){
2458                         target_list = new ArrayList ();
2459
2460                         foreach (MemberInfo mi in new_members){
2461                                 if (mi is MethodBase)
2462                                         target_list.Add (mi);
2463                         }
2464                         return target_list;
2465                 }
2466                 
2467                 MemberInfo [] target_array = new MemberInfo [target_list.Count];
2468                 target_list.CopyTo (target_array, 0);
2469                 
2470                 foreach (MemberInfo mi in new_members){
2471                         MethodBase new_method = (MethodBase) mi;
2472                         
2473                         if (!ArrayContainsMethod (target_array, new_method, true))
2474                                 target_list.Add (new_method);
2475                 }
2476                 return target_list;
2477         }
2478
2479 #region Generics
2480         // <remarks>
2481         //   Tracks the generic parameters.
2482         // </remarks>
2483         static PtrHashtable builder_to_type_param;
2484
2485         public static void AddTypeParameter (Type t, TypeParameter tparam)
2486         {
2487                 if (!builder_to_type_param.Contains (t))
2488                         builder_to_type_param.Add (t, tparam);
2489         }
2490
2491         public static TypeParameter LookupTypeParameter (Type t)
2492         {
2493                 return (TypeParameter) builder_to_type_param [t];
2494         }
2495
2496         // This method always return false for non-generic compiler,
2497         // while Type.IsGenericParameter is returned if it is supported.
2498         public static bool IsGenericParameter (Type type)
2499         {
2500 #if GMCS_SOURCE
2501                 return type.IsGenericParameter;
2502 #else
2503                 return false;
2504 #endif
2505         }
2506
2507         public static int GenericParameterPosition (Type type)
2508         {
2509 #if GMCS_SOURCE
2510                 return type.GenericParameterPosition;
2511 #else
2512                 throw new InternalErrorException ("should not be called");
2513 #endif
2514         }
2515
2516         public static bool IsGenericType (Type type)
2517         {
2518 #if GMCS_SOURCE
2519                 return type.IsGenericType;
2520 #else
2521                 return false;
2522 #endif
2523         }
2524
2525         public static bool IsGenericTypeDefinition (Type type)
2526         {
2527 #if GMCS_SOURCE
2528                 return type.IsGenericTypeDefinition;
2529 #else
2530                 return false;
2531 #endif
2532         }
2533
2534         public static bool ContainsGenericParameters (Type type)
2535         {
2536 #if GMCS_SOURCE
2537                 return type.ContainsGenericParameters;
2538 #else
2539                 return false;
2540 #endif
2541         }
2542
2543         public static FieldInfo GetGenericFieldDefinition (FieldInfo fi)
2544         {
2545 #if GMCS_SOURCE
2546                 if (fi.DeclaringType.IsGenericTypeDefinition ||
2547                     !fi.DeclaringType.IsGenericType)
2548                         return fi;
2549
2550                 Type t = fi.DeclaringType.GetGenericTypeDefinition ();
2551                 BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic |
2552                         BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
2553
2554                 // TODO: use CodeGen.Module.Builder.ResolveField (fi.MetadataToken);
2555                 foreach (FieldInfo f in t.GetFields (bf))
2556                         if (f.MetadataToken == fi.MetadataToken)
2557                                 return f;
2558 #endif
2559
2560                 return fi;
2561         }
2562
2563         public static bool IsEqual (Type a, Type b)
2564         {
2565                 if (a.Equals (b)) {
2566                         // MS BCL returns true even if enum types are different
2567                         if (a.BaseType == TypeManager.enum_type || b.BaseType == TypeManager.enum_type)
2568                                 return a.FullName == b.FullName;
2569
2570                         // Some types are never equal
2571                         if (a == TypeManager.null_type || a == TypeManager.anonymous_method_type)
2572                                 return false;
2573
2574                         return true;
2575                 }
2576
2577 #if GMCS_SOURCE
2578                 if (a.IsGenericParameter && b.IsGenericParameter) {
2579                         // TODO: needs more testing before cleaning up
2580                         //if (a.DeclaringMethod != b.DeclaringMethod &&
2581                         //    (a.DeclaringMethod == null || b.DeclaringMethod == null))
2582                         //      return false;
2583                         return a.GenericParameterPosition == b.GenericParameterPosition;
2584                 }
2585
2586                 if (a.IsArray && b.IsArray) {
2587                         if (a.GetArrayRank () != b.GetArrayRank ())
2588                                 return false;
2589                         return IsEqual (a.GetElementType (), b.GetElementType ());
2590                 }
2591
2592                 if (a.IsByRef && b.IsByRef)
2593                         return IsEqual (a.GetElementType (), b.GetElementType ());
2594
2595                 if (a.IsGenericType && b.IsGenericType) {
2596                         Type adef = a.GetGenericTypeDefinition ();
2597                         Type bdef = b.GetGenericTypeDefinition ();
2598
2599                         if (adef != bdef)
2600                                 return false;
2601
2602                         if (adef.IsEnum && bdef.IsEnum)
2603                                 return true;
2604
2605                         Type[] aargs = a.GetGenericArguments ();
2606                         Type[] bargs = b.GetGenericArguments ();
2607
2608                         if (aargs.Length != bargs.Length)
2609                                 return false;
2610
2611                         for (int i = 0; i < aargs.Length; i++) {
2612                                 if (!IsEqual (aargs [i], bargs [i]))
2613                                         return false;
2614                         }
2615
2616                         return true;
2617                 }
2618 #endif
2619
2620                 return false;
2621         }
2622
2623         public static bool IsEqual (Type[] a, Type[] b)
2624         {
2625                 if (a == null || b == null || a.Length != b.Length)
2626                         return false;
2627
2628                 for (int i = 0; i < a.Length; ++i) {
2629                         if (a [i] == null || b [i] == null) {
2630                                 if (a [i] == b [i])
2631                                         continue;
2632
2633                                 return false;
2634                         }
2635                 
2636                         if (!IsEqual (a [i], b [i]))
2637                                 return false;
2638                 }
2639
2640                 return true;
2641         }
2642
2643         public static Type DropGenericTypeArguments (Type t)
2644         {
2645 #if GMCS_SOURCE
2646                 if (!t.IsGenericType)
2647                         return t;
2648                 // Micro-optimization: a generic typebuilder is always a generic type definition
2649                 if (t is TypeBuilder)
2650                         return t;
2651                 return t.GetGenericTypeDefinition ();
2652 #else
2653                 return t;
2654 #endif
2655         }
2656
2657         public static MethodBase DropGenericMethodArguments (MethodBase m)
2658         {
2659 #if GMCS_SOURCE
2660                 if (m.IsGenericMethod)
2661                   m = ((MethodInfo) m).GetGenericMethodDefinition ();
2662
2663                 Type t = m.DeclaringType;
2664                 if (!t.IsGenericType || t.IsGenericTypeDefinition)
2665                         return m;
2666
2667                 t = t.GetGenericTypeDefinition ();
2668                 BindingFlags bf = BindingFlags.Public | BindingFlags.NonPublic |
2669                         BindingFlags.Static | BindingFlags.Instance | BindingFlags.DeclaredOnly;
2670
2671 #if MS_COMPATIBLE
2672                 // TODO: use CodeGen.Module.Builder.ResolveMethod ()
2673                 return m;
2674 #endif
2675
2676                 if (m is ConstructorInfo) {
2677                         foreach (ConstructorInfo c in t.GetConstructors (bf))
2678                                 if (c.MetadataToken == m.MetadataToken)
2679                                         return c;
2680                 } else {
2681                         foreach (MethodBase mb in t.GetMethods (bf))
2682                                 if (mb.MetadataToken == m.MetadataToken)
2683                                         return mb;
2684                 }
2685 #endif
2686
2687                 return m;
2688         }
2689
2690         public static Type[] GetGenericArguments (MethodBase mi)
2691         {
2692 #if GMCS_SOURCE
2693                 return mi.GetGenericArguments ();
2694 #else
2695                 return Type.EmptyTypes;
2696 #endif
2697         }
2698
2699         public static Type[] GetTypeArguments (Type t)
2700         {
2701 #if GMCS_SOURCE
2702                 DeclSpace tc = LookupDeclSpace (t);
2703                 if (tc != null) {
2704                         if (!tc.IsGeneric)
2705                                 return Type.EmptyTypes;
2706
2707                         TypeParameter[] tparam = tc.TypeParameters;
2708                         Type[] ret = new Type [tparam.Length];
2709                         for (int i = 0; i < tparam.Length; i++) {
2710                                 ret [i] = tparam [i].Type;
2711                                 if (ret [i] == null)
2712                                         throw new InternalErrorException ();
2713                         }
2714
2715                         return ret;
2716                 } else
2717                         return t.GetGenericArguments ();
2718 #else
2719                 throw new InternalErrorException ();
2720 #endif
2721         }
2722                         
2723         public static GenericConstraints GetTypeParameterConstraints (Type t)
2724         {
2725 #if GMCS_SOURCE                         
2726                 if (!t.IsGenericParameter)
2727                         throw new InvalidOperationException ();
2728
2729                 TypeParameter tparam = LookupTypeParameter (t);
2730                 if (tparam != null)
2731                         return tparam.GenericConstraints;
2732
2733                 return ReflectionConstraints.GetConstraints (t);
2734 #else
2735                 throw new InternalErrorException ();
2736 #endif                          
2737         }
2738
2739         public static bool HasGenericArguments (Type t)
2740         {
2741                 return GetNumberOfTypeArguments (t) > 0;
2742         }
2743
2744         public static int GetNumberOfTypeArguments (Type t)
2745         {
2746 #if GMCS_SOURCE
2747                 if (t.IsGenericParameter)
2748                         return 0;
2749                 DeclSpace tc = LookupDeclSpace (t);
2750                 if (tc != null)
2751                         return tc.IsGeneric ? tc.CountTypeParameters : 0;
2752                 else
2753                         return t.IsGenericType ? t.GetGenericArguments ().Length : 0;
2754 #else
2755                 return 0;
2756 #endif
2757         }
2758
2759         /// <summary>
2760         ///   Check whether `type' and `parent' are both instantiations of the same
2761         ///   generic type.  Note that we do not check the type parameters here.
2762         /// </summary>
2763         public static bool IsInstantiationOfSameGenericType (Type type, Type parent)
2764         {
2765                 int tcount = GetNumberOfTypeArguments (type);
2766                 int pcount = GetNumberOfTypeArguments (parent);
2767
2768                 if (tcount != pcount)
2769                         return false;
2770
2771                 type = DropGenericTypeArguments (type);
2772                 parent = DropGenericTypeArguments (parent);
2773
2774                 return type.Equals (parent);
2775         }
2776
2777         /// <summary>
2778         ///   Whether `mb' is a generic method definition.
2779         /// </summary>
2780         public static bool IsGenericMethodDefinition (MethodBase mb)
2781         {
2782 #if GMCS_SOURCE
2783                 if (mb.DeclaringType is TypeBuilder) {
2784                         IMethodData method = (IMethodData) builder_to_method [mb];
2785                         if (method == null)
2786                                 return false;
2787
2788                         return method.GenericMethod != null;
2789                 }
2790
2791                 return mb.IsGenericMethodDefinition;
2792 #else
2793                 return false;
2794 #endif
2795         }
2796
2797         /// <summary>
2798         ///   Whether `mb' is a generic method.
2799         /// </summary>
2800         public static bool IsGenericMethod (MethodBase mb)
2801         {
2802 #if GMCS_SOURCE
2803                 return mb.IsGenericMethod;
2804 #else
2805                 return false;
2806 #endif
2807         }
2808
2809         public static bool IsNullableType (Type t)
2810         {
2811 #if GMCS_SOURCE
2812                 return generic_nullable_type == DropGenericTypeArguments (t);
2813 #else
2814                 return false;
2815 #endif
2816         }
2817
2818         public static bool IsNullableTypeOf (Type t, Type nullable)
2819         {
2820 #if GMCS_SOURCE
2821                 if (!IsNullableType (t))
2822                         return false;
2823
2824                 return GetTypeArguments (t) [0] == nullable;
2825 #else
2826                 return false;
2827 #endif
2828         }
2829
2830         public static bool IsNullableValueType (Type t)
2831         {
2832 #if GMCS_SOURCE
2833                 if (!IsNullableType (t))
2834                         return false;
2835
2836                 return GetTypeArguments (t) [0].IsValueType;
2837 #else
2838                 return false;
2839 #endif
2840         }
2841 #endregion
2842
2843 #region MemberLookup implementation
2844         
2845         //
2846         // Whether we allow private members in the result (since FindMembers
2847         // uses NonPublic for both protected and private), we need to distinguish.
2848         //
2849
2850         internal class Closure {
2851                 internal bool     private_ok;
2852
2853                 // Who is invoking us and which type is being queried currently.
2854                 internal Type     invocation_type;
2855                 internal Type     qualifier_type;
2856
2857                 // The assembly that defines the type is that is calling us
2858                 internal Assembly invocation_assembly;
2859                 internal IList almost_match;
2860
2861                 private bool CheckValidFamilyAccess (bool is_static, MemberInfo m)
2862                 {
2863                         if (invocation_type == null)
2864                                 return false;
2865
2866                         if (is_static && qualifier_type == null)
2867                                 // It resolved from a simple name, so it should be visible.
2868                                 return true;
2869
2870                         if (IsNestedChildOf (invocation_type, m.DeclaringType))
2871                                 return true;
2872
2873                         for (Type t = invocation_type; t != null; t = t.DeclaringType) {
2874                                 if (!IsFamilyAccessible (t, m.DeclaringType))
2875                                         continue;
2876
2877                                 // Although a derived class can access protected members of its base class
2878                                 // it cannot do so through an instance of the base class (CS1540).
2879                                 // => Ancestry should be: declaring_type ->* invocation_type ->*  qualified_type
2880                                 if (is_static || qualifier_type == null ||
2881                                     IsInstantiationOfSameGenericType (t, qualifier_type) ||
2882                                     IsFamilyAccessible (qualifier_type, t))
2883                                         return true;
2884                         }
2885
2886                         if (almost_match != null)
2887                                 almost_match.Add (m);
2888
2889                         return false;
2890                 }
2891                 
2892                 //
2893                 // This filter filters by name + whether it is ok to include private
2894                 // members in the search
2895                 //
2896                 internal bool Filter (MemberInfo m, object filter_criteria)
2897                 {
2898                         //
2899                         // Hack: we know that the filter criteria will always be in the
2900                         // `closure' // fields. 
2901                         //
2902
2903                         if ((filter_criteria != null) && (m.Name != (string) filter_criteria))
2904                                 return false;
2905
2906                         if (((qualifier_type == null) || (qualifier_type == invocation_type)) &&
2907                             (invocation_type != null) &&
2908                             IsPrivateAccessible (m.DeclaringType, invocation_type))
2909                                 return true;
2910
2911                         //
2912                         // Ugly: we need to find out the type of `m', and depending
2913                         // on this, tell whether we accept or not
2914                         //
2915                         if (m is MethodBase){
2916                                 MethodBase mb = (MethodBase) m;
2917                                 MethodAttributes ma = mb.Attributes & MethodAttributes.MemberAccessMask;
2918
2919                                 if (ma == MethodAttributes.Public)
2920                                         return true;
2921
2922                                 if (ma == MethodAttributes.PrivateScope)
2923                                         return false;
2924
2925                                 if (ma == MethodAttributes.Private)
2926                                         return private_ok ||
2927                                                 IsPrivateAccessible (invocation_type, m.DeclaringType) ||
2928                                                 IsNestedChildOf (invocation_type, m.DeclaringType);
2929
2930                                 if (TypeManager.IsThisOrFriendAssembly (mb.DeclaringType.Assembly)) {
2931                                         if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamORAssem)
2932                                                 return true;
2933                                 } else {
2934                                         if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamANDAssem)
2935                                                 return false;
2936                                 }
2937
2938                                 // Family, FamORAssem or FamANDAssem
2939                                 return CheckValidFamilyAccess (mb.IsStatic, m);
2940                         }
2941                         
2942                         if (m is FieldInfo){
2943                                 FieldInfo fi = (FieldInfo) m;
2944                                 FieldAttributes fa = fi.Attributes & FieldAttributes.FieldAccessMask;
2945
2946                                 if (fa == FieldAttributes.Public)
2947                                         return true;
2948
2949                                 if (fa == FieldAttributes.PrivateScope)
2950                                         return false;
2951
2952                                 if (fa == FieldAttributes.Private)
2953                                         return private_ok ||
2954                                                 IsPrivateAccessible (invocation_type, m.DeclaringType) ||
2955                                                 IsNestedChildOf (invocation_type, m.DeclaringType);
2956
2957                                 if (TypeManager.IsThisOrFriendAssembly (fi.DeclaringType.Assembly)) {
2958                                         if ((fa == FieldAttributes.Assembly) ||
2959                                             (fa == FieldAttributes.FamORAssem))
2960                                                 return true;
2961                                 } else {
2962                                         if ((fa == FieldAttributes.Assembly) ||
2963                                             (fa == FieldAttributes.FamANDAssem))
2964                                                 return false;
2965                                 }
2966
2967                                 // Family, FamORAssem or FamANDAssem
2968                                 return CheckValidFamilyAccess (fi.IsStatic, m);
2969                         }
2970
2971                         //
2972                         // EventInfos and PropertyInfos, return true because they lack
2973                         // permission information, so we need to check later on the methods.
2974                         //
2975                         return true;
2976                 }
2977         }
2978
2979         static Closure closure = new Closure ();
2980         static MemberFilter FilterWithClosure_delegate = new MemberFilter (closure.Filter);
2981
2982         //
2983         // Looks up a member called `name' in the `queried_type'.  This lookup
2984         // is done by code that is contained in the definition for `invocation_type'
2985         // through a qualifier of type `qualifier_type' (or null if there is no qualifier).
2986         //
2987         // `invocation_type' is used to check whether we're allowed to access the requested
2988         // member wrt its protection level.
2989         //
2990         // When called from MemberAccess, `qualifier_type' is the type which is used to access
2991         // the requested member (`class B { A a = new A (); a.foo = 5; }'; here invocation_type
2992         // is B and qualifier_type is A).  This is used to do the CS1540 check.
2993         //
2994         // When resolving a SimpleName, `qualifier_type' is null.
2995         //
2996         // The `qualifier_type' is used for the CS1540 check; it's normally either null or
2997         // the same than `queried_type' - except when we're being called from BaseAccess;
2998         // in this case, `invocation_type' is the current type and `queried_type' the base
2999         // type, so this'd normally trigger a CS1540.
3000         //
3001         // The binding flags are `bf' and the kind of members being looked up are `mt'
3002         //
3003         // The return value always includes private members which code in `invocation_type'
3004         // is allowed to access (using the specified `qualifier_type' if given); only use
3005         // BindingFlags.NonPublic to bypass the permission check.
3006         //
3007         // The 'almost_match' argument is used for reporting error CS1540.
3008         //
3009         // Returns an array of a single element for everything but Methods/Constructors
3010         // that might return multiple matches.
3011         //
3012         public static MemberInfo [] MemberLookup (Type invocation_type, Type qualifier_type,
3013                                                   Type queried_type, MemberTypes mt,
3014                                                   BindingFlags original_bf, string name, IList almost_match)
3015         {
3016                 Timer.StartTimer (TimerType.MemberLookup);
3017
3018                 MemberInfo[] retval = RealMemberLookup (invocation_type, qualifier_type,
3019                                                         queried_type, mt, original_bf, name, almost_match);
3020
3021                 Timer.StopTimer (TimerType.MemberLookup);
3022
3023                 return retval;
3024         }
3025
3026         static MemberInfo [] RealMemberLookup (Type invocation_type, Type qualifier_type,
3027                                                Type queried_type, MemberTypes mt,
3028                                                BindingFlags original_bf, string name, IList almost_match)
3029         {
3030                 BindingFlags bf = original_bf;
3031                 
3032                 ArrayList method_list = null;
3033                 Type current_type = queried_type;
3034                 bool searching = (original_bf & BindingFlags.DeclaredOnly) == 0;
3035                 bool skip_iface_check = true, used_cache = false;
3036                 bool always_ok_flag = invocation_type != null && IsNestedChildOf (invocation_type, queried_type);
3037
3038                 closure.invocation_type = invocation_type;
3039                 closure.invocation_assembly = invocation_type != null ? invocation_type.Assembly : null;
3040                 closure.qualifier_type = qualifier_type;
3041                 closure.almost_match = almost_match;
3042
3043                 // This is from the first time we find a method
3044                 // in most cases, we do not actually find a method in the base class
3045                 // so we can just ignore it, and save the arraylist allocation
3046                 MemberInfo [] first_members_list = null;
3047                 bool use_first_members_list = false;
3048                 
3049                 do {
3050                         MemberInfo [] list;
3051
3052                         //
3053                         // `NonPublic' is lame, because it includes both protected and
3054                         // private methods, so we need to control this behavior by
3055                         // explicitly tracking if a private method is ok or not.
3056                         //
3057                         // The possible cases are:
3058                         //    public, private and protected (internal does not come into the
3059                         //    equation)
3060                         //
3061                         if ((invocation_type != null) &&
3062                             ((invocation_type == current_type) ||
3063                              IsNestedChildOf (invocation_type, current_type)) ||
3064                             always_ok_flag)
3065                                 bf = original_bf | BindingFlags.NonPublic;
3066                         else
3067                                 bf = original_bf;
3068
3069                         closure.private_ok = (original_bf & BindingFlags.NonPublic) != 0;
3070
3071                         Timer.StopTimer (TimerType.MemberLookup);
3072
3073                         list = MemberLookup_FindMembers (current_type, mt, bf, name, out used_cache);
3074
3075                         Timer.StartTimer (TimerType.MemberLookup);
3076
3077                         //
3078                         // When queried for an interface type, the cache will automatically check all
3079                         // inherited members, so we don't need to do this here.  However, this only
3080                         // works if we already used the cache in the first iteration of this loop.
3081                         //
3082                         // If we used the cache in any further iteration, we can still terminate the
3083                         // loop since the cache always looks in all base classes.
3084                         //
3085
3086                         if (used_cache)
3087                                 searching = false;
3088                         else
3089                                 skip_iface_check = false;
3090
3091                         if (current_type == TypeManager.object_type)
3092                                 searching = false;
3093                         else {
3094                                 current_type = current_type.BaseType;
3095                                 
3096                                 //
3097                                 // This happens with interfaces, they have a null
3098                                 // basetype.  Look members up in the Object class.
3099                                 //
3100                                 if (current_type == null) {
3101                                         current_type = TypeManager.object_type;
3102                                         searching = true;
3103                                 }
3104                         }
3105                         
3106                         if (list.Length == 0)
3107                                 continue;
3108
3109                         //
3110                         // Events and types are returned by both `static' and `instance'
3111                         // searches, which means that our above FindMembers will
3112                         // return two copies of the same.
3113                         //
3114                         if (list.Length == 1 && !(list [0] is MethodBase)){
3115                                 return list;
3116                         }
3117
3118                         //
3119                         // Multiple properties: we query those just to find out the indexer
3120                         // name
3121                         //
3122                         if (list [0] is PropertyInfo)
3123                                 return list;
3124
3125                         //
3126                         // We found an event: the cache lookup returns both the event and
3127                         // its private field.
3128                         //
3129                         if (list [0] is EventInfo) {
3130                                 if ((list.Length == 2) && (list [1] is FieldInfo))
3131                                         return new MemberInfo [] { list [0] };
3132
3133                                 return list;
3134                         }
3135
3136                         //
3137                         // We found methods, turn the search into "method scan"
3138                         // mode.
3139                         //
3140
3141                         if (first_members_list != null) {
3142                                 if (use_first_members_list) {
3143                                         method_list = CopyNewMethods (method_list, first_members_list);
3144                                         use_first_members_list = false;
3145                                 }
3146                                 
3147                                 method_list = CopyNewMethods (method_list, list);
3148                         } else {
3149                                 first_members_list = list;
3150                                 use_first_members_list = true;
3151                                 mt &= (MemberTypes.Method | MemberTypes.Constructor);
3152                         }
3153                 } while (searching);
3154
3155                 if (use_first_members_list)
3156                         return first_members_list;
3157
3158                 if (method_list != null && method_list.Count > 0) {
3159                         return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
3160                 }
3161                 //
3162                 // This happens if we already used the cache in the first iteration, in this case
3163                 // the cache already looked in all interfaces.
3164                 //
3165                 if (skip_iface_check)
3166                         return null;
3167
3168                 //
3169                 // Interfaces do not list members they inherit, so we have to
3170                 // scan those.
3171                 // 
3172                 if (!queried_type.IsInterface)
3173                         return null;
3174
3175                 if (queried_type.IsArray)
3176                         queried_type = TypeManager.array_type;
3177                 
3178                 Type [] ifaces = GetInterfaces (queried_type);
3179                 if (ifaces == null)
3180                         return null;
3181                 
3182                 foreach (Type itype in ifaces){
3183                         MemberInfo [] x;
3184
3185                         x = MemberLookup (null, null, itype, mt, bf, name, null);
3186                         if (x != null)
3187                                 return x;
3188                 }
3189                                         
3190                 return null;
3191         }
3192
3193         const BindingFlags AllMembers = BindingFlags.Public | BindingFlags.NonPublic |
3194                                                                         BindingFlags.Static | BindingFlags.Instance | 
3195                                                                         BindingFlags.DeclaredOnly;
3196
3197         // Currently is designed to work with external types only
3198         public static PropertyInfo GetPropertyFromAccessor (MethodBase mb)
3199         {
3200                 if (!mb.IsSpecialName)
3201                         return null;
3202
3203                 string name = mb.Name;
3204                 if (name.Length < 5)
3205                         return null;
3206
3207                 if (name [3] != '_')
3208                         return null;
3209
3210                 if (name.StartsWith ("get") || name.StartsWith ("set")) {
3211                         MemberInfo[] pi = mb.DeclaringType.FindMembers (MemberTypes.Property, AllMembers,
3212                                 Type.FilterName, name.Substring (4));
3213
3214                         if (pi == null)
3215                                 return null;
3216
3217                         // This can happen when property is indexer (it can have same name but different parameters)
3218                         foreach (PropertyInfo p in pi) {
3219                                 foreach (MethodInfo p_mi in p.GetAccessors (true)) {
3220                                         if (p_mi == mb || TypeManager.GetParameterData (p_mi).Equals (TypeManager.GetParameterData (mb)))
3221                                                 return p;
3222                                 }
3223                         }
3224                 }
3225
3226                 return null;
3227         }
3228
3229         // Currently is designed to work with external types only
3230         public static MemberInfo GetEventFromAccessor (MethodBase mb)
3231         {
3232                 if (!mb.IsSpecialName)
3233                         return null;
3234
3235                 string name = mb.Name;
3236                 if (name.Length < 5)
3237                         return null;
3238
3239                 if (name.StartsWith ("add_"))
3240                         return mb.DeclaringType.GetEvent (name.Substring (4), AllMembers);
3241
3242                 if (name.StartsWith ("remove_"))
3243                         return mb.DeclaringType.GetEvent (name.Substring (7), AllMembers);
3244
3245                 return null;
3246         }
3247
3248         // Tests whether external method is really special
3249         public static bool IsSpecialMethod (MethodBase mb)
3250         {
3251                 if (!mb.IsSpecialName)
3252                         return false;
3253
3254                 IMethodData md = TypeManager.GetMethod (mb);
3255                 if (md != null) 
3256                         return (md is AbstractPropertyEventMethod || md is Operator);
3257
3258                 PropertyInfo pi = GetPropertyFromAccessor (mb);
3259                 if (pi != null)
3260                         return IsValidProperty (pi);
3261                                 
3262                 if (GetEventFromAccessor (mb) != null)
3263                         return true;
3264
3265                 string name = mb.Name;
3266                 if (name.StartsWith ("op_"))
3267                         return Operator.GetName (name) != null;
3268
3269                 return false;
3270         }
3271
3272         // Tests whether imported property is valid C# property.
3273         // TODO: It seems to me that we should do a lot of sanity tests before
3274         // we accept property as C# property
3275         static bool IsValidProperty (PropertyInfo pi)
3276         {
3277                 MethodInfo get_method = pi.GetGetMethod (true);
3278                 MethodInfo set_method = pi.GetSetMethod (true);
3279                 int g_count = 0;
3280                 int s_count = 0;
3281                 if (get_method != null && set_method != null) {
3282                         g_count = get_method.GetParameters ().Length;
3283                         s_count = set_method.GetParameters ().Length;
3284                         if (g_count + 1 != s_count)
3285                                 return false;
3286                 } else if (get_method != null) {
3287                         g_count = get_method.GetParameters ().Length;
3288                 } else if (set_method != null) {
3289                         s_count = set_method.GetParameters ().Length;
3290                 }
3291
3292                 //
3293                 // DefaultMemberName and indexer name has to match to identify valid C# indexer
3294                 //
3295                 if ((s_count > 1 || g_count > 0) && TypeManager.default_member_type != null) {
3296                         object[] o = pi.DeclaringType.GetCustomAttributes (TypeManager.default_member_type, false);
3297                         if (o.Length == 0)
3298                                 return false;
3299                         
3300                         DefaultMemberAttribute dma = (DefaultMemberAttribute) o [0];
3301                         if (dma.MemberName != pi.Name)
3302                                 return false;
3303                         if (get_method != null && "get_" + dma.MemberName != get_method.Name)
3304                                 return false;
3305                         if (set_method != null && "set_" + dma.MemberName != set_method.Name)
3306                                 return false;
3307                 }
3308
3309                 return true;
3310         }
3311
3312 #endregion
3313         
3314 }
3315
3316 /// <summary>
3317 ///   There is exactly one instance of this class per type.
3318 /// </summary>
3319 public sealed class TypeHandle : IMemberContainer {
3320         public readonly IMemberContainer BaseType;
3321
3322         readonly int id = ++next_id;
3323         static int next_id = 0;
3324
3325         static TypeHandle ()
3326         {
3327                 Reset ();
3328         }
3329
3330         /// <summary>
3331         ///   Lookup a TypeHandle instance for the given type.  If the type doesn't have
3332         ///   a TypeHandle yet, a new instance of it is created.  This static method
3333         ///   ensures that we'll only have one TypeHandle instance per type.
3334         /// </summary>
3335         private static TypeHandle GetTypeHandle (Type t)
3336         {
3337                 TypeHandle handle = (TypeHandle) type_hash [t];
3338                 if (handle != null)
3339                         return handle;
3340
3341                 handle = new TypeHandle (t);
3342                 type_hash.Add (t, handle);
3343                 return handle;
3344         }
3345
3346         public static MemberCache GetMemberCache (Type t)
3347         {
3348                 return GetTypeHandle (t).MemberCache;
3349         }
3350         
3351         public static void CleanUp ()
3352         {
3353                 type_hash = null;
3354         }
3355
3356         public static void Reset ()
3357         {
3358                 type_hash = new PtrHashtable ();
3359         }
3360
3361         /// <summary>
3362         ///   Returns the TypeHandle for TypeManager.object_type.
3363         /// </summary>
3364         public static IMemberContainer ObjectType {
3365                 get {
3366                         if (object_type != null)
3367                                 return object_type;
3368
3369                         object_type = GetTypeHandle (TypeManager.object_type);
3370
3371                         return object_type;
3372                 }
3373         }
3374
3375         /// <summary>
3376         ///   Returns the TypeHandle for TypeManager.array_type.
3377         /// </summary>
3378         public static TypeHandle ArrayType {
3379                 get {
3380                         if (array_type != null)
3381                                 return array_type;
3382
3383                         array_type = GetTypeHandle (TypeManager.array_type);
3384
3385                         return array_type;
3386                 }
3387         }
3388
3389         private static PtrHashtable type_hash;
3390
3391         private static TypeHandle object_type = null;
3392         private static TypeHandle array_type = null;
3393
3394         private Type type;
3395         private string full_name;
3396         private bool is_interface;
3397         private MemberCache member_cache;
3398         private MemberCache base_cache;
3399
3400         private TypeHandle (Type type)
3401         {
3402                 this.type = type;
3403                 full_name = type.FullName != null ? type.FullName : type.Name;
3404                 if (type.BaseType != null) {
3405                         base_cache = TypeManager.LookupMemberCache (type.BaseType);
3406                         BaseType = base_cache.Container;
3407                 } else if (type.IsInterface)
3408                         base_cache = TypeManager.LookupBaseInterfacesCache (type);
3409                 this.is_interface = type.IsInterface || TypeManager.IsGenericParameter (type);
3410                 this.member_cache = new MemberCache (this);
3411         }
3412
3413         // IMemberContainer methods
3414
3415         public string Name {
3416                 get {
3417                         return full_name;
3418                 }
3419         }
3420
3421         public Type Type {
3422                 get {
3423                         return type;
3424                 }
3425         }
3426
3427         public MemberCache BaseCache {
3428                 get {
3429                         return base_cache;
3430                 }
3431         }
3432
3433         public bool IsInterface {
3434                 get {
3435                         return is_interface;
3436                 }
3437         }
3438
3439         public MemberList GetMembers (MemberTypes mt, BindingFlags bf)
3440         {
3441                 MemberInfo [] members;
3442
3443 #if GMCS_SOURCE
3444                 if (type is GenericTypeParameterBuilder)
3445                         return MemberList.Empty;
3446 #endif
3447
3448                 if (mt == MemberTypes.Event)
3449                         members = type.GetEvents (bf | BindingFlags.DeclaredOnly);
3450                 else
3451                         members = type.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
3452                                                                                 null, null);
3453
3454                 if (members.Length == 0)
3455                         return MemberList.Empty;
3456
3457                 Array.Reverse (members);
3458                 return new MemberList (members);
3459         }
3460
3461         // IMemberFinder methods
3462
3463         public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
3464                                        MemberFilter filter, object criteria)
3465         {
3466                 return new MemberList (member_cache.FindMembers (mt, bf, name, filter, criteria));
3467         }
3468
3469         public MemberCache MemberCache {
3470                 get {
3471                         return member_cache;
3472                 }
3473         }
3474
3475         public override string ToString ()
3476         {
3477                 if (BaseType != null)
3478                         return "TypeHandle (" + id + "," + Name + " : " + BaseType + ")";
3479                 else
3480                         return "TypeHandle (" + id + "," + Name + ")";
3481         }
3482 }
3483 }