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