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