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