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