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