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