833cc0378603b0cdf3f15dc8bbabd37e43918ea0
[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 //
7 // Licensed under the terms of the GNU GPL
8 //
9 // (C) 2001 Ximian, Inc (http://www.ximian.com)
10 //
11 //
12
13 //
14 // We will eventually remove the SIMPLE_SPEEDUP, and should never change 
15 // the behavior of the compilation.  This can be removed if we rework
16 // the code to get a list of namespaces available.
17 //
18 #define SIMPLE_SPEEDUP
19
20 using System;
21 using System.IO;
22 using System.Globalization;
23 using System.Collections;
24 using System.Reflection;
25 using System.Reflection.Emit;
26 using System.Text;
27 using System.Text.RegularExpressions;
28 using System.Runtime.CompilerServices;
29 using System.Diagnostics;
30
31 namespace Mono.CSharp {
32
33 public class TypeManager {
34         //
35         // A list of core types that the compiler requires or uses
36         //
37         static public Type object_type;
38         static public Type value_type;
39         static public Type string_type;
40         static public Type int32_type;
41         static public Type uint32_type;
42         static public Type int64_type;
43         static public Type uint64_type;
44         static public Type float_type;
45         static public Type double_type;
46         static public Type char_type;
47         static public Type char_ptr_type;
48         static public Type short_type;
49         static public Type decimal_type;
50         static public Type bool_type;
51         static public Type sbyte_type;
52         static public Type byte_type;
53         static public Type ushort_type;
54         static public Type enum_type;
55         static public Type delegate_type;
56         static public Type multicast_delegate_type;
57         static public Type void_type;
58         static public Type null_type;
59         static public Type enumeration_type;
60         static public Type array_type;
61         static public Type runtime_handle_type;
62         static public Type icloneable_type;
63         static public Type type_type;
64         static public Type ienumerator_type;
65         static public Type ienumerable_type;
66         static public Type idisposable_type;
67         static public Type iconvertible_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 monitor_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 unverifiable_code_type;
80         static public Type methodimpl_attr_type;
81         static public Type marshal_as_attr_type;
82         static public Type param_array_type;
83         static public Type void_ptr_type;
84         static public Type indexer_name_type;
85         static public Type exception_type;
86         static public Type invalid_operation_exception_type;
87         static public Type not_supported_exception_type;
88         static public Type obsolete_attribute_type;
89         static public Type conditional_attribute_type;
90         static public Type in_attribute_type;
91         static public Type out_attribute_type;
92         static public Type anonymous_method_type;
93         static public Type cls_compliant_attribute_type;
94         static public Type typed_reference_type;
95         static public Type arg_iterator_type;
96         static public Type mbr_type;
97         static public Type struct_layout_attribute_type;
98         static public Type field_offset_attribute_type;
99         static public Type security_attr_type;
100         static public Type required_attr_type;
101
102         /// 
103         /// .NET 2.0
104         ///
105 #if NET_2_0
106         static internal Type compiler_generated_attr_type;
107         static internal Type fixed_buffer_attr_type;
108         static internal Type default_charset_type;
109 #endif
110
111         //
112         // An empty array of types
113         //
114         static public Type [] NoTypes;
115         static public TypeExpr [] NoTypeExprs;
116
117
118         // 
119         // Expressions representing the internal types.  Used during declaration
120         // definition.
121         //
122         static public TypeExpr system_object_expr, system_string_expr; 
123         static public TypeExpr system_boolean_expr, system_decimal_expr;
124         static public TypeExpr system_single_expr, system_double_expr;
125         static public TypeExpr system_sbyte_expr, system_byte_expr;
126         static public TypeExpr system_int16_expr, system_uint16_expr;
127         static public TypeExpr system_int32_expr, system_uint32_expr;
128         static public TypeExpr system_int64_expr, system_uint64_expr;
129         static public TypeExpr system_char_expr, system_void_expr;
130         static public TypeExpr system_asynccallback_expr;
131         static public TypeExpr system_iasyncresult_expr;
132         static public TypeExpr system_valuetype_expr;
133         static public TypeExpr system_intptr_expr;
134
135         //
136         // This is only used when compiling corlib
137         //
138         static public Type system_int32_type;
139         static public Type system_array_type;
140         static public Type system_type_type;
141         static public Type system_assemblybuilder_type;
142         static public MethodInfo system_int_array_get_length;
143         static public MethodInfo system_int_array_get_rank;
144         static public MethodInfo system_object_array_clone;
145         static public MethodInfo system_int_array_get_length_int;
146         static public MethodInfo system_int_array_get_lower_bound_int;
147         static public MethodInfo system_int_array_get_upper_bound_int;
148         static public MethodInfo system_void_array_copyto_array_int;
149
150         
151         //
152         // Internal, not really used outside
153         //
154         static Type runtime_helpers_type;
155         
156         //
157         // These methods are called by code generated by the compiler
158         //
159         static public MethodInfo string_concat_string_string;
160         static public MethodInfo string_concat_string_string_string;
161         static public MethodInfo string_concat_string_string_string_string;
162         static public MethodInfo string_concat_string_dot_dot_dot;
163         static public MethodInfo string_concat_object_object;
164         static public MethodInfo string_concat_object_object_object;
165         static public MethodInfo string_concat_object_dot_dot_dot;
166         static public MethodInfo string_isinterneted_string;
167         static public MethodInfo system_type_get_type_from_handle;
168         static public MethodInfo object_getcurrent_void;
169         static public MethodInfo bool_movenext_void;
170         static public MethodInfo ienumerable_getenumerator_void;
171         static public MethodInfo void_reset_void;
172         static public MethodInfo void_dispose_void;
173         static public MethodInfo void_monitor_enter_object;
174         static public MethodInfo void_monitor_exit_object;
175         static public MethodInfo void_initializearray_array_fieldhandle;
176         static public MethodInfo int_getlength_int;
177         static public MethodInfo delegate_combine_delegate_delegate;
178         static public MethodInfo delegate_remove_delegate_delegate;
179         static public MethodInfo int_get_offset_to_string_data;
180         static public MethodInfo int_array_get_length;
181         static public MethodInfo int_array_get_rank;
182         static public MethodInfo object_array_clone;
183         static public MethodInfo int_array_get_length_int;
184         static public MethodInfo int_array_get_lower_bound_int;
185         static public MethodInfo int_array_get_upper_bound_int;
186         static public MethodInfo void_array_copyto_array_int;
187         
188         //
189         // The attribute constructors.
190         //
191         static public ConstructorInfo object_ctor;
192         static public ConstructorInfo cons_param_array_attribute;
193         static public ConstructorInfo void_decimal_ctor_five_args;
194         static public ConstructorInfo void_decimal_ctor_int_arg;
195         static public ConstructorInfo unverifiable_code_ctor;
196         static public ConstructorInfo default_member_ctor;
197         static public ConstructorInfo decimal_constant_attribute_ctor;
198         static internal ConstructorInfo struct_layout_attribute_ctor;
199         static public ConstructorInfo field_offset_attribute_ctor;
200         
201         ///
202         /// A new in C# 2.0
203         /// 
204 #if NET_2_0
205         static internal CustomAttributeBuilder compiler_generated_attr;
206         static internal ConstructorInfo fixed_buffer_attr_ctor;
207 #endif
208
209         // <remarks>
210         //   Holds the Array of Assemblies that have been loaded
211         //   (either because it is the default or the user used the
212         //   -r command line option)
213         // </remarks>
214         static Assembly [] assemblies;
215
216         // <remarks>
217         //  Keeps a list of modules. We used this to do lookups
218         //  on the module using GetType -- needed for arrays
219         // </remarks>
220         static Module [] modules;
221
222         // <remarks>
223         //   This is the type_cache from the assemblies to avoid
224         //   hitting System.Reflection on every lookup.
225         // </summary>
226         static Hashtable types;
227
228         // <remarks>
229         //  This is used to hotld the corresponding TypeContainer objects
230         //  since we need this in FindMembers
231         // </remarks>
232         static Hashtable typecontainers;
233
234         // <remarks>
235         //   Keeps track of those types that are defined by the
236         //   user's program
237         // </remarks>
238         static ArrayList user_types;
239
240         static PtrHashtable builder_to_declspace;
241
242         static PtrHashtable builder_to_member_cache;
243
244         // <remarks>
245         //   Tracks the interfaces implemented by typebuilders.  We only
246         //   enter those who do implement or or more interfaces
247         // </remarks>
248         static PtrHashtable builder_to_ifaces;
249
250         // <remarks>
251         //   Maps MethodBase.RuntimeTypeHandle to a Type array that contains
252         //   the arguments to the method
253         // </remarks>
254         static Hashtable method_arguments;
255
256         // <remarks>
257         //   Maps PropertyBuilder to a Type array that contains
258         //   the arguments to the indexer
259         // </remarks>
260         static Hashtable indexer_arguments;
261
262         // <remarks>
263         //   Maps a MethodBase to its ParameterData (either InternalParameters or ReflectionParameters)
264         // <remarks>
265         static Hashtable method_params;
266
267         // <remarks>
268         //  A hash table from override methods to their base virtual method.
269         // <remarks>
270         static Hashtable method_overrides;
271
272         // <remarks>
273         //  Keeps track of methods
274         // </remarks>
275
276         static Hashtable builder_to_method;
277
278         // <remarks>
279         //  Contains all public types from referenced assemblies.
280         //  This member is used only if CLS Compliance verification is required.
281         // </remarks>
282         public static Hashtable all_imported_types;
283
284         static Hashtable fieldbuilders_to_fields;
285         static Hashtable fields;
286
287         struct Signature {
288                 public string name;
289                 public Type [] args;
290         }
291         
292         public static void CleanUp ()
293         {
294                 // Lets get everything clean so that we can collect before generating code
295                 assemblies = null;
296                 modules = null;
297                 types = null;
298                 typecontainers = null;
299                 user_types = null;
300                 builder_to_declspace = null;
301                 builder_to_member_cache = null;
302                 builder_to_ifaces = null;
303                 method_arguments = null;
304                 indexer_arguments = null;
305                 method_params = null;
306                 builder_to_method = null;
307                 
308                 fields = null;
309                 builder_to_constant = null;
310                 fieldbuilders_to_fields = null;
311                 events = null;
312                 priv_fields_events = null;
313                 properties = null;
314                 type_hash = null;
315                 
316                 TypeHandle.CleanUp ();
317         }
318
319         /// <summary>
320         ///   A filter for Findmembers that uses the Signature object to
321         ///   extract objects
322         /// </summary>
323         static bool SignatureFilter (MemberInfo mi, object criteria)
324         {
325                 Signature sig = (Signature) criteria;
326
327                 if (!(mi is MethodBase))
328                         return false;
329                 
330                 if (mi.Name != sig.name)
331                         return false;
332
333                 int count = sig.args.Length;
334                 
335                 if (mi is MethodBuilder || mi is ConstructorBuilder){
336                         Type [] candidate_args = GetArgumentTypes ((MethodBase) mi);
337
338                         if (candidate_args.Length != count)
339                                 return false;
340                         
341                         for (int i = 0; i < count; i++)
342                                 if (candidate_args [i] != sig.args [i])
343                                         return false;
344                         
345                         return true;
346                 } else {
347                         ParameterInfo [] pars = ((MethodBase) mi).GetParameters ();
348
349                         if (pars.Length != count)
350                                 return false;
351
352                         for (int i = 0; i < count; i++)
353                                 if (pars [i].ParameterType != sig.args [i])
354                                         return false;
355                         return true;
356                 }
357         }
358
359         // A delegate that points to the filter above.
360         static MemberFilter signature_filter;
361
362         //
363         // These are expressions that represent some of the internal data types, used
364         // elsewhere
365         //
366         static void InitExpressionTypes ()
367         {
368                 system_object_expr  = new TypeLookupExpression ("System.Object");
369                 system_string_expr  = new TypeLookupExpression ("System.String");
370                 system_boolean_expr = new TypeLookupExpression ("System.Boolean");
371                 system_decimal_expr = new TypeLookupExpression ("System.Decimal");
372                 system_single_expr  = new TypeLookupExpression ("System.Single");
373                 system_double_expr  = new TypeLookupExpression ("System.Double");
374                 system_sbyte_expr   = new TypeLookupExpression ("System.SByte");
375                 system_byte_expr    = new TypeLookupExpression ("System.Byte");
376                 system_int16_expr   = new TypeLookupExpression ("System.Int16");
377                 system_uint16_expr  = new TypeLookupExpression ("System.UInt16");
378                 system_int32_expr   = new TypeLookupExpression ("System.Int32");
379                 system_uint32_expr  = new TypeLookupExpression ("System.UInt32");
380                 system_int64_expr   = new TypeLookupExpression ("System.Int64");
381                 system_uint64_expr  = new TypeLookupExpression ("System.UInt64");
382                 system_char_expr    = new TypeLookupExpression ("System.Char");
383                 system_void_expr    = new TypeLookupExpression ("System.Void");
384                 system_asynccallback_expr = new TypeLookupExpression ("System.AsyncCallback");
385                 system_iasyncresult_expr = new TypeLookupExpression ("System.IAsyncResult");
386                 system_valuetype_expr  = new TypeLookupExpression ("System.ValueType");
387                 system_intptr_expr  = new TypeLookupExpression ("System.IntPtr");
388         }
389
390         static TypeManager ()
391         {
392                 Reset ();
393
394                 signature_filter = new MemberFilter (SignatureFilter);
395                 InitExpressionTypes ();
396         }
397
398         static public void Reset ()
399         {
400                 assemblies = new Assembly [0];
401                 modules = null;
402                 user_types = new ArrayList ();
403                 
404                 types = new Hashtable ();
405                 typecontainers = new Hashtable ();
406                 
407                 builder_to_declspace = new PtrHashtable ();
408                 builder_to_member_cache = new PtrHashtable ();
409                 builder_to_method = new PtrHashtable ();
410                 method_arguments = new PtrHashtable ();
411                 method_params = new PtrHashtable ();
412                 method_overrides = new PtrHashtable ();
413                 indexer_arguments = new PtrHashtable ();
414                 builder_to_ifaces = new PtrHashtable ();
415                 
416                 NoTypes = new Type [0];
417                 NoTypeExprs = new TypeExpr [0];
418
419                 fieldbuilders_to_fields = new Hashtable ();
420                 fields = new Hashtable ();
421                 type_hash = new DoubleHash ();
422         }
423
424         public static void HandleDuplicate (string name, Type t)
425         {
426                 Type prev = (Type) types [name];
427                 TypeContainer tc = builder_to_declspace [prev] as TypeContainer;
428                 
429                 if (tc != null){
430                         //
431                         // This probably never happens, as we catch this before
432                         //
433                         Report.Error (-17, "The type `" + name + "' has already been defined.");
434                         return;
435                 }
436                 
437                 tc = builder_to_declspace [t] as TypeContainer;
438                 if (tc != null){
439                         Report.Warning (
440                                         1595, "The type `" + name + "' is defined in an existing assembly;"+
441                                         " Using the new definition from: " + tc.Location);
442                 } else {
443                         Report.Warning (
444                                         1595, "The type `" + name + "' is defined in an existing assembly;");
445                 }
446                 
447                 Report.Warning (1595, "Previously defined in: " + prev.Assembly.FullName);
448                 
449                 types.Remove (name);
450                 types.Add (name, t);
451         }
452         
453         public static void AddUserType (string name, TypeBuilder t)
454         {
455                 try {
456                         types.Add (name, t);
457                 } catch {
458                         HandleDuplicate (name, t); 
459                 }
460
461                 user_types.Add (t);
462         }
463
464         //
465         // This entry point is used by types that we define under the covers
466         // 
467         public static void RegisterBuilder (Type tb, Type [] ifaces)
468         {
469                 if (ifaces != null)
470                         builder_to_ifaces [tb] = ifaces;
471         }
472         
473         public static void AddUserType (string name, TypeBuilder t, TypeContainer tc)
474         {
475                 builder_to_declspace.Add (t, tc);
476                 typecontainers.Add (name, tc);
477                 AddUserType (name, t);
478         }
479
480         public static void AddDelegateType (string name, TypeBuilder t, Delegate del)
481         {
482                 try {
483                         types.Add (name, t);
484                 } catch {
485                         HandleDuplicate (name, t);
486                 }
487                 
488                 builder_to_declspace.Add (t, del);
489         }
490         
491         public static void AddEnumType (string name, TypeBuilder t, Enum en)
492         {
493                 try {
494                         types.Add (name, t);
495                 } catch {
496                         HandleDuplicate (name, t);
497                 }
498                 builder_to_declspace.Add (t, en);
499         }
500
501         public static void AddMethod (MethodBase builder, IMethodData method)
502         {
503                 builder_to_method.Add (builder, method);
504         }
505
506         public static IMethodData GetMethod (MethodBase builder)
507         {
508                 return (IMethodData) builder_to_method [builder];
509         }
510
511         /// <summary>
512         ///   Returns the DeclSpace whose Type is `t' or null if there is no
513         ///   DeclSpace for `t' (ie, the Type comes from a library)
514         /// </summary>
515         public static DeclSpace LookupDeclSpace (Type t)
516         {
517                 return builder_to_declspace [t] as DeclSpace;
518         }
519
520         /// <summary>
521         ///   Returns the TypeContainer whose Type is `t' or null if there is no
522         ///   TypeContainer for `t' (ie, the Type comes from a library)
523         /// </summary>
524         public static TypeContainer LookupTypeContainer (Type t)
525         {
526                 return builder_to_declspace [t] as TypeContainer;
527         }
528
529         public static MemberCache LookupMemberCache (Type t)
530         {
531                 if (t is TypeBuilder) {
532                         IMemberContainer container = builder_to_declspace [t] as IMemberContainer;
533                         if (container != null)
534                                 return container.MemberCache;
535                 }
536
537                 return TypeHandle.GetMemberCache (t);
538         }
539
540         public static MemberCache LookupBaseInterfacesCache (Type t)
541         {
542                 Type [] ifaces = t.GetInterfaces ();
543
544                 if (ifaces != null && ifaces.Length == 1)
545                         return LookupMemberCache (ifaces [0]);
546
547                 // TODO: the builder_to_member_cache should be indexed by 'ifaces', not 't'
548                 MemberCache cache = builder_to_member_cache [t] as MemberCache;
549                 if (cache != null)
550                         return cache;
551
552                 cache = new MemberCache (ifaces);
553                 builder_to_member_cache.Add (t, cache);
554                 return cache;
555         }
556
557         public static TypeContainer LookupInterface (Type t)
558         {
559                 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
560                 if ((tc == null) || (tc.Kind != Kind.Interface))
561                         return null;
562
563                 return tc;
564         }
565
566         public static Delegate LookupDelegate (Type t)
567         {
568                 return builder_to_declspace [t] as Delegate;
569         }
570
571         public static Enum LookupEnum (Type t)
572         {
573                 return builder_to_declspace [t] as Enum;
574         }
575
576         public static Class LookupClass (Type t)
577         {
578                 return (Class) builder_to_declspace [t];
579         }
580         
581         /// <summary>
582         ///   Registers an assembly to load types from.
583         /// </summary>
584         public static void AddAssembly (Assembly a)
585         {
586                 foreach (Assembly assembly in assemblies) {
587                         if (a == assembly)
588                                 return;
589                 }
590
591                 int top = assemblies.Length;
592                 Assembly [] n = new Assembly [top + 1];
593
594                 assemblies.CopyTo (n, 0);
595                 
596                 n [top] = a;
597                 assemblies = n;
598         }
599
600         public static Assembly [] GetAssemblies ()
601         {
602                 return assemblies;
603         }
604
605         /// <summary>
606         ///  Registers a module builder to lookup types from
607         /// </summary>
608         public static void AddModule (Module mb)
609         {
610                 int top = modules != null ? modules.Length : 0;
611                 Module [] n = new Module [top + 1];
612
613                 if (modules != null)
614                         modules.CopyTo (n, 0);
615                 n [top] = mb;
616                 modules = n;
617         }
618
619         public static Module[] Modules {
620                 get {
621                         return modules;
622                 }
623         }
624
625         //
626         // We use this hash for multiple kinds of constructed types:
627         //
628         //    (T, "&")  Given T, get T &
629         //    (T, "*")  Given T, get T *
630         //    (T, "[]") Given T and a array dimension, get T []
631         //    (T, X)    Given a type T and a simple name X, get the type T+X
632         //
633         // Accessibility tests, if necessary, should be done by the user
634         //
635         static DoubleHash type_hash = new DoubleHash ();
636
637         //
638         // Gets the reference to T version of the Type (T&)
639         //
640         public static Type GetReferenceType (Type t)
641         {
642                 return GetConstructedType (t, "&");
643         }
644
645         //
646         // Gets the pointer to T version of the Type  (T*)
647         //
648         public static Type GetPointerType (Type t)
649         {
650                 return GetConstructedType (t, "*");
651         }
652
653         public static Type GetConstructedType (Type t, string dim)
654         {
655                 object ret = null;
656                 if (!type_hash.Lookup (t, dim, out ret)) {
657                         ret = t.Module.GetType (t.ToString () + dim);
658                         type_hash.Insert (t, dim, ret);
659                 }
660                 return (Type) ret;
661         }
662
663         public static Type GetNestedType (Type t, string name)
664         {
665                 object ret = null;
666                 if (!type_hash.Lookup (t, name, out ret)) {
667                         string lookup = t.ToString () + "+" + name;
668                         ret = t.Module.GetType (lookup);
669                         type_hash.Insert (t, name, ret);
670                 }
671                 return (Type) ret;
672         }
673         
674         //
675         // Low-level lookup, cache-less
676         //
677         public static Type LookupTypeReflection (string name)
678         {
679                 Type t;
680
681                 foreach (Assembly a in assemblies){
682                         t = a.GetType (name);
683                         if (t == null)
684                                 continue;
685
686                         do {
687                                 TypeAttributes ta = t.Attributes & TypeAttributes.VisibilityMask;
688                                 if (ta == TypeAttributes.NotPublic ||
689                                     ta == TypeAttributes.NestedPrivate ||
690                                     ta == TypeAttributes.NestedAssembly ||
691                                     ta == TypeAttributes.NestedFamANDAssem){
692                                         
693                                         //
694                                         // In .NET pointers turn out to be private, even if their
695                                         // element type is not
696                                         //
697                                         if (t.IsPointer){
698                                                 t = t.GetElementType ();
699                                                 continue;
700                                         } else
701                                                 t = null;
702                                 } else {
703                                         return t;
704                                 }
705                         } while (t != null);
706                 }
707
708                 foreach (Module mb in modules) {
709                         t = mb.GetType (name);
710                         if (t != null) 
711                                 return t;
712                 }
713                         
714                 return null;
715         }
716
717         /// <summary>
718         ///   Computes the namespaces that we import from the assemblies we reference.
719         /// </summary>
720         public static void ComputeNamespaces ()
721         {
722                 MethodInfo assembly_get_namespaces = typeof (Assembly).GetMethod ("GetNamespaces", BindingFlags.Instance|BindingFlags.NonPublic);
723
724                 Hashtable cache = null;
725
726                 //
727                 // First add the assembly namespaces
728                 //
729                 if (assembly_get_namespaces != null){
730                         int count = assemblies.Length;
731
732                         for (int i = 0; i < count; i++){
733                                 Assembly a = assemblies [i];
734                                 string [] namespaces = (string []) assembly_get_namespaces.Invoke (a, null);
735                                 foreach (string ns in namespaces){
736                                         if (ns == "")
737                                                 continue;
738                                         Namespace.LookupNamespace (ns, true);
739                                 }
740                         }
741                 } else {
742                         cache = new Hashtable ();
743                         cache.Add ("", null);
744                         foreach (Assembly a in assemblies) {
745                                 foreach (Type t in a.GetExportedTypes ()) {
746                                         string ns = t.Namespace;
747                                         if (ns == null || cache.Contains (ns))
748                                                 continue;
749
750                                         Namespace.LookupNamespace (ns, true);
751                                         cache.Add (ns, null);
752                                 }
753                         }
754                 }
755
756                 //
757                 // Then add module namespaces
758                 //
759                 foreach (Module m in modules) {
760                         if (m == CodeGen.Module.Builder)
761                                 continue;
762                         if (cache == null) {
763                                 cache = new Hashtable ();
764                                 cache.Add ("", null);
765                         }
766                         foreach (Type t in m.GetTypes ()) {
767                                 string ns = t.Namespace;
768                                 if (ns == null || cache.Contains (ns))
769                                         continue;
770                                 Namespace.LookupNamespace (ns, true);
771                                 cache.Add (ns, null);
772                         }
773                 }
774         }
775
776         /// <summary>
777         /// Fills static table with exported types from all referenced assemblies.
778         /// This information is required for CLS Compliance tests.
779         /// </summary>
780         public static void LoadAllImportedTypes ()
781         {
782                 all_imported_types = new Hashtable ();
783                 foreach (Assembly a in assemblies) {
784                         foreach (Type t in a.GetExportedTypes ()) {
785                                 all_imported_types [t.FullName] = t;
786                         }
787                 }
788         }
789
790         public static bool NamespaceClash (string name, Location loc)
791         {
792                 if (Namespace.LookupNamespace (name, false) == null)
793                         return false;
794
795                 Report.Error (519, loc, String.Format ("`{0}' clashes with a predefined namespace", name));
796                 return true;
797         }
798
799         /// <summary>
800         ///   Returns the C# name of a type if possible, or the full type name otherwise
801         /// </summary>
802         static public string CSharpName (Type t)
803         {
804                 return Regex.Replace (t.FullName, 
805                         @"^System\." +
806                         @"(Int32|UInt32|Int16|UInt16|Int64|UInt64|" +
807                         @"Single|Double|Char|Decimal|Byte|SByte|Object|" +
808                         @"Boolean|String|Void|Null)" +
809                         @"(\W+|\b)", 
810                         new MatchEvaluator (CSharpNameMatch)).Replace ('+', '.');
811         }       
812
813         static public string CSharpName (Type[] types)
814         {
815                 StringBuilder sb = new StringBuilder ();
816                 foreach (Type t in types) {
817                         sb.Append (CSharpName (t));
818                         sb.Append (',');
819                 }
820                 sb.Remove (sb.Length - 1, 1);
821                 return sb.ToString ();
822         }
823         
824         static String CSharpNameMatch (Match match) 
825         {
826                 string s = match.Groups [1].Captures [0].Value;
827                 return s.ToLower ().
828                 Replace ("int32", "int").
829                 Replace ("uint32", "uint").
830                 Replace ("int16", "short").
831                 Replace ("uint16", "ushort").
832                 Replace ("int64", "long").
833                 Replace ("uint64", "ulong").
834                 Replace ("single", "float").
835                 Replace ("boolean", "bool")
836                 + match.Groups [2].Captures [0].Value;
837         }
838
839         /// <summary>
840         ///  Returns the signature of the method with full namespace classification
841         /// </summary>
842         static public string GetFullNameSignature (MemberInfo mi)
843         {
844                 // Unfortunately, there's no dynamic dispatch on the arguments of a function.
845                 return (mi is MethodBase)
846                         ? GetFullNameSignature (mi as MethodBase) 
847                         : mi.DeclaringType.FullName.Replace ('+', '.') + '.' + mi.Name;
848         }
849
850         static public string GetFullNameSignature (MethodBase mb)
851         {
852                 string name = mb.Name;
853                 if (name == ".ctor")
854                         name = mb.DeclaringType.Name;
855
856                 if (mb.IsSpecialName) {
857                         if (name.StartsWith ("get_") || name.StartsWith ("set_")) {
858                                 name = name.Remove (0, 4);
859                         }
860
861                         if (name == "Item")
862                                 name = "this";
863                 }
864
865                 return mb.DeclaringType.FullName.Replace ('+', '.') + '.' + name;
866         }
867
868         /// <summary>
869         ///   Returns the signature of the property and indexer
870         /// </summary>
871         static public string CSharpSignature (PropertyBuilder pb, bool is_indexer) 
872         {
873                 if (!is_indexer) {
874                         return GetFullNameSignature (pb);
875                 }
876
877                 MethodBase mb = pb.GetSetMethod (true) != null ? pb.GetSetMethod (true) : pb.GetGetMethod (true);
878                 string signature = GetFullNameSignature (mb);
879                 string arg = GetParameterData (mb).ParameterDesc (0);
880                 return String.Format ("{0}.this[{1}]", signature.Substring (0, signature.LastIndexOf ('.')), arg);
881         }
882
883         /// <summary>
884         ///   Returns the signature of the method
885         /// </summary>
886         static public string CSharpSignature (MethodBase mb)
887         {
888                 StringBuilder sig = new StringBuilder ("(");
889
890                 ParameterData iparams = GetParameterData (mb);
891
892                 // Is property
893                 if (mb.IsSpecialName && iparams.Count == 0 && !mb.IsConstructor)
894                         return GetFullNameSignature (mb);
895                 
896                 for (int i = 0; i < iparams.Count; i++) {
897                         if (i > 0) {
898                                 sig.Append (", ");
899                         }
900                         sig.Append (iparams.ParameterDesc (i));
901                 }
902                 sig.Append (")");
903
904                 // Is indexer
905                 if (mb.IsSpecialName && iparams.Count == 1 && !mb.IsConstructor) {
906                         sig.Replace ('(', '[');
907                         sig.Replace (')', ']');
908                 }
909
910                 return GetFullNameSignature (mb) + sig.ToString ();
911         }
912
913         /// <summary>
914         ///   Looks up a type, and aborts if it is not found.  This is used
915         ///   by types required by the compiler
916         /// </summary>
917         static Type CoreLookupType (string name)
918         {
919                 Type t = null;
920                 if (types.Contains (name))
921                         t = (Type) types [name];
922                 else
923                         t = LookupTypeReflection (name);
924
925                 if (t == null)
926                         Report.Error (518, "The predefined type `" + name + "' is not defined or imported");
927
928                 types [name] = t;
929                 return t;
930         }
931
932         /// <summary>
933         ///   Returns the MethodInfo for a method named `name' defined
934         ///   in type `t' which takes arguments of types `args'
935         /// </summary>
936         static MethodInfo GetMethod (Type t, string name, Type [] args, bool is_private, bool report_errors)
937         {
938                 MemberList list;
939                 Signature sig;
940                 BindingFlags flags = instance_and_static | BindingFlags.Public;
941
942                 sig.name = name;
943                 sig.args = args;
944
945                 if (is_private)
946                         flags |= BindingFlags.NonPublic;
947
948                 list = FindMembers (t, MemberTypes.Method, flags, signature_filter, sig);
949                 if (list.Count == 0) {
950                         if (report_errors)
951                                 Report.Error (-19, "Can not find the core function `" + name + "'");
952                         return null;
953                 }
954
955                 MethodInfo mi = list [0] as MethodInfo;
956                 if (mi == null) {
957                         if (report_errors)
958                                 Report.Error (-19, "Can not find the core function `" + name + "'");
959                         return null;
960                 }
961
962                 return mi;
963         }
964
965         static MethodInfo GetMethod (Type t, string name, Type [] args, bool report_errors)
966         {
967                 return GetMethod (t, name, args, false, report_errors);
968         }
969
970         static MethodInfo GetMethod (Type t, string name, Type [] args)
971         {
972                 return GetMethod (t, name, args, true);
973         }
974
975
976         /// <summary>
977         ///    Returns the ConstructorInfo for "args"
978         /// </summary>
979         public static ConstructorInfo GetConstructor (Type t, Type [] args)
980         {
981                 MemberList list;
982                 Signature sig;
983
984                 sig.name = ".ctor";
985                 sig.args = args;
986                 
987                 list = FindMembers (t, MemberTypes.Constructor,
988                                     instance_and_static | BindingFlags.Public | BindingFlags.DeclaredOnly,
989                                     signature_filter, sig);
990                 if (list.Count == 0){
991                         Report.Error (-19, "Can not find the core constructor for type `" + t.Name + "'");
992                         return null;
993                 }
994
995                 ConstructorInfo ci = list [0] as ConstructorInfo;
996                 if (ci == null){
997                         Report.Error (-19, "Can not find the core constructor for type `" + t.Name + "'");
998                         return null;
999                 }
1000
1001                 return ci;
1002         }
1003
1004         public static void InitEnumUnderlyingTypes ()
1005         {
1006
1007                 int32_type    = CoreLookupType ("System.Int32");
1008                 int64_type    = CoreLookupType ("System.Int64");
1009                 uint32_type   = CoreLookupType ("System.UInt32"); 
1010                 uint64_type   = CoreLookupType ("System.UInt64"); 
1011                 byte_type     = CoreLookupType ("System.Byte");
1012                 sbyte_type    = CoreLookupType ("System.SByte");
1013                 short_type    = CoreLookupType ("System.Int16");
1014                 ushort_type   = CoreLookupType ("System.UInt16");
1015         }
1016         
1017         /// <remarks>
1018         ///   The types have to be initialized after the initial
1019         ///   population of the type has happened (for example, to
1020         ///   bootstrap the corlib.dll
1021         /// </remarks>
1022         public static void InitCoreTypes ()
1023         {
1024                 object_type   = CoreLookupType ("System.Object");
1025                 value_type    = CoreLookupType ("System.ValueType");
1026
1027                 InitEnumUnderlyingTypes ();
1028
1029                 char_type     = CoreLookupType ("System.Char");
1030                 string_type   = CoreLookupType ("System.String");
1031                 float_type    = CoreLookupType ("System.Single");
1032                 double_type   = CoreLookupType ("System.Double");
1033                 char_ptr_type = CoreLookupType ("System.Char*");
1034                 decimal_type  = CoreLookupType ("System.Decimal");
1035                 bool_type     = CoreLookupType ("System.Boolean");
1036                 enum_type     = CoreLookupType ("System.Enum");
1037
1038                 multicast_delegate_type = CoreLookupType ("System.MulticastDelegate");
1039                 delegate_type           = CoreLookupType ("System.Delegate");
1040
1041                 array_type    = CoreLookupType ("System.Array");
1042                 void_type     = CoreLookupType ("System.Void");
1043                 type_type     = CoreLookupType ("System.Type");
1044
1045                 runtime_field_handle_type = CoreLookupType ("System.RuntimeFieldHandle");
1046                 runtime_argument_handle_type = CoreLookupType ("System.RuntimeArgumentHandle");
1047                 runtime_helpers_type = CoreLookupType ("System.Runtime.CompilerServices.RuntimeHelpers");
1048                 default_member_type  = CoreLookupType ("System.Reflection.DefaultMemberAttribute");
1049                 runtime_handle_type  = CoreLookupType ("System.RuntimeTypeHandle");
1050                 asynccallback_type   = CoreLookupType ("System.AsyncCallback");
1051                 iasyncresult_type    = CoreLookupType ("System.IAsyncResult");
1052                 ienumerator_type     = CoreLookupType ("System.Collections.IEnumerator");
1053                 ienumerable_type     = CoreLookupType ("System.Collections.IEnumerable");
1054                 idisposable_type     = CoreLookupType ("System.IDisposable");
1055                 icloneable_type      = CoreLookupType ("System.ICloneable");
1056                 iconvertible_type    = CoreLookupType ("System.IConvertible");
1057                 monitor_type         = CoreLookupType ("System.Threading.Monitor");
1058                 intptr_type          = CoreLookupType ("System.IntPtr");
1059
1060                 attribute_type       = CoreLookupType ("System.Attribute");
1061                 attribute_usage_type = CoreLookupType ("System.AttributeUsageAttribute");
1062                 dllimport_type       = CoreLookupType ("System.Runtime.InteropServices.DllImportAttribute");
1063                 methodimpl_attr_type = CoreLookupType ("System.Runtime.CompilerServices.MethodImplAttribute");
1064                 marshal_as_attr_type = CoreLookupType ("System.Runtime.InteropServices.MarshalAsAttribute");
1065                 param_array_type     = CoreLookupType ("System.ParamArrayAttribute");
1066                 in_attribute_type    = CoreLookupType ("System.Runtime.InteropServices.InAttribute");
1067                 out_attribute_type   = CoreLookupType ("System.Runtime.InteropServices.OutAttribute");
1068                 typed_reference_type = CoreLookupType ("System.TypedReference");
1069                 arg_iterator_type    = CoreLookupType ("System.ArgIterator");
1070                 mbr_type             = CoreLookupType ("System.MarshalByRefObject");
1071                 decimal_constant_attribute_type = CoreLookupType ("System.Runtime.CompilerServices.DecimalConstantAttribute");
1072
1073                 unverifiable_code_type= CoreLookupType ("System.Security.UnverifiableCodeAttribute");
1074
1075                 void_ptr_type         = CoreLookupType ("System.Void*");
1076
1077                 indexer_name_type     = CoreLookupType ("System.Runtime.CompilerServices.IndexerNameAttribute");
1078
1079                 exception_type        = CoreLookupType ("System.Exception");
1080                 invalid_operation_exception_type = CoreLookupType ("System.InvalidOperationException");
1081                 not_supported_exception_type = CoreLookupType ("System.NotSupportedException");
1082
1083                 //
1084                 // Attribute types
1085                 //
1086                 obsolete_attribute_type = CoreLookupType ("System.ObsoleteAttribute");
1087                 conditional_attribute_type = CoreLookupType ("System.Diagnostics.ConditionalAttribute");
1088                 cls_compliant_attribute_type = CoreLookupType ("System.CLSCompliantAttribute");
1089                 struct_layout_attribute_type = CoreLookupType ("System.Runtime.InteropServices.StructLayoutAttribute");
1090                 field_offset_attribute_type = CoreLookupType ("System.Runtime.InteropServices.FieldOffsetAttribute");
1091                 security_attr_type = CoreLookupType ("System.Security.Permissions.SecurityAttribute");
1092                 required_attr_type = CoreLookupType ("System.Runtime.CompilerServices.RequiredAttributeAttribute");
1093
1094                 //
1095                 // .NET 2.0
1096                 //
1097 #if NET_2_0
1098                 compiler_generated_attr_type = CoreLookupType ("System.Runtime.CompilerServices.CompilerGeneratedAttribute");
1099                 fixed_buffer_attr_type = CoreLookupType ("System.Runtime.CompilerServices.FixedBufferAttribute");
1100                 default_charset_type = CoreLookupType ("System.Runtime.InteropServices.DefaultCharSetAttribute");
1101 #endif
1102                 //
1103                 // When compiling corlib, store the "real" types here.
1104                 //
1105                 if (!RootContext.StdLib) {
1106                         system_int32_type = typeof (System.Int32);
1107                         system_array_type = typeof (System.Array);
1108                         system_type_type = typeof (System.Type);
1109                         system_assemblybuilder_type = typeof (System.Reflection.Emit.AssemblyBuilder);
1110
1111                         Type [] void_arg = {  };
1112                         system_int_array_get_length = GetMethod (
1113                                 system_array_type, "get_Length", void_arg);
1114                         system_int_array_get_rank = GetMethod (
1115                                 system_array_type, "get_Rank", void_arg);
1116                         system_object_array_clone = GetMethod (
1117                                 system_array_type, "Clone", void_arg);
1118
1119                         Type [] system_int_arg = { system_int32_type };
1120                         system_int_array_get_length_int = GetMethod (
1121                                 system_array_type, "GetLength", system_int_arg);
1122                         system_int_array_get_upper_bound_int = GetMethod (
1123                                 system_array_type, "GetUpperBound", system_int_arg);
1124                         system_int_array_get_lower_bound_int = GetMethod (
1125                                 system_array_type, "GetLowerBound", system_int_arg);
1126
1127                         Type [] system_array_int_arg = { system_array_type, system_int32_type };
1128                         system_void_array_copyto_array_int = GetMethod (
1129                                 system_array_type, "CopyTo", system_array_int_arg);
1130
1131                         Type [] system_3_type_arg = {
1132                                 system_type_type, system_type_type, system_type_type };
1133                         Type [] system_4_type_arg = {
1134                                 system_type_type, system_type_type, system_type_type, system_type_type };
1135
1136                         MethodInfo set_corlib_type_builders = GetMethod (
1137                                 system_assemblybuilder_type, "SetCorlibTypeBuilders",
1138                                 system_4_type_arg, true, false);
1139
1140                         if (set_corlib_type_builders != null) {
1141                                 object[] args = new object [4];
1142                                 args [0] = object_type;
1143                                 args [1] = value_type;
1144                                 args [2] = enum_type;
1145                                 args [3] = void_type;
1146                                 
1147                                 set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
1148                         } else {
1149                                 // Compatibility for an older version of the class libs.
1150                                 set_corlib_type_builders = GetMethod (
1151                                         system_assemblybuilder_type, "SetCorlibTypeBuilders",
1152                                         system_3_type_arg, true, true);
1153
1154                                 if (set_corlib_type_builders == null) {
1155                                         Report.Error (-26, "Corlib compilation is not supported in Microsoft.NET due to bugs in it");
1156                                         return;
1157                                 }
1158
1159                                 object[] args = new object [3];
1160                                 args [0] = object_type;
1161                                 args [1] = value_type;
1162                                 args [2] = enum_type;
1163                                 
1164                                 set_corlib_type_builders.Invoke (CodeGen.Assembly.Builder, args);
1165                         }
1166                 }
1167
1168                 system_object_expr.Type = object_type;
1169                 system_string_expr.Type = string_type;
1170                 system_boolean_expr.Type = bool_type;
1171                 system_decimal_expr.Type = decimal_type;
1172                 system_single_expr.Type = float_type;
1173                 system_double_expr.Type = double_type;
1174                 system_sbyte_expr.Type = sbyte_type;
1175                 system_byte_expr.Type = byte_type;
1176                 system_int16_expr.Type = short_type;
1177                 system_uint16_expr.Type = ushort_type;
1178                 system_int32_expr.Type = int32_type;
1179                 system_uint32_expr.Type = uint32_type;
1180                 system_int64_expr.Type = int64_type;
1181                 system_uint64_expr.Type = uint64_type;
1182                 system_char_expr.Type = char_type;
1183                 system_void_expr.Type = void_type;
1184                 system_asynccallback_expr.Type = asynccallback_type;
1185                 system_iasyncresult_expr.Type = iasyncresult_type;
1186                 system_valuetype_expr.Type = value_type;
1187
1188                 //
1189                 // These are only used for compare purposes
1190                 //
1191                 anonymous_method_type = typeof (AnonymousMethod);
1192                 null_type = typeof (NullType);
1193         }
1194
1195         //
1196         // The helper methods that are used by the compiler
1197         //
1198         public static void InitCodeHelpers ()
1199         {
1200                 //
1201                 // Now load the default methods that we use.
1202                 //
1203                 Type [] string_string = { string_type, string_type };
1204                 string_concat_string_string = GetMethod (
1205                         string_type, "Concat", string_string);
1206                 Type [] string_string_string = { string_type, string_type, string_type };
1207                 string_concat_string_string_string = GetMethod (
1208                         string_type, "Concat", string_string_string);
1209                 Type [] string_string_string_string = { string_type, string_type, string_type, string_type };
1210                 string_concat_string_string_string_string = GetMethod (
1211                         string_type, "Concat", string_string_string_string);
1212                 Type[] params_string = { GetConstructedType (string_type, "[]") };
1213                 string_concat_string_dot_dot_dot = GetMethod (
1214                         string_type, "Concat", params_string);
1215
1216                 Type [] object_object = { object_type, object_type };
1217                 string_concat_object_object = GetMethod (
1218                         string_type, "Concat", object_object);
1219                 Type [] object_object_object = { object_type, object_type, object_type };
1220                 string_concat_object_object_object = GetMethod (
1221                         string_type, "Concat", object_object_object);
1222                 Type[] params_object = { GetConstructedType (object_type, "[]") };
1223                 string_concat_object_dot_dot_dot = GetMethod (
1224                         string_type, "Concat", params_object);
1225
1226                 Type [] string_ = { string_type };
1227                 string_isinterneted_string = GetMethod (
1228                         string_type, "IsInterned", string_);
1229                 
1230                 Type [] runtime_type_handle = { runtime_handle_type };
1231                 system_type_get_type_from_handle = GetMethod (
1232                         type_type, "GetTypeFromHandle", runtime_type_handle);
1233
1234                 Type [] delegate_delegate = { delegate_type, delegate_type };
1235                 delegate_combine_delegate_delegate = GetMethod (
1236                                 delegate_type, "Combine", delegate_delegate);
1237
1238                 delegate_remove_delegate_delegate = GetMethod (
1239                                 delegate_type, "Remove", delegate_delegate);
1240
1241                 //
1242                 // Void arguments
1243                 //
1244                 Type [] void_arg = {  };
1245                 object_getcurrent_void = GetMethod (
1246                         ienumerator_type, "get_Current", void_arg);
1247                 bool_movenext_void = GetMethod (
1248                         ienumerator_type, "MoveNext", void_arg);
1249                 void_reset_void = GetMethod (
1250                         ienumerator_type, "Reset", void_arg);
1251                 void_dispose_void = GetMethod (
1252                         idisposable_type, "Dispose", void_arg);
1253                 int_get_offset_to_string_data = GetMethod (
1254                         runtime_helpers_type, "get_OffsetToStringData", void_arg);
1255                 int_array_get_length = GetMethod (
1256                         array_type, "get_Length", void_arg);
1257                 int_array_get_rank = GetMethod (
1258                         array_type, "get_Rank", void_arg);
1259                 ienumerable_getenumerator_void = GetMethod (
1260                         ienumerable_type, "GetEnumerator", void_arg);
1261                 
1262                 //
1263                 // Int32 arguments
1264                 //
1265                 Type [] int_arg = { int32_type };
1266                 int_array_get_length_int = GetMethod (
1267                         array_type, "GetLength", int_arg);
1268                 int_array_get_upper_bound_int = GetMethod (
1269                         array_type, "GetUpperBound", int_arg);
1270                 int_array_get_lower_bound_int = GetMethod (
1271                         array_type, "GetLowerBound", int_arg);
1272
1273                 //
1274                 // System.Array methods
1275                 //
1276                 object_array_clone = GetMethod (
1277                         array_type, "Clone", void_arg);
1278                 Type [] array_int_arg = { array_type, int32_type };
1279                 void_array_copyto_array_int = GetMethod (
1280                         array_type, "CopyTo", array_int_arg);
1281                 
1282                 //
1283                 // object arguments
1284                 //
1285                 Type [] object_arg = { object_type };
1286                 void_monitor_enter_object = GetMethod (
1287                         monitor_type, "Enter", object_arg);
1288                 void_monitor_exit_object = GetMethod (
1289                         monitor_type, "Exit", object_arg);
1290
1291                 Type [] array_field_handle_arg = { array_type, runtime_field_handle_type };
1292                 
1293                 void_initializearray_array_fieldhandle = GetMethod (
1294                         runtime_helpers_type, "InitializeArray", array_field_handle_arg);
1295
1296                 //
1297                 // Array functions
1298                 //
1299                 int_getlength_int = GetMethod (
1300                         array_type, "GetLength", int_arg);
1301
1302                 //
1303                 // Decimal constructors
1304                 //
1305                 Type [] dec_arg = { int32_type, int32_type, int32_type, bool_type, byte_type };
1306                 void_decimal_ctor_five_args = GetConstructor (
1307                         decimal_type, dec_arg);
1308                 
1309                 void_decimal_ctor_int_arg = GetConstructor (decimal_type, int_arg);
1310
1311                 //
1312                 // Attributes
1313                 //
1314                 cons_param_array_attribute = GetConstructor (param_array_type, void_arg);
1315                 unverifiable_code_ctor = GetConstructor (unverifiable_code_type, void_arg);
1316                 default_member_ctor = GetConstructor (default_member_type, string_);
1317
1318                 Type[] short_arg = { short_type };
1319                 struct_layout_attribute_ctor = GetConstructor (struct_layout_attribute_type, short_arg);
1320
1321                 decimal_constant_attribute_ctor = GetConstructor (decimal_constant_attribute_type, new Type []
1322                         { byte_type, byte_type, uint32_type, uint32_type, uint32_type } );
1323
1324                 field_offset_attribute_ctor = GetConstructor (field_offset_attribute_type, new Type []
1325                         { int32_type });
1326
1327                 //
1328                 // .NET 2.0 types
1329                 //
1330 #if NET_2_0
1331                 compiler_generated_attr = new CustomAttributeBuilder (
1332                         GetConstructor (compiler_generated_attr_type, void_arg), new object[0]);
1333
1334                 Type[] type_int_arg = { type_type, int32_type };
1335                 fixed_buffer_attr_ctor = GetConstructor (fixed_buffer_attr_type, type_int_arg);
1336 #endif
1337
1338                 // Object
1339                 object_ctor = GetConstructor (object_type, void_arg);
1340
1341         }
1342
1343         const BindingFlags instance_and_static = BindingFlags.Static | BindingFlags.Instance;
1344
1345         /// <remarks>
1346         ///   This is the "old", non-cache based FindMembers() function.  We cannot use
1347         ///   the cache here because there is no member name argument.
1348         /// </remarks>
1349         public static MemberList FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1350                                               MemberFilter filter, object criteria)
1351         {
1352                 DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1353
1354                 //
1355                 // `builder_to_declspace' contains all dynamic types.
1356                 //
1357                 if (decl != null) {
1358                         MemberList list;
1359                         Timer.StartTimer (TimerType.FindMembers);
1360                         list = decl.FindMembers (mt, bf, filter, criteria);
1361                         Timer.StopTimer (TimerType.FindMembers);
1362                         return list;
1363                 }
1364
1365                 //
1366                 // We have to take care of arrays specially, because GetType on
1367                 // a TypeBuilder array will return a Type, not a TypeBuilder,
1368                 // and we can not call FindMembers on this type.
1369                 //
1370                 if (t.IsSubclassOf (TypeManager.array_type))
1371                         return new MemberList (TypeManager.array_type.FindMembers (mt, bf, filter, criteria));
1372
1373                 //
1374                 // Since FindMembers will not lookup both static and instance
1375                 // members, we emulate this behaviour here.
1376                 //
1377                 if ((bf & instance_and_static) == instance_and_static){
1378                         MemberInfo [] i_members = t.FindMembers (
1379                                 mt, bf & ~BindingFlags.Static, filter, criteria);
1380
1381                         int i_len = i_members.Length;
1382                         if (i_len == 1){
1383                                 MemberInfo one = i_members [0];
1384
1385                                 //
1386                                 // If any of these are present, we are done!
1387                                 //
1388                                 if ((one is Type) || (one is EventInfo) || (one is FieldInfo))
1389                                         return new MemberList (i_members);
1390                         }
1391                                 
1392                         MemberInfo [] s_members = t.FindMembers (
1393                                 mt, bf & ~BindingFlags.Instance, filter, criteria);
1394
1395                         int s_len = s_members.Length;
1396                         if (i_len > 0 || s_len > 0)
1397                                 return new MemberList (i_members, s_members);
1398                         else {
1399                                 if (i_len > 0)
1400                                         return new MemberList (i_members);
1401                                 else
1402                                         return new MemberList (s_members);
1403                         }
1404                 }
1405
1406                 return new MemberList (t.FindMembers (mt, bf, filter, criteria));
1407         }
1408
1409
1410         /// <summary>
1411         ///   This method is only called from within MemberLookup.  It tries to use the member
1412         ///   cache if possible and falls back to the normal FindMembers if not.  The `used_cache'
1413         ///   flag tells the caller whether we used the cache or not.  If we used the cache, then
1414         ///   our return value will already contain all inherited members and the caller don't need
1415         ///   to check base classes and interfaces anymore.
1416         /// </summary>
1417         private static MemberInfo [] MemberLookup_FindMembers (Type t, MemberTypes mt, BindingFlags bf,
1418                                                             string name, out bool used_cache)
1419         {
1420                 MemberCache cache;
1421
1422                 //
1423                 // We have to take care of arrays specially, because GetType on
1424                 // a TypeBuilder array will return a Type, not a TypeBuilder,
1425                 // and we can not call FindMembers on this type.
1426                 //
1427                 if (t == TypeManager.array_type || t.IsSubclassOf (TypeManager.array_type)) {
1428                         used_cache = true;
1429                         return TypeHandle.ArrayType.MemberCache.FindMembers (
1430                                 mt, bf, name, FilterWithClosure_delegate, null);
1431                 }
1432
1433                 //
1434                 // If this is a dynamic type, it's always in the `builder_to_declspace' hash table
1435                 // and we can ask the DeclSpace for the MemberCache.
1436                 //
1437                 if (t is TypeBuilder) {
1438                         DeclSpace decl = (DeclSpace) builder_to_declspace [t];
1439                         cache = decl.MemberCache;
1440
1441                         //
1442                         // If this DeclSpace has a MemberCache, use it.
1443                         //
1444
1445                         if (cache != null) {
1446                                 used_cache = true;
1447                                 return cache.FindMembers (
1448                                         mt, bf, name, FilterWithClosure_delegate, null);
1449                         }
1450
1451                         // If there is no MemberCache, we need to use the "normal" FindMembers.
1452                         // Note, this is a VERY uncommon route!
1453                         
1454                         MemberList list;
1455                         Timer.StartTimer (TimerType.FindMembers);
1456                         list = decl.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
1457                                                  FilterWithClosure_delegate, name);
1458                         Timer.StopTimer (TimerType.FindMembers);
1459                         used_cache = false;
1460                         
1461                         return (MemberInfo []) list;
1462                 }
1463
1464                 //
1465                 // This call will always succeed.  There is exactly one TypeHandle instance per
1466                 // type, TypeHandle.GetMemberCache() will, if necessary, create a new one, and return
1467                 // the corresponding MemberCache.
1468                 //
1469                 cache = TypeHandle.GetMemberCache (t);
1470
1471                 used_cache = true;
1472                 return cache.FindMembers (mt, bf, name, FilterWithClosure_delegate, null);
1473         }
1474
1475         public static bool IsBuiltinType (Type t)
1476         {
1477                 if (t == object_type || t == string_type || t == int32_type || t == uint32_type ||
1478                     t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1479                     t == char_type || t == short_type || t == decimal_type || t == bool_type ||
1480                     t == sbyte_type || t == byte_type || t == ushort_type || t == void_type)
1481                         return true;
1482                 else
1483                         return false;
1484         }
1485
1486         public static bool IsBuiltinType (TypeContainer tc)
1487         {
1488                 return IsBuiltinType (tc.TypeBuilder);
1489         }
1490
1491         //
1492         // This is like IsBuiltinType, but lacks decimal_type, we should also clean up
1493         // the pieces in the code where we use IsBuiltinType and special case decimal_type.
1494         // 
1495         public static bool IsPrimitiveType (Type t)
1496         {
1497                 return (t == int32_type || t == uint32_type ||
1498                     t == int64_type || t == uint64_type || t == float_type || t == double_type ||
1499                     t == char_type || t == short_type || t == bool_type ||
1500                     t == sbyte_type || t == byte_type || t == ushort_type);
1501         }
1502
1503         public static bool IsDelegateType (Type t)
1504         {
1505                 if (t.IsSubclassOf (TypeManager.delegate_type))
1506                         return true;
1507                 else
1508                         return false;
1509         }
1510         
1511         public static bool IsEnumType (Type t)
1512         {
1513                 if (t.IsSubclassOf (TypeManager.enum_type))
1514                         return true;
1515                 else
1516                         return false;
1517         }
1518         public static bool IsBuiltinOrEnum (Type t)
1519         {
1520                 if (IsBuiltinType (t))
1521                         return true;
1522                 
1523                 if (IsEnumType (t))
1524                         return true;
1525
1526                 return false;
1527         }
1528
1529         //
1530         // Whether a type is unmanaged.  This is used by the unsafe code (25.2)
1531         //
1532         public static bool IsUnmanagedType (Type t)
1533         {
1534                 // builtins that are not unmanaged types
1535                 if (t == TypeManager.object_type || t == TypeManager.string_type)
1536                         return false;
1537
1538                 if (IsBuiltinOrEnum (t))
1539                         return true;
1540
1541                 // Someone did the work of checking if the ElementType of t is unmanaged.  Let's not repeat it.
1542                 if (t.IsPointer)
1543                         return true;
1544
1545                 // Arrays are disallowed, even if we mark them with [MarshalAs(UnmanagedType.ByValArray, ...)]
1546                 if (t.IsArray)
1547                         return false;
1548
1549                 if (!IsValueType (t))
1550                         return false;
1551
1552                 if (t is TypeBuilder){
1553                         TypeContainer tc = LookupTypeContainer (t);
1554                         if (tc.Fields == null)
1555                                 return true;
1556                         foreach (Field f in tc.Fields){
1557                                 // Avoid using f.FieldBuilder: f.Define () may not yet have been invoked.
1558                                 if ((f.ModFlags & Modifiers.STATIC) != 0)
1559                                         continue;
1560                                 if (f.MemberType == null)
1561                                         continue;
1562                                 if (!IsUnmanagedType (f.MemberType)){
1563                                         Report.SymbolRelatedToPreviousError (f.Location, CSharpName (t) + "." + f.Name);
1564                                         return false;
1565                                 }
1566                         }
1567                         return true;
1568                 }
1569                 
1570                 FieldInfo [] fields = t.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);
1571
1572                 foreach (FieldInfo f in fields){
1573                         if (!IsUnmanagedType (f.FieldType)){
1574                                 Report.SymbolRelatedToPreviousError (f);
1575                                 return false;
1576                         }
1577                 }
1578
1579                 return true;
1580         }
1581                 
1582         public static bool IsValueType (Type t)
1583         {
1584                 if (t.IsSubclassOf (TypeManager.value_type) && (t != TypeManager.enum_type))
1585                         return true;
1586                 else
1587                         return false;
1588         }
1589         
1590         public static bool IsInterfaceType (Type t)
1591         {
1592                 TypeContainer tc = (TypeContainer) builder_to_declspace [t];
1593                 if (tc == null)
1594                         return false;
1595
1596                 return tc.Kind == Kind.Interface;
1597         }
1598
1599         public static bool IsSubclassOf (Type type, Type base_type)
1600         {
1601                 do {
1602                         if (type.Equals (base_type))
1603                                 return true;
1604
1605                         type = type.BaseType;
1606                 } while (type != null);
1607
1608                 return false;
1609         }
1610
1611         public static bool IsFamilyAccessible (Type type, Type base_type)
1612         {
1613                 return IsSubclassOf (type, base_type);
1614         }
1615
1616         //
1617         // Checks whether `type' is a subclass or nested child of `base_type'.
1618         //
1619         public static bool IsNestedFamilyAccessible (Type type, Type base_type)
1620         {
1621                 do {
1622                         if ((type == base_type) || type.IsSubclassOf (base_type))
1623                                 return true;
1624
1625                         // Handle nested types.
1626                         type = type.DeclaringType;
1627                 } while (type != null);
1628
1629                 return false;
1630         }
1631
1632         //
1633         // Checks whether `type' is a nested child of `parent'.
1634         //
1635         public static bool IsNestedChildOf (Type type, Type parent)
1636         {
1637                 if (type == parent)
1638                         return false;
1639
1640                 type = type.DeclaringType;
1641                 while (type != null) {
1642                         if (type == parent)
1643                                 return true;
1644
1645                         type = type.DeclaringType;
1646                 }
1647
1648                 return false;
1649         }
1650
1651         //
1652         // Do the right thing when returning the element type of an
1653         // array type based on whether we are compiling corlib or not
1654         //
1655         public static Type GetElementType (Type t)
1656         {
1657                 if (RootContext.StdLib)
1658                         return t.GetElementType ();
1659                 else
1660                         return TypeToCoreType (t.GetElementType ());
1661         }
1662
1663         /// <summary>
1664         /// This method is not implemented by MS runtime for dynamic types
1665         /// </summary>
1666         public static bool HasElementType (Type t)
1667         {
1668                 return t.IsArray || t.IsPointer || t.IsByRef;
1669         }
1670
1671         /// <summary>
1672         ///   Returns the User Defined Types
1673         /// </summary>
1674         public static ArrayList UserTypes {
1675                 get {
1676                         return user_types;
1677                 }
1678         }
1679
1680         public static Hashtable TypeContainers {
1681                 get {
1682                         return typecontainers;
1683                 }
1684         }
1685
1686         static Hashtable builder_to_constant;
1687
1688         public static void RegisterConstant (FieldBuilder fb, Const c)
1689         {
1690                 if (builder_to_constant == null)
1691                         builder_to_constant = new PtrHashtable ();
1692
1693                 if (builder_to_constant.Contains (fb))
1694                         return;
1695
1696                 builder_to_constant.Add (fb, c);
1697         }
1698
1699         public static Const LookupConstant (FieldBuilder fb)
1700         {
1701                 if (builder_to_constant == null)
1702                         return null;
1703                 
1704                 return (Const) builder_to_constant [fb];
1705         }
1706         
1707         /// <summary>
1708         ///   Gigantic work around for missing features in System.Reflection.Emit follows.
1709         /// </summary>
1710         ///
1711         /// <remarks>
1712         ///   Since System.Reflection.Emit can not return MethodBase.GetParameters
1713         ///   for anything which is dynamic, and we need this in a number of places,
1714         ///   we register this information here, and use it afterwards.
1715         /// </remarks>
1716         static public void RegisterMethod (MethodBase mb, InternalParameters ip, Type [] args)
1717         {
1718                 if (args == null)
1719                         args = NoTypes;
1720                                 
1721                 method_arguments.Add (mb, args);
1722                 method_params.Add (mb, ip);
1723         }
1724         
1725         static public ParameterData GetParameterData (MethodBase mb)
1726         {
1727                 object pd = method_params [mb];
1728                 if (pd == null) {
1729                         if (mb is MethodBuilder || mb is ConstructorBuilder)
1730                                 throw new InternalErrorException ("Argument for Method not registered" + mb);
1731
1732                         method_params [mb] = pd = new ReflectionParameters (mb);
1733                 }
1734
1735                 return (ParameterData) pd;
1736         }
1737
1738         static public void RegisterOverride (MethodBase override_method, MethodBase base_method)
1739         {
1740                 if (method_overrides.Contains (override_method)) {
1741                         if (method_overrides [override_method] != base_method)
1742                                 throw new InternalErrorException ("Override mismatch: " + override_method);
1743                         return;
1744                 }
1745                 method_overrides [override_method] = base_method;
1746         }
1747
1748         static public bool IsOverride (MethodBase m)
1749         {
1750                 return m.IsVirtual &&
1751                         (m.Attributes & MethodAttributes.NewSlot) == 0 &&
1752                         (m is MethodBuilder || method_overrides.Contains (m));
1753         }
1754
1755         /// <summary>
1756         ///    Returns the argument types for a method based on its methodbase
1757         ///
1758         ///    For dynamic methods, we use the compiler provided types, for
1759         ///    methods from existing assemblies we load them from GetParameters,
1760         ///    and insert them into the cache
1761         /// </summary>
1762         static public Type [] GetArgumentTypes (MethodBase mb)
1763         {
1764                 object t = method_arguments [mb];
1765                 if (t != null)
1766                         return (Type []) t;
1767
1768                 ParameterInfo [] pi = mb.GetParameters ();
1769                 int c = pi.Length;
1770                 Type [] types;
1771
1772                 if (c == 0) {
1773                         types = NoTypes;
1774                 } else {
1775                         types = new Type [c];
1776                         for (int i = 0; i < c; i++)
1777                                 types [i] = pi [i].ParameterType;
1778                 }
1779                 method_arguments.Add (mb, types);
1780                 return types;
1781         }
1782
1783         /// <summary>
1784         ///    Returns the argument types for an indexer based on its PropertyInfo
1785         ///
1786         ///    For dynamic indexers, we use the compiler provided types, for
1787         ///    indexers from existing assemblies we load them from GetParameters,
1788         ///    and insert them into the cache
1789         /// </summary>
1790         static public Type [] GetArgumentTypes (PropertyInfo indexer)
1791         {
1792                 if (indexer_arguments.Contains (indexer))
1793                         return (Type []) indexer_arguments [indexer];
1794                 else if (indexer is PropertyBuilder)
1795                         // If we're a PropertyBuilder and not in the
1796                         // `indexer_arguments' hash, then we're a property and
1797                         // not an indexer.
1798                         return NoTypes;
1799                 else {
1800                         ParameterInfo [] pi = indexer.GetIndexParameters ();
1801                         // Property, not an indexer.
1802                         if (pi == null)
1803                                 return NoTypes;
1804                         int c = pi.Length;
1805                         Type [] types = new Type [c];
1806                         
1807                         for (int i = 0; i < c; i++)
1808                                 types [i] = pi [i].ParameterType;
1809
1810                         indexer_arguments.Add (indexer, types);
1811                         return types;
1812                 }
1813         }
1814         
1815         // <remarks>
1816         //  This is a workaround the fact that GetValue is not
1817         //  supported for dynamic types
1818         // </remarks>
1819         static public bool RegisterFieldValue (FieldBuilder fb, object value)
1820         {
1821                 if (fields.Contains (fb))
1822                         return false;
1823
1824                 fields.Add (fb, value);
1825
1826                 return true;
1827         }
1828
1829         static public object GetValue (FieldBuilder fb)
1830         {
1831                 return fields [fb];
1832         }
1833
1834         static public bool RegisterFieldBase (FieldBuilder fb, FieldBase f)
1835         {
1836                 if (fieldbuilders_to_fields.Contains (fb))
1837                         return false;
1838
1839                 fieldbuilders_to_fields.Add (fb, f);
1840                 return true;
1841         }
1842
1843         //
1844         // The return value can be null;  This will be the case for
1845         // auxiliary FieldBuilders created by the compiler that have no
1846         // real field being declared on the source code
1847         //
1848         static public FieldBase GetField (FieldInfo fb)
1849         {
1850                 return (FieldBase) fieldbuilders_to_fields [fb];
1851         }
1852         
1853         static Hashtable events;
1854
1855         static public void RegisterEvent (MyEventBuilder eb, MethodBase add, MethodBase remove)
1856         {
1857                 if (events == null)
1858                         events = new Hashtable ();
1859
1860                 if (!events.Contains (eb)) {
1861                         events.Add (eb, new Pair (add, remove));
1862                 }
1863         }
1864
1865         static public MethodInfo GetAddMethod (EventInfo ei)
1866         {
1867                 if (ei is MyEventBuilder) {
1868                         Pair pair = (Pair) events [ei];
1869
1870                         return (MethodInfo) pair.First;
1871                 }
1872                 return ei.GetAddMethod (true);
1873         }
1874
1875         static public MethodInfo GetRemoveMethod (EventInfo ei)
1876         {
1877                 if (ei is MyEventBuilder) {
1878                         Pair pair = (Pair) events [ei];
1879
1880                         return (MethodInfo) pair.Second;
1881                 }
1882                 return ei.GetRemoveMethod (true);
1883         }
1884
1885         static Hashtable priv_fields_events;
1886
1887         static public bool RegisterPrivateFieldOfEvent (EventInfo einfo, FieldBuilder builder)
1888         {
1889                 if (priv_fields_events == null)
1890                         priv_fields_events = new Hashtable ();
1891
1892                 if (priv_fields_events.Contains (einfo))
1893                         return false;
1894
1895                 priv_fields_events.Add (einfo, builder);
1896
1897                 return true;
1898         }
1899
1900         static public MemberInfo GetPrivateFieldOfEvent (EventInfo ei)
1901         {
1902                 if (priv_fields_events == null)
1903                         return null;
1904                 else
1905                         return (MemberInfo) priv_fields_events [ei];
1906         }
1907                 
1908         static Hashtable properties;
1909         
1910         static public bool RegisterProperty (PropertyBuilder pb, MethodBase get, MethodBase set)
1911         {
1912                 if (properties == null)
1913                         properties = new Hashtable ();
1914
1915                 if (properties.Contains (pb))
1916                         return false;
1917
1918                 properties.Add (pb, new Pair (get, set));
1919
1920                 return true;
1921         }
1922
1923         static public bool RegisterIndexer (PropertyBuilder pb, MethodBase get,
1924                                             MethodBase set, Type[] args)
1925         {
1926                 if (!RegisterProperty (pb, get,set))
1927                         return false;
1928
1929                 indexer_arguments.Add (pb, args);
1930
1931                 return true;
1932         }
1933
1934         public static bool CheckStructCycles (TypeContainer tc, Hashtable seen)
1935         {
1936                 Hashtable hash = new Hashtable ();
1937                 return CheckStructCycles (tc, seen, hash);
1938         }
1939
1940         public static bool CheckStructCycles (TypeContainer tc, Hashtable seen,
1941                                               Hashtable hash)
1942         {
1943                 if ((tc.Kind != Kind.Struct) || IsBuiltinType (tc))
1944                         return true;
1945
1946                 //
1947                 // `seen' contains all types we've already visited.
1948                 //
1949                 if (seen.Contains (tc))
1950                         return true;
1951                 seen.Add (tc, null);
1952
1953                 if (tc.Fields == null)
1954                         return true;
1955
1956                 foreach (FieldMember field in tc.Fields) {
1957                         if (field.FieldBuilder == null || field.FieldBuilder.IsStatic)
1958                                 continue;
1959
1960                         Type ftype = field.FieldBuilder.FieldType;
1961                         TypeContainer ftc = LookupTypeContainer (ftype);
1962                         if (ftc == null)
1963                                 continue;
1964
1965                         if (hash.Contains (ftc)) {
1966                                 Report.Error (523, tc.Location,
1967                                               "Struct member `{0}.{1}' of type `{2}' " +
1968                                               "causes a cycle in the struct layout",
1969                                               tc.Name, field.Name, ftc.Name);
1970                                 return false;
1971                         }
1972
1973                         //
1974                         // `hash' contains all types in the current path.
1975                         //
1976                         hash.Add (tc, null);
1977
1978                         bool ok = CheckStructCycles (ftc, seen, hash);
1979
1980                         hash.Remove (tc);
1981
1982                         if (!ok)
1983                                 return false;
1984
1985                         if (!seen.Contains (ftc))
1986                                 seen.Add (ftc, null);
1987                 }
1988
1989                 return true;
1990         }
1991
1992         /// <summary>
1993         ///   Given an array of interface types, expand and eliminate repeated ocurrences
1994         ///   of an interface.  
1995         /// </summary>
1996         ///
1997         /// <remarks>
1998         ///   This expands in context like: IA; IB : IA; IC : IA, IB; the interface "IC" to
1999         ///   be IA, IB, IC.
2000         /// </remarks>
2001         public static Type[] ExpandInterfaces (EmitContext ec, TypeExpr [] base_interfaces)
2002         {
2003                 ArrayList new_ifaces = new ArrayList ();
2004
2005                 foreach (TypeExpr iface in base_interfaces){
2006                         Type itype = iface.ResolveType (ec);
2007                         if (itype == null)
2008                                 return null;
2009
2010                         if (!new_ifaces.Contains (itype))
2011                                 new_ifaces.Add (itype);
2012                         
2013                         Type [] implementing = itype.GetInterfaces ();
2014                         
2015                         foreach (Type imp in implementing){
2016                                 if (!new_ifaces.Contains (imp))
2017                                         new_ifaces.Add (imp);
2018                         }
2019                 }
2020                 Type [] ret = new Type [new_ifaces.Count];
2021                 new_ifaces.CopyTo (ret, 0);
2022                 return ret;
2023         }
2024         
2025         static PtrHashtable iface_cache = new PtrHashtable ();
2026                 
2027         /// <summary>
2028         ///   This function returns the interfaces in the type `t'.  Works with
2029         ///   both types and TypeBuilders.
2030         /// </summary>
2031         public static Type [] GetInterfaces (Type t)
2032         {
2033                 
2034                 Type [] cached = iface_cache [t] as Type [];
2035                 if (cached != null)
2036                         return cached;
2037                 
2038                 //
2039                 // The reason for catching the Array case is that Reflection.Emit
2040                 // will not return a TypeBuilder for Array types of TypeBuilder types,
2041                 // but will still throw an exception if we try to call GetInterfaces
2042                 // on the type.
2043                 //
2044                 // Since the array interfaces are always constant, we return those for
2045                 // the System.Array
2046                 //
2047                 
2048                 if (t.IsArray)
2049                         t = TypeManager.array_type;
2050                 
2051                 if (t is TypeBuilder){
2052                         Type [] base_ifaces;
2053                         
2054                         if (t.BaseType == null)
2055                                 base_ifaces = NoTypes;
2056                         else
2057                                 base_ifaces = GetInterfaces (t.BaseType);
2058                         Type [] type_ifaces = (Type []) builder_to_ifaces [t];
2059                         if (type_ifaces == null)
2060                                 type_ifaces = NoTypes;
2061
2062                         int base_count = base_ifaces.Length;
2063                         Type [] result = new Type [base_count + type_ifaces.Length];
2064                         base_ifaces.CopyTo (result, 0);
2065                         type_ifaces.CopyTo (result, base_count);
2066
2067                         iface_cache [t] = result;
2068                         return result;
2069                 } else {
2070                         Type[] ifaces = t.GetInterfaces ();
2071                         iface_cache [t] = ifaces;
2072                         return ifaces;
2073                 }
2074         }
2075         
2076         //
2077         // gets the interfaces that are declared explicitly on t
2078         //
2079         public static Type [] GetExplicitInterfaces (TypeBuilder t)
2080         {
2081                 return (Type []) builder_to_ifaces [t];
2082         }
2083         
2084         /// <remarks>
2085         ///  The following is used to check if a given type implements an interface.
2086         ///  The cache helps us reduce the expense of hitting Type.GetInterfaces everytime.
2087         /// </remarks>
2088         public static bool ImplementsInterface (Type t, Type iface)
2089         {
2090                 Type [] interfaces;
2091
2092                 //
2093                 // FIXME OPTIMIZATION:
2094                 // as soon as we hit a non-TypeBuiler in the interface
2095                 // chain, we could return, as the `Type.GetInterfaces'
2096                 // will return all the interfaces implement by the type
2097                 // or its bases.
2098                 //
2099                 do {
2100                         interfaces = GetInterfaces (t);
2101
2102                         if (interfaces != null){
2103                                 foreach (Type i in interfaces){
2104                                         if (i == iface)
2105                                                 return true;
2106                                 }
2107                         }
2108                         
2109                         t = t.BaseType;
2110                 } while (t != null);
2111                 
2112                 return false;
2113         }
2114
2115         static NumberFormatInfo nf_provider = CultureInfo.CurrentCulture.NumberFormat;
2116
2117         // This is a custom version of Convert.ChangeType() which works
2118         // with the TypeBuilder defined types when compiling corlib.
2119         public static object ChangeType (object value, Type conversionType, out bool error)
2120         {
2121                 IConvertible convert_value = value as IConvertible;
2122                 
2123                 if (convert_value == null){
2124                         error = true;
2125                         return null;
2126                 }
2127                 
2128                 //
2129                 // We must use Type.Equals() here since `conversionType' is
2130                 // the TypeBuilder created version of a system type and not
2131                 // the system type itself.  You cannot use Type.GetTypeCode()
2132                 // on such a type - it'd always return TypeCode.Object.
2133                 //
2134                 error = false;
2135                 try {
2136                         if (conversionType.Equals (typeof (Boolean)))
2137                                 return (object)(convert_value.ToBoolean (nf_provider));
2138                         else if (conversionType.Equals (typeof (Byte)))
2139                                 return (object)(convert_value.ToByte (nf_provider));
2140                         else if (conversionType.Equals (typeof (Char)))
2141                                 return (object)(convert_value.ToChar (nf_provider));
2142                         else if (conversionType.Equals (typeof (DateTime)))
2143                                 return (object)(convert_value.ToDateTime (nf_provider));
2144                         else if (conversionType.Equals (TypeManager.decimal_type)) // typeof (Decimal)))
2145                                 return (object)(convert_value.ToDecimal (nf_provider));
2146                         else if (conversionType.Equals (typeof (Double)))
2147                                 return (object)(convert_value.ToDouble (nf_provider));
2148                         else if (conversionType.Equals (typeof (Int16)))
2149                                 return (object)(convert_value.ToInt16 (nf_provider));
2150                         else if (conversionType.Equals (typeof (Int32)))
2151                                 return (object)(convert_value.ToInt32 (nf_provider));
2152                         else if (conversionType.Equals (typeof (Int64)))
2153                                 return (object)(convert_value.ToInt64 (nf_provider));
2154                         else if (conversionType.Equals (typeof (SByte)))
2155                                 return (object)(convert_value.ToSByte (nf_provider));
2156                         else if (conversionType.Equals (typeof (Single)))
2157                                 return (object)(convert_value.ToSingle (nf_provider));
2158                         else if (conversionType.Equals (typeof (String)))
2159                                 return (object)(convert_value.ToString (nf_provider));
2160                         else if (conversionType.Equals (typeof (UInt16)))
2161                                 return (object)(convert_value.ToUInt16 (nf_provider));
2162                         else if (conversionType.Equals (typeof (UInt32)))
2163                                 return (object)(convert_value.ToUInt32 (nf_provider));
2164                         else if (conversionType.Equals (typeof (UInt64)))
2165                                 return (object)(convert_value.ToUInt64 (nf_provider));
2166                         else if (conversionType.Equals (typeof (Object)))
2167                                 return (object)(value);
2168                         else 
2169                                 error = true;
2170                 } catch {
2171                         error = true;
2172                 }
2173                 return null;
2174         }
2175
2176         //
2177         // This is needed, because enumerations from assemblies
2178         // do not report their underlyingtype, but they report
2179         // themselves
2180         //
2181         public static Type EnumToUnderlying (Type t)
2182         {
2183                 if (t == TypeManager.enum_type)
2184                         return t;
2185
2186                 t = t.UnderlyingSystemType;
2187                 if (!TypeManager.IsEnumType (t))
2188                         return t;
2189         
2190                 if (t is TypeBuilder) {
2191                         // slow path needed to compile corlib
2192                         if (t == TypeManager.bool_type ||
2193                             t == TypeManager.byte_type ||
2194                             t == TypeManager.sbyte_type ||
2195                             t == TypeManager.char_type ||
2196                             t == TypeManager.short_type ||
2197                             t == TypeManager.ushort_type ||
2198                             t == TypeManager.int32_type ||
2199                             t == TypeManager.uint32_type ||
2200                             t == TypeManager.int64_type ||
2201                             t == TypeManager.uint64_type)
2202                                 return t;
2203                         throw new Exception ("Unhandled typecode in enum " + " from " + t.AssemblyQualifiedName);
2204                 }
2205                 TypeCode tc = Type.GetTypeCode (t);
2206
2207                 switch (tc){
2208                 case TypeCode.Boolean:
2209                         return TypeManager.bool_type;
2210                 case TypeCode.Byte:
2211                         return TypeManager.byte_type;
2212                 case TypeCode.SByte:
2213                         return TypeManager.sbyte_type;
2214                 case TypeCode.Char:
2215                         return TypeManager.char_type;
2216                 case TypeCode.Int16:
2217                         return TypeManager.short_type;
2218                 case TypeCode.UInt16:
2219                         return TypeManager.ushort_type;
2220                 case TypeCode.Int32:
2221                         return TypeManager.int32_type;
2222                 case TypeCode.UInt32:
2223                         return TypeManager.uint32_type;
2224                 case TypeCode.Int64:
2225                         return TypeManager.int64_type;
2226                 case TypeCode.UInt64:
2227                         return TypeManager.uint64_type;
2228                 }
2229                 throw new Exception ("Unhandled typecode in enum " + tc + " from " + t.AssemblyQualifiedName);
2230         }
2231
2232         //
2233         // When compiling corlib and called with one of the core types, return
2234         // the corresponding typebuilder for that type.
2235         //
2236         public static Type TypeToCoreType (Type t)
2237         {
2238                 if (RootContext.StdLib || (t is TypeBuilder))
2239                         return t;
2240
2241                 TypeCode tc = Type.GetTypeCode (t);
2242
2243                 switch (tc){
2244                 case TypeCode.Boolean:
2245                         return TypeManager.bool_type;
2246                 case TypeCode.Byte:
2247                         return TypeManager.byte_type;
2248                 case TypeCode.SByte:
2249                         return TypeManager.sbyte_type;
2250                 case TypeCode.Char:
2251                         return TypeManager.char_type;
2252                 case TypeCode.Int16:
2253                         return TypeManager.short_type;
2254                 case TypeCode.UInt16:
2255                         return TypeManager.ushort_type;
2256                 case TypeCode.Int32:
2257                         return TypeManager.int32_type;
2258                 case TypeCode.UInt32:
2259                         return TypeManager.uint32_type;
2260                 case TypeCode.Int64:
2261                         return TypeManager.int64_type;
2262                 case TypeCode.UInt64:
2263                         return TypeManager.uint64_type;
2264                 case TypeCode.Single:
2265                         return TypeManager.float_type;
2266                 case TypeCode.Double:
2267                         return TypeManager.double_type;
2268                 case TypeCode.String:
2269                         return TypeManager.string_type;
2270                 case TypeCode.Decimal:
2271                         return TypeManager.decimal_type;
2272                 default:
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                         return t;
2282                 }
2283         }
2284
2285         /// <summary>
2286         ///   Utility function that can be used to probe whether a type
2287         ///   is managed or not.  
2288         /// </summary>
2289         public static bool VerifyUnManaged (Type t, Location loc)
2290         {
2291                 if (IsUnmanagedType (t))
2292                         return true;
2293
2294                 Report.Error (
2295                         208, loc,
2296                         "Cannot take the address or size of a variable of a managed type ('" +
2297                         CSharpName (t) + "')");
2298                 return false;   
2299         }
2300         
2301         /// <summary>
2302         ///   Returns the name of the indexer in a given type.
2303         /// </summary>
2304         /// <remarks>
2305         ///   The default is not always `Item'.  The user can change this behaviour by
2306         ///   using the IndexerNameAttribute in the container.
2307         ///   For example, the String class indexer is named `Chars' not `Item' 
2308         /// </remarks>
2309         public static string IndexerPropertyName (Type t)
2310         {
2311                 if (t is TypeBuilder) {
2312                         TypeContainer tc = t.IsInterface ? LookupInterface (t) : LookupTypeContainer (t);
2313                         return tc == null ? TypeContainer.DefaultIndexerName : tc.IndexerName;
2314                 }
2315                 
2316                 System.Attribute attr = System.Attribute.GetCustomAttribute (
2317                         t, TypeManager.default_member_type);
2318                 if (attr != null){
2319                         DefaultMemberAttribute dma = (DefaultMemberAttribute) attr;
2320                         return dma.MemberName;
2321                 }
2322
2323                 return TypeContainer.DefaultIndexerName;
2324         }
2325
2326         static MethodInfo declare_local_method = null;
2327         
2328         public static LocalBuilder DeclareLocalPinned (ILGenerator ig, Type t)
2329         {
2330                 if (declare_local_method == null){
2331                         declare_local_method = typeof (ILGenerator).GetMethod (
2332                                 "DeclareLocal",
2333                                 BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic,
2334                                 null, 
2335                                 new Type [] { typeof (Type), typeof (bool)},
2336                                 null);
2337                         if (declare_local_method == null){
2338                                 Report.Warning (-30, new Location (-1),
2339                                                 "This version of the runtime does not support making pinned local variables.  " +
2340                                                 "This code may cause errors on a runtime with a moving GC");
2341                                 return ig.DeclareLocal (t);
2342                         }
2343                 }
2344                 return (LocalBuilder) declare_local_method.Invoke (ig, new object [] { t, true });
2345         }
2346         
2347         //
2348         // Returns whether the array of memberinfos contains the given method
2349         //
2350         public static bool ArrayContainsMethod (MemberInfo [] array, MethodBase new_method)
2351         {
2352                 Type [] new_args = TypeManager.GetArgumentTypes (new_method);
2353                 
2354                 foreach (MethodBase method in array) {
2355                         if (method.Name != new_method.Name)
2356                                 continue;
2357
2358                         if (method is MethodInfo && new_method is MethodInfo)
2359                                 if (((MethodInfo) method).ReturnType != ((MethodInfo) new_method).ReturnType)
2360                                         continue;
2361
2362                         
2363                         Type [] old_args = TypeManager.GetArgumentTypes (method);
2364                         int old_count = old_args.Length;
2365                         int i;
2366                         
2367                         if (new_args.Length != old_count)
2368                                 continue;
2369                         
2370                         for (i = 0; i < old_count; i++){
2371                                 if (old_args [i] != new_args [i])
2372                                         break;
2373                         }
2374                         if (i != old_count)
2375                                 continue;
2376
2377                         return true;
2378                 }
2379                 
2380                 return false;
2381         }
2382         
2383         //
2384         // We copy methods from `new_members' into `target_list' if the signature
2385         // for the method from in the new list does not exist in the target_list
2386         //
2387         // The name is assumed to be the same.
2388         //
2389         public static ArrayList CopyNewMethods (ArrayList target_list, IList new_members)
2390         {
2391                 if (target_list == null){
2392                         target_list = new ArrayList ();
2393
2394                         foreach (MemberInfo mi in new_members){
2395                                 if (mi is MethodBase)
2396                                         target_list.Add (mi);
2397                         }
2398                         return target_list;
2399                 }
2400                 
2401                 MemberInfo [] target_array = new MemberInfo [target_list.Count];
2402                 target_list.CopyTo (target_array, 0);
2403                 
2404                 foreach (MemberInfo mi in new_members){
2405                         MethodBase new_method = (MethodBase) mi;
2406                         
2407                         if (!ArrayContainsMethod (target_array, new_method))
2408                                 target_list.Add (new_method);
2409                 }
2410                 return target_list;
2411         }
2412
2413
2414 #region MemberLookup implementation
2415         
2416         //
2417         // Whether we allow private members in the result (since FindMembers
2418         // uses NonPublic for both protected and private), we need to distinguish.
2419         //
2420
2421         static internal bool FilterNone (MemberInfo m, object filter_criteria)
2422         {
2423                 return true;
2424         }
2425
2426         internal class Closure {
2427                 internal bool     private_ok;
2428
2429                 // Who is invoking us and which type is being queried currently.
2430                 internal Type     invocation_type;
2431                 internal Type     qualifier_type;
2432
2433                 // The assembly that defines the type is that is calling us
2434                 internal Assembly invocation_assembly;
2435                 internal IList almost_match;
2436
2437                 private bool CheckValidFamilyAccess (bool is_static, MemberInfo m)
2438                 {
2439                         if (invocation_type == null)
2440                                 return false;
2441
2442                         if (is_static && qualifier_type == null)
2443                                 // It resolved from a simple name, so it should be visible.
2444                                 return true;
2445
2446                         // A nested class has access to all the protected members visible to its parent.
2447                         if (qualifier_type != null && TypeManager.IsNestedChildOf (invocation_type, qualifier_type))
2448                                 return true;
2449
2450                         if (invocation_type == m.DeclaringType || invocation_type.IsSubclassOf (m.DeclaringType)) {
2451                                 // Although a derived class can access protected members of its base class
2452                                 // it cannot do so through an instance of the base class (CS1540).
2453                                 // => Ancestry should be: declaring_type ->* invocation_type ->*  qualified_type
2454                                 if (is_static ||
2455                                     qualifier_type == null ||
2456                                     qualifier_type == invocation_type ||
2457                                     qualifier_type.IsSubclassOf (invocation_type))
2458                                         return true;
2459                         }
2460
2461                         if (!is_static && almost_match != null)
2462                                 almost_match.Add (m);
2463
2464                         return false;
2465                 }
2466                 
2467                 //
2468                 // This filter filters by name + whether it is ok to include private
2469                 // members in the search
2470                 //
2471                 internal bool Filter (MemberInfo m, object filter_criteria)
2472                 {
2473                         //
2474                         // Hack: we know that the filter criteria will always be in the `closure'
2475                         // fields. 
2476                         //
2477
2478                         if ((filter_criteria != null) && (m.Name != (string) filter_criteria))
2479                                 return false;
2480                         
2481                         if (((qualifier_type == null) || (qualifier_type == invocation_type)) &&
2482                             (m.DeclaringType == invocation_type))
2483                                 return true;
2484                         
2485                         //
2486                         // Ugly: we need to find out the type of `m', and depending
2487                         // on this, tell whether we accept or not
2488                         //
2489                         if (m is MethodBase){
2490                                 MethodBase mb = (MethodBase) m;
2491                                 MethodAttributes ma = mb.Attributes & MethodAttributes.MemberAccessMask;
2492
2493                                 if (ma == MethodAttributes.Private)
2494                                         return private_ok || invocation_type == m.DeclaringType ||
2495                                                 IsNestedChildOf (invocation_type, m.DeclaringType);
2496
2497                                 if (invocation_assembly == mb.DeclaringType.Assembly) {
2498                                         if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamORAssem)
2499                                                 return true;
2500                                 } else {
2501                                         if (ma == MethodAttributes.Assembly || ma == MethodAttributes.FamANDAssem)
2502                                                 return false;
2503                                 }
2504
2505                                 if (ma == MethodAttributes.Family ||
2506                                     ma == MethodAttributes.FamANDAssem ||
2507                                     ma == MethodAttributes.FamORAssem)
2508                                         return CheckValidFamilyAccess (mb.IsStatic, m);
2509                                 
2510                                 // Public.
2511                                 return true;
2512                         }
2513                         
2514                         if (m is FieldInfo){
2515                                 FieldInfo fi = (FieldInfo) m;
2516                                 FieldAttributes fa = fi.Attributes & FieldAttributes.FieldAccessMask;
2517                                 
2518                                 if (fa == FieldAttributes.Private)
2519                                         return private_ok || (invocation_type == m.DeclaringType) ||
2520                                                 IsNestedChildOf (invocation_type, m.DeclaringType);
2521
2522                                 if (invocation_assembly == fi.DeclaringType.Assembly) {
2523                                         if (fa == FieldAttributes.Assembly || fa == FieldAttributes.FamORAssem)
2524                                                 return true;
2525                                 } else {
2526                                         if (fa == FieldAttributes.Assembly || fa == FieldAttributes.FamANDAssem)
2527                                                 return false;
2528                                 }
2529
2530                                 if (fa == FieldAttributes.Family ||
2531                                     fa == FieldAttributes.FamANDAssem ||
2532                                     fa == FieldAttributes.FamORAssem)
2533                                         return CheckValidFamilyAccess (fi.IsStatic, m);
2534                                 
2535                                 // Public.
2536                                 return true;
2537                         }
2538                         
2539                         //
2540                         // EventInfos and PropertyInfos, return true because they lack permission
2541                         // information, so we need to check later on the methods.
2542                         //
2543                         return true;
2544                 }
2545         }
2546
2547         static Closure closure = new Closure ();
2548         static MemberFilter FilterWithClosure_delegate = new MemberFilter (closure.Filter);
2549
2550         //
2551         // Looks up a member called `name' in the `queried_type'.  This lookup
2552         // is done by code that is contained in the definition for `invocation_type'
2553         // through a qualifier of type `qualifier_type' (or null if there is no qualifier).
2554         //
2555         // `invocation_type' is used to check whether we're allowed to access the requested
2556         // member wrt its protection level.
2557         //
2558         // When called from MemberAccess, `qualifier_type' is the type which is used to access
2559         // the requested member (`class B { A a = new A (); a.foo = 5; }'; here invocation_type
2560         // is B and qualifier_type is A).  This is used to do the CS1540 check.
2561         //
2562         // When resolving a SimpleName, `qualifier_type' is null.
2563         //
2564         // The `qualifier_type' is used for the CS1540 check; it's normally either null or
2565         // the same than `queried_type' - except when we're being called from BaseAccess;
2566         // in this case, `invocation_type' is the current type and `queried_type' the base
2567         // type, so this'd normally trigger a CS1540.
2568         //
2569         // The binding flags are `bf' and the kind of members being looked up are `mt'
2570         //
2571         // The return value always includes private members which code in `invocation_type'
2572         // is allowed to access (using the specified `qualifier_type' if given); only use
2573         // BindingFlags.NonPublic to bypass the permission check.
2574         //
2575         // The 'almost_match' argument is used for reporting error CS1540.
2576         //
2577         // Returns an array of a single element for everything but Methods/Constructors
2578         // that might return multiple matches.
2579         //
2580         public static MemberInfo [] MemberLookup (Type invocation_type, Type qualifier_type,
2581                                                   Type queried_type,  MemberTypes mt,
2582                                                   BindingFlags original_bf, string name, IList almost_match)
2583         {
2584                 Timer.StartTimer (TimerType.MemberLookup);
2585
2586                 MemberInfo[] retval = RealMemberLookup (invocation_type, qualifier_type,
2587                                                         queried_type, mt, original_bf, name, almost_match);
2588
2589                 Timer.StopTimer (TimerType.MemberLookup);
2590
2591                 return retval;
2592         }
2593
2594         static MemberInfo [] RealMemberLookup (Type invocation_type, Type qualifier_type,
2595                                                Type queried_type, MemberTypes mt,
2596                                                BindingFlags original_bf, string name, IList almost_match)
2597         {
2598                 BindingFlags bf = original_bf;
2599                 
2600                 ArrayList method_list = null;
2601                 Type current_type = queried_type;
2602                 bool searching = (original_bf & BindingFlags.DeclaredOnly) == 0;
2603                 bool skip_iface_check = true, used_cache = false;
2604                 bool always_ok_flag = false;
2605
2606                 closure.invocation_type = invocation_type;
2607                 closure.invocation_assembly = invocation_type != null ? invocation_type.Assembly : null;
2608                 closure.qualifier_type = qualifier_type;
2609                 closure.almost_match = almost_match;
2610
2611                 //
2612                 // If we are a nested class, we always have access to our container
2613                 // type names
2614                 //
2615                 if (invocation_type != null){
2616                         string invocation_name = invocation_type.FullName;
2617                         if (invocation_name.IndexOf ('+') != -1){
2618                                 string container = queried_type.FullName + "+";
2619                                 int container_length = container.Length;
2620
2621                                 if (invocation_name.Length > container_length){
2622                                         string shared = invocation_name.Substring (0, container_length);
2623                                 
2624                                         if (shared == container)
2625                                                 always_ok_flag = true;
2626                                 }
2627                         }
2628                 }
2629                 
2630                 // This is from the first time we find a method
2631                 // in most cases, we do not actually find a method in the base class
2632                 // so we can just ignore it, and save the arraylist allocation
2633                 MemberInfo [] first_members_list = null;
2634                 bool use_first_members_list = false;
2635                 
2636                 do {
2637                         MemberInfo [] list;
2638
2639                         //
2640                         // `NonPublic' is lame, because it includes both protected and
2641                         // private methods, so we need to control this behavior by
2642                         // explicitly tracking if a private method is ok or not.
2643                         //
2644                         // The possible cases are:
2645                         //    public, private and protected (internal does not come into the
2646                         //    equation)
2647                         //
2648                         if ((invocation_type != null) &&
2649                             ((invocation_type == current_type) ||
2650                              IsNestedChildOf (invocation_type, current_type)) ||
2651                             always_ok_flag)
2652                                 bf = original_bf | BindingFlags.NonPublic;
2653                         else
2654                                 bf = original_bf;
2655
2656                         closure.private_ok = (original_bf & BindingFlags.NonPublic) != 0;
2657
2658                         Timer.StopTimer (TimerType.MemberLookup);
2659
2660                         list = MemberLookup_FindMembers (current_type, mt, bf, name, out used_cache);
2661
2662                         Timer.StartTimer (TimerType.MemberLookup);
2663
2664                         //
2665                         // When queried for an interface type, the cache will automatically check all
2666                         // inherited members, so we don't need to do this here.  However, this only
2667                         // works if we already used the cache in the first iteration of this loop.
2668                         //
2669                         // If we used the cache in any further iteration, we can still terminate the
2670                         // loop since the cache always looks in all base classes.
2671                         //
2672
2673                         if (used_cache)
2674                                 searching = false;
2675                         else
2676                                 skip_iface_check = false;
2677
2678                         if (current_type == TypeManager.object_type)
2679                                 searching = false;
2680                         else {
2681                                 current_type = current_type.BaseType;
2682                                 
2683                                 //
2684                                 // This happens with interfaces, they have a null
2685                                 // basetype.  Look members up in the Object class.
2686                                 //
2687                                 if (current_type == null) {
2688                                         current_type = TypeManager.object_type;
2689                                         searching = true;
2690                                 }
2691                         }
2692                         
2693                         if (list.Length == 0)
2694                                 continue;
2695
2696                         //
2697                         // Events and types are returned by both `static' and `instance'
2698                         // searches, which means that our above FindMembers will
2699                         // return two copies of the same.
2700                         //
2701                         if (list.Length == 1 && !(list [0] is MethodBase)){
2702                                 return list;
2703                         }
2704
2705                         //
2706                         // Multiple properties: we query those just to find out the indexer
2707                         // name
2708                         //
2709                         if (list [0] is PropertyInfo)
2710                                 return list;
2711
2712                         //
2713                         // We found an event: the cache lookup returns both the event and
2714                         // its private field.
2715                         //
2716                         if (list [0] is EventInfo) {
2717                                 if ((list.Length == 2) && (list [1] is FieldInfo))
2718                                         return new MemberInfo [] { list [0] };
2719
2720                                 // Oooops
2721                                 return null;
2722                         }
2723
2724                         //
2725                         // We found methods, turn the search into "method scan"
2726                         // mode.
2727                         //
2728
2729                         if (first_members_list != null) {
2730                                 if (use_first_members_list) {
2731                                         method_list = CopyNewMethods (method_list, first_members_list);
2732                                         use_first_members_list = false;
2733                                 }
2734                                 
2735                                 method_list = CopyNewMethods (method_list, list);
2736                         } else {
2737                                 first_members_list = list;
2738                                 use_first_members_list = true;
2739                                 mt &= (MemberTypes.Method | MemberTypes.Constructor);
2740                         }
2741                 } while (searching);
2742                 
2743                 if (use_first_members_list) {
2744                         foreach (MemberInfo mi in first_members_list) {
2745                                 if (! (mi is MethodBase)) {
2746                                         method_list = CopyNewMethods (method_list, first_members_list);
2747                                         return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
2748                                 }
2749                         }
2750                         return (MemberInfo []) first_members_list;
2751                 }
2752
2753                 if (method_list != null && method_list.Count > 0)
2754                         return (MemberInfo []) method_list.ToArray (typeof (MemberInfo));
2755                 
2756                 //
2757                 // This happens if we already used the cache in the first iteration, in this case
2758                 // the cache already looked in all interfaces.
2759                 //
2760                 if (skip_iface_check)
2761                         return null;
2762
2763                 //
2764                 // Interfaces do not list members they inherit, so we have to
2765                 // scan those.
2766                 // 
2767                 if (!queried_type.IsInterface)
2768                         return null;
2769
2770                 if (queried_type.IsArray)
2771                         queried_type = TypeManager.array_type;
2772                 
2773                 Type [] ifaces = GetInterfaces (queried_type);
2774                 if (ifaces == null)
2775                         return null;
2776                 
2777                 foreach (Type itype in ifaces){
2778                         MemberInfo [] x;
2779
2780                         x = MemberLookup (null, null, itype, mt, bf, name, null);
2781                         if (x != null)
2782                                 return x;
2783                 }
2784                                         
2785                 return null;
2786         }
2787
2788         // Tests whether external method is really special
2789         public static bool IsSpecialMethod (MethodBase mb)
2790         {
2791                 string name = mb.Name;
2792                 if (name.StartsWith ("get_") || name.StartsWith ("set_"))
2793                         return mb.DeclaringType.GetProperty (name.Substring (4)) != null;
2794
2795                 if (name.StartsWith ("add_"))
2796                         return mb.DeclaringType.GetEvent (name.Substring (4)) != null;
2797
2798                 if (name.StartsWith ("remove_"))
2799                         return mb.DeclaringType.GetEvent (name.Substring (7)) != null;
2800
2801                 if (name.StartsWith ("op_")){
2802                         foreach (string oname in Unary.oper_names) {
2803                                 if (oname == name)
2804                                         return true;
2805                         }
2806                 
2807                         foreach (string oname in Binary.oper_names) {
2808                                 if (oname == name)
2809                                         return true;
2810                         }
2811                 }
2812                 return false;
2813         }
2814                 
2815 #endregion
2816         
2817 }
2818
2819 /// <summary>
2820 ///   There is exactly one instance of this class per type.
2821 /// </summary>
2822 public sealed class TypeHandle : IMemberContainer {
2823         public readonly IMemberContainer BaseType;
2824
2825         readonly int id = ++next_id;
2826         static int next_id = 0;
2827
2828         static TypeHandle ()
2829         {
2830                 Reset ();
2831         }
2832
2833         /// <summary>
2834         ///   Lookup a TypeHandle instance for the given type.  If the type doesn't have
2835         ///   a TypeHandle yet, a new instance of it is created.  This static method
2836         ///   ensures that we'll only have one TypeHandle instance per type.
2837         /// </summary>
2838         private static TypeHandle GetTypeHandle (Type t)
2839         {
2840                 TypeHandle handle = (TypeHandle) type_hash [t];
2841                 if (handle != null)
2842                         return handle;
2843
2844                 handle = new TypeHandle (t);
2845                 type_hash.Add (t, handle);
2846                 return handle;
2847         }
2848
2849         public static MemberCache GetMemberCache (Type t)
2850         {
2851                 return GetTypeHandle (t).MemberCache;
2852         }
2853         
2854         public static void CleanUp ()
2855         {
2856                 type_hash = null;
2857         }
2858
2859         public static void Reset ()
2860         {
2861                 type_hash = new PtrHashtable ();
2862         }
2863
2864         /// <summary>
2865         ///   Returns the TypeHandle for TypeManager.object_type.
2866         /// </summary>
2867         public static IMemberContainer ObjectType {
2868                 get {
2869                         if (object_type != null)
2870                                 return object_type;
2871
2872                         object_type = GetTypeHandle (TypeManager.object_type);
2873
2874                         return object_type;
2875                 }
2876         }
2877
2878         /// <summary>
2879         ///   Returns the TypeHandle for TypeManager.array_type.
2880         /// </summary>
2881         public static IMemberContainer ArrayType {
2882                 get {
2883                         if (array_type != null)
2884                                 return array_type;
2885
2886                         array_type = GetTypeHandle (TypeManager.array_type);
2887
2888                         return array_type;
2889                 }
2890         }
2891
2892         private static PtrHashtable type_hash;
2893
2894         private static TypeHandle object_type = null;
2895         private static TypeHandle array_type = null;
2896
2897         private Type type;
2898         private bool is_interface;
2899         private MemberCache member_cache;
2900         private MemberCache base_cache;
2901
2902         private TypeHandle (Type type)
2903         {
2904                 this.type = type;
2905                 if (type.BaseType != null) {
2906                         base_cache = TypeManager.LookupMemberCache (type.BaseType);
2907                         BaseType = base_cache.Container;
2908                 } else if (type.IsInterface)
2909                         base_cache = TypeManager.LookupBaseInterfacesCache (type);
2910                 this.is_interface = type.IsInterface;
2911                 this.member_cache = new MemberCache (this);
2912         }
2913
2914         // IMemberContainer methods
2915
2916         public string Name {
2917                 get {
2918                         return type.FullName;
2919                 }
2920         }
2921
2922         public Type Type {
2923                 get {
2924                         return type;
2925                 }
2926         }
2927
2928         public MemberCache BaseCache {
2929                 get {
2930                         return base_cache;
2931                 }
2932         }
2933
2934         public bool IsInterface {
2935                 get {
2936                         return is_interface;
2937                 }
2938         }
2939
2940         public MemberList GetMembers (MemberTypes mt, BindingFlags bf)
2941         {
2942                 MemberInfo [] members;
2943                 if (mt == MemberTypes.Event)
2944                         members = type.GetEvents (bf | BindingFlags.DeclaredOnly);
2945                 else
2946                         members = type.FindMembers (mt, bf | BindingFlags.DeclaredOnly,
2947                                                     null, null);
2948                 Array.Reverse (members);
2949
2950                 return new MemberList (members);
2951         }
2952
2953         // IMemberFinder methods
2954
2955         public MemberList FindMembers (MemberTypes mt, BindingFlags bf, string name,
2956                                        MemberFilter filter, object criteria)
2957         {
2958                 return new MemberList (member_cache.FindMembers (mt, bf, name, filter, criteria));
2959         }
2960
2961         public MemberCache MemberCache {
2962                 get {
2963                         return member_cache;
2964                 }
2965         }
2966
2967         public override string ToString ()
2968         {
2969                 if (BaseType != null)
2970                         return "TypeHandle (" + id + "," + Name + " : " + BaseType + ")";
2971                 else
2972                         return "TypeHandle (" + id + "," + Name + ")";
2973         }
2974 }
2975
2976 }